repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/util/bindingadapters/ToolbarBindingAdapters.kt
1
2183
package sk.styk.martin.apkanalyzer.util.bindingadapters import android.widget.SearchView import androidx.annotation.MenuRes import androidx.annotation.StringRes import androidx.appcompat.graphics.drawable.DrawerArrowDrawable import androidx.appcompat.widget.Toolbar import androidx.databinding.BindingAdapter import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.util.TextInfo import sk.styk.martin.apkanalyzer.views.toolbar.NavigationIconState @BindingAdapter("navigationIconState") fun Toolbar.navigationIconState(iconState: NavigationIconState) { navigationIcon = when (iconState) { NavigationIconState.NONE -> null NavigationIconState.ARROW -> DrawerArrowDrawable(context).apply { progress = 1f } NavigationIconState.HAMBURGER -> DrawerArrowDrawable(context).apply { progress = 0f } } } @BindingAdapter("inflateMenu") fun Toolbar.inflateMenu(@MenuRes menuResId: Int) { menu.clear() if (menuResId != 0) { inflateMenu(menuResId) } } @BindingAdapter("onQueryTextListener") fun Toolbar.searchOnQueryTextListener(onQueryTextListener: SearchView.OnQueryTextListener) { val searchView = menu.findItem(R.id.action_search).actionView as? SearchView ?: return searchView.setOnQueryTextListener(onQueryTextListener) } @BindingAdapter("onSearchCloseListener") fun Toolbar.onSearchCloseListener(onCloseListener: SearchView.OnCloseListener) { val searchView = menu.findItem(R.id.action_search)?.actionView as? SearchView ?: return searchView.setOnCloseListener(onCloseListener) } @BindingAdapter("searchHint") fun Toolbar.searchHint(@StringRes searchHint: Int) { val searchView = menu.findItem(R.id.action_search)?.actionView as? SearchView ?: return searchView.queryHint = context.getString(searchHint) } @BindingAdapter("searchQuery") fun Toolbar.searchQuery(searchQuery: String?) { val searchView = menu.findItem(R.id.action_search)?.actionView as? SearchView ?: return if (searchView.query != searchQuery) { searchView.setQuery(searchQuery, false) } } @BindingAdapter("title") fun Toolbar.setTitle(textInfo: TextInfo?) { title = textInfo?.getText(context) ?: "" }
gpl-3.0
7e4ce250160e95287dfa623482b2c5aa
35.383333
93
0.775996
4.446029
false
false
false
false
jameshnsears/brexitsoundboard
app/src/androidTest/java/com/github/jameshnsears/brexitsoundboard/espresso/LiamTest.kt
1
2891
package com.github.jameshnsears.brexitsoundboard.espresso import android.view.View import android.view.ViewGroup import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.pressBack import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.scrollTo import androidx.test.espresso.matcher.ViewMatchers.withContentDescription import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.filters.LargeTest import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import androidx.test.rule.ActivityTestRule import com.github.jameshnsears.brexitsoundboard.ActivityBrexitSoundboard import com.github.jameshnsears.brexitsoundboard.R import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf import org.hamcrest.TypeSafeMatcher import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4ClassRunner::class) class LiamTest { @Rule @JvmField var mActivityTestRule = ActivityTestRule(ActivityBrexitSoundboard::class.java) @Test fun liamTest() { // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html Thread.sleep(1000) val appCompatImageButton = onView( allOf( withId(R.id.imageButtonLiam00), withContentDescription("Dr Liam Fox"), childAtPosition( childAtPosition( withId(R.id.linearLayout), 2 ), 0 ) ) ) appCompatImageButton.perform(scrollTo(), click()) // Added a sleep statement to match the app's execution delay. // The recommended way to handle such scenarios is to use Espresso idling resources: // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html Thread.sleep(1000) pressBack() } private fun childAtPosition( parentMatcher: Matcher<View>, position: Int ): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("Child at position $position in parent ") parentMatcher.describeTo(description) } public override fun matchesSafely(view: View): Boolean { val parent = view.parent return parent is ViewGroup && parentMatcher.matches(parent) && view == parent.getChildAt(position) } } } }
apache-2.0
b77b351003fe61d9a7d4e9aa62045cc6
35.1375
108
0.680042
4.967354
false
true
false
false
vicpinm/KPresenterAdapter
library/src/main/java/com/vicpin/kpresenteradapter/model/ViewInfo.kt
1
1170
package com.vicpin.kpresenteradapter.model import android.view.View import com.vicpin.kpresenteradapter.ViewHolder import kotlin.reflect.KClass /** * Created by Victor on 01/11/2016. */ data class ViewInfo<out T: Any>(val viewHolderClass: KClass<out ViewHolder<*>>? = null) { var viewResourceId: Int? = null var view: View? = null constructor(viewHolderClass: KClass<out ViewHolder<T>>? = null, viewResourceId: Int): this(viewHolderClass) { this.viewResourceId = viewResourceId } constructor(viewHolderClass: KClass<out ViewHolder<T>>? = null, view: View): this(viewHolderClass) { this.view = view } fun createViewHolder(view: View): ViewHolder<*> { return if (viewHolderClass != null) { try { viewHolderClass.java.getConstructor(View::class.java).newInstance(view) } catch (ex: Exception) { throw ex } } else { object : ViewHolder<T>(view) { override val containerView = view override val presenter = null } } } }
apache-2.0
d51d41a4918f9e3bb4b110a79da2b1f8
24.590909
113
0.589744
4.661355
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/settings/currency/DisplayCurrencyHandler.kt
1
4727
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 1/7/20. * Copyright (c) 2020 breadwallet LLC * * 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.breadwallet.ui.settings.currency import android.content.Context import com.breadwallet.R import com.breadwallet.logger.logError import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.manager.BRSharedPrefs.putPreferredFiatIso import com.breadwallet.tools.manager.COINGECKO_API_URL import com.breadwallet.ui.settings.currency.DisplayCurrency.E import com.breadwallet.ui.settings.currency.DisplayCurrency.F import drewcarlson.mobius.flow.subtypeEffectHandler import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.flow.transform import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request import org.json.JSONArray import org.json.JSONException import java.io.File import java.io.IOException import java.util.Currency import java.util.concurrent.TimeUnit.MILLISECONDS import kotlin.time.days import kotlin.time.toDuration private const val CURRENCIES_URL = "${COINGECKO_API_URL}supported_vs_currencies" private const val FIAT_CURRENCIES_FILENAME = "fiatcurrencies.json" fun createDisplayCurrencyHandler( context: Context, http: OkHttpClient ) = subtypeEffectHandler<F, E> { addFunction<F.SetDisplayCurrency> { putPreferredFiatIso(iso = it.currencyCode) E.OnSelectedCurrencyUpdated(it.currencyCode) } addTransformer<F.LoadCurrencies> { effects -> effects.transform { val selectedCurrency = BRSharedPrefs.getPreferredFiatIso() val localCacheFile = File(context.filesDir, FIAT_CURRENCIES_FILENAME) val fiatCurrencies = if (localCacheFile.exists()) { localCacheFile.readText() } else { context.resources .openRawResource(R.raw.fiatcurrencies) .use { it.reader().readText() } .also { localCacheFile.writeText(it) } }.toFiatCurrencies() emit(E.OnCurrenciesLoaded(selectedCurrency, fiatCurrencies)) if (localCacheFile.isExpired()) { val selected = BRSharedPrefs.getPreferredFiatIso() val updatedCurrencies = http.fetchCurrencies(localCacheFile) emit(E.OnCurrenciesLoaded(selected, updatedCurrencies)) } } } } private fun File.isExpired(): Boolean { return (lastModified() - System.currentTimeMillis()) .toDuration(MILLISECONDS) > 1.days } private fun String.toFiatCurrencies(): List<String> { val jsonArray = try { JSONArray(this) } catch (e: JSONException) { logError("Failed to parse fiat currencies", e, this) JSONArray() } return List(jsonArray.length(), jsonArray::getString).filter { code -> code != null && Currency.getAvailableCurrencies() .any { it.currencyCode.equals(code, true) } } } private suspend fun OkHttpClient.fetchCurrencies(cache: File): List<String> { val request = Request.Builder().url(CURRENCIES_URL).build() val newCurrencies = try { @Suppress("BlockingMethodInNonBlockingContext") withContext(IO) { newCall(request).execute().use { response -> if (response.isSuccessful) response.body?.string() else null } } } catch (e: IOException) { logError("Failed to fetch fiat currencies", e) null } return newCurrencies?.let { data -> cache.writeText(data) data.toFiatCurrencies() } ?: emptyList() }
mit
5234543ad57bbad8f5d4cad0b59b623d
37.754098
81
0.702137
4.549567
false
false
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/game/entity/Weapon.kt
1
1393
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.entity import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.me import com.charlatano.game.netvars.NetVarOffsets.flNextPrimaryAttack import com.charlatano.game.netvars.NetVarOffsets.iClip1 import com.charlatano.utils.extensions.uint typealias Weapon = Long internal fun Weapon.bullets() = csgoEXE.uint(this + iClip1) internal fun Weapon.nextPrimaryAttack() = csgoEXE.float(this + flNextPrimaryAttack).toDouble() internal fun Weapon.canFire(): Boolean { val nextAttack = nextPrimaryAttack() return nextAttack <= 0 || nextAttack < me.time() }
agpl-3.0
e59b03992d6353497707b691896c7914
37.722222
94
0.765973
3.891061
false
false
false
false
hazuki0x0/YuzuBrowser
module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/repository/HideMenuSource.kt
1
3055
/* * 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.bookmark.repository import android.app.Application import android.content.Context import android.util.SparseArray import com.squareup.moshi.Moshi import com.squareup.moshi.Types import jp.hazuki.yuzubrowser.bookmark.overflow.HideMenuType import jp.hazuki.yuzubrowser.bookmark.overflow.MenuType import jp.hazuki.yuzubrowser.bookmark.overflow.model.HideModel import jp.hazuki.yuzubrowser.core.utility.extensions.getOrPut import okio.buffer import okio.sink import okio.source import java.io.File import java.io.IOException import javax.inject.Inject class HideMenuSource @Inject constructor(val application: Application, private val moshi: Moshi) : HideMenuRepository { private val root = application.getDir("bookmark1", Context.MODE_PRIVATE) private val cache = SparseArray<List<HideModel>>(2) override fun getHideMenu(@HideMenuType type: Int): List<HideModel> { return cache.getOrPut(type) { getInternal(getFile(type)) } } override fun saveHideMenu(@HideMenuType type: Int, hides: List<HideModel>) { cache.put(type, hides) saveInternal(getFile(type), hides) } private fun getFile(@HideMenuType type: Int): File { return when (type) { MenuType.SITE -> File(root, SITE) MenuType.FOLDER -> File(root, FOLDER) else -> throw IllegalArgumentException() } } private fun getInternal(file: File): List<HideModel> { val adapter = moshi.adapter<List<HideModel>>(hideListType) if (file.exists()) { try { file.inputStream().source().buffer().use { adapter.fromJson(it)?.let { list -> return list } } } catch (e: IOException) { e.printStackTrace() } } return emptyList() } private fun saveInternal(file: File, hides: List<HideModel>) { val adapter = moshi.adapter<List<HideModel>>(hideListType) try { file.sink().buffer().use { adapter.toJson(it, hides) } } catch (e: IOException) { e.printStackTrace() } } private val hideListType = Types.newParameterizedType(List::class.java, Integer::class.java) companion object { private const val SITE = "hide_menu_site" private const val FOLDER = "hide_menu_folder" } }
apache-2.0
c49b426ba2e0057c11833bfb74142ee1
32.206522
119
0.661211
4.370529
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AddAdBlockDialog.kt
1
4551
/* * 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.adblock.ui.original import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.InputType import android.view.ViewGroup import android.widget.EditText import android.widget.LinearLayout import androidx.fragment.app.DialogFragment import jp.hazuki.yuzubrowser.adblock.R import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlock import jp.hazuki.yuzubrowser.adblock.repository.original.AdBlockManager import jp.hazuki.yuzubrowser.core.utility.extensions.density class AddAdBlockDialog : DialogFragment() { private var listener: OnAdBlockListUpdateListener? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity ?: throw IllegalStateException() val arguments = arguments ?: throw IllegalArgumentException() val params = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) val density = activity.density val marginWidth = (8 * density + 0.5f).toInt() val marginHeight = (16 * density + 0.5f).toInt() params.setMargins(marginWidth, marginHeight, marginWidth, marginHeight) val editText = EditText(activity).apply { layoutParams = params id = android.R.id.edit inputType = InputType.TYPE_CLASS_TEXT setText(arguments.getString(ARG_URL)) } val builder = AlertDialog.Builder(activity).apply { setTitle(arguments.getInt(ARG_TITLE)) setView(editText) setPositiveButton(android.R.string.ok) { _, _ -> val provider = AdBlockManager.getProvider(activity, arguments.getInt(ARG_TYPE)) provider.update(AdBlock(editText.text.toString())) listener!!.onAdBlockListUpdate() } setNegativeButton(android.R.string.cancel, null) } return builder.create() } override fun onAttach(context: Context) { super.onAttach(context) listener = activity as OnAdBlockListUpdateListener } override fun onDetach() { super.onDetach() listener = null } interface OnAdBlockListUpdateListener { fun onAdBlockListUpdate() } companion object { private const val ARG_TYPE = "type" private const val ARG_TITLE = "title" private const val ARG_URL = "url" fun addBackListInstance(url: String?): AddAdBlockDialog { val bundle = Bundle().apply { putInt(ARG_TYPE, 1) putInt(ARG_TITLE, R.string.pref_ad_block_black) putString(ARG_URL, trimUrl(url)) } return newInstance(bundle) } fun addWhiteListInstance(url: String?): AddAdBlockDialog { val bundle = Bundle().apply { putInt(ARG_TYPE, 2) putInt(ARG_TITLE, R.string.pref_ad_block_white) putString(ARG_URL, trimUrl(url)) } return newInstance(bundle) } fun addWhitePageListInstance(url: String?): AddAdBlockDialog { val bundle = Bundle().apply { putInt(ARG_TYPE, 3) putInt(ARG_TITLE, R.string.pref_ad_block_white_page) putString(ARG_URL, trimUrl(url)) } return newInstance(bundle) } private fun trimUrl(url: String?): String? { if (url != null) { val index = url.indexOf("://") if (index > -1) { return url.substring(index + 3) } } return url } private fun newInstance(bundle: Bundle): AddAdBlockDialog { return AddAdBlockDialog().apply { arguments = bundle } } } }
apache-2.0
a1b5cff000d442791db809284369062c
33.218045
95
0.626236
4.725857
false
false
false
false
hazuki0x0/YuzuBrowser
browser/src/main/java/jp/hazuki/yuzubrowser/browser/ActionExecutor.kt
1
62850
/* * Copyright (C) 2017-2021 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.browser import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import android.text.TextUtils import android.view.KeyEvent import android.view.View import android.webkit.CookieManager import android.webkit.URLUtil import android.webkit.WebSettings import android.webkit.WebView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.print.PrintHelper import jp.hazuki.yuzubrowser.adblock.ui.original.AdBlockActivity import jp.hazuki.yuzubrowser.adblock.ui.original.AddAdBlockDialog import jp.hazuki.yuzubrowser.bookmark.view.BookmarkActivity import jp.hazuki.yuzubrowser.core.utility.extensions.clipboardText import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.core.utility.utils.ImageUtils import jp.hazuki.yuzubrowser.core.utility.utils.ui import jp.hazuki.yuzubrowser.download.core.data.DownloadFile import jp.hazuki.yuzubrowser.download.core.data.DownloadRequest import jp.hazuki.yuzubrowser.download.download import jp.hazuki.yuzubrowser.download.getBlobDownloadJavaScript import jp.hazuki.yuzubrowser.download.getDownloadFolderUri import jp.hazuki.yuzubrowser.download.getImage import jp.hazuki.yuzubrowser.download.ui.DownloadListActivity import jp.hazuki.yuzubrowser.download.ui.FastDownloadActivity import jp.hazuki.yuzubrowser.download.ui.fragment.DownloadDialog import jp.hazuki.yuzubrowser.download.ui.fragment.SaveWebArchiveDialog import jp.hazuki.yuzubrowser.favicon.FaviconManager import jp.hazuki.yuzubrowser.history.presenter.BrowserHistoryActivity import jp.hazuki.yuzubrowser.legacy.Constants import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.item.* import jp.hazuki.yuzubrowser.legacy.action.item.startactivity.StartActivitySingleAction import jp.hazuki.yuzubrowser.legacy.action.manager.ActionController import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.legacy.action.view.ActionListViewAdapter import jp.hazuki.yuzubrowser.legacy.browser.BrowserController import jp.hazuki.yuzubrowser.legacy.browser.BrowserManager import jp.hazuki.yuzubrowser.legacy.browser.Scripts import jp.hazuki.yuzubrowser.legacy.pattern.url.PatternUrlActivity import jp.hazuki.yuzubrowser.legacy.reader.ReaderActivity import jp.hazuki.yuzubrowser.legacy.readitlater.ReadItLaterActivity import jp.hazuki.yuzubrowser.legacy.resblock.ResourceBlockListActivity import jp.hazuki.yuzubrowser.legacy.settings.activity.MainSettingsActivity import jp.hazuki.yuzubrowser.legacy.settings.preference.ClearBrowserDataAlertDialog import jp.hazuki.yuzubrowser.legacy.settings.preference.ProxySettingDialog import jp.hazuki.yuzubrowser.legacy.speeddial.view.SpeedDialSettingActivity import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData import jp.hazuki.yuzubrowser.legacy.useragent.UserAgentListActivity import jp.hazuki.yuzubrowser.legacy.userjs.UserScriptListActivity import jp.hazuki.yuzubrowser.legacy.utils.DisplayUtils import jp.hazuki.yuzubrowser.legacy.utils.WebUtils import jp.hazuki.yuzubrowser.legacy.utils.extensions.setClipboardWithToast import jp.hazuki.yuzubrowser.legacy.webencode.WebTextEncodeListActivity import jp.hazuki.yuzubrowser.legacy.webkit.TabType import jp.hazuki.yuzubrowser.legacy.webkit.handler.* import jp.hazuki.yuzubrowser.search.domain.makeGoogleImageSearch import jp.hazuki.yuzubrowser.ui.BrowserApplication import jp.hazuki.yuzubrowser.ui.dialog.SeekBarDialog import jp.hazuki.yuzubrowser.ui.extensions.decodePunyCodeUrl import jp.hazuki.yuzubrowser.ui.settings.AppPrefs import jp.hazuki.yuzubrowser.ui.utils.PackageUtils import jp.hazuki.yuzubrowser.ui.utils.checkStoragePermission import jp.hazuki.yuzubrowser.ui.utils.makeUrlFromQuery import jp.hazuki.yuzubrowser.ui.widget.ContextMenuTitleView import jp.hazuki.yuzubrowser.webview.CustomWebView import jp.hazuki.yuzubrowser.webview.utility.WebViewUtils import jp.hazuki.yuzubrowser.webview.utility.getUserAgent import jp.hazuki.yuzubrowser.webview.utility.savePictureOverall import jp.hazuki.yuzubrowser.webview.utility.savePicturePart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.IOException class ActionExecutor( private val controller: BrowserController, private val faviconManager: FaviconManager ) : ActionController { override fun run(action: SingleAction, target: ActionController.HitTestResultTargetInfo): Boolean { val result = target.webView.hitTestResult ?: return false val url = result.extra ?: return false when (result.type) { WebView.HitTestResult.SRC_ANCHOR_TYPE -> { when (action.id) { SingleAction.LPRESS_OPEN -> { controller.openInCurrentTab(url) return true } SingleAction.LPRESS_OPEN_NEW -> { controller.openInNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_BG -> { controller.openInBackground(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_NEW_RIGHT -> { controller.openInRightNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_BG_RIGHT -> { controller.openInRightBgTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_SHARE -> { WebUtils.shareWeb(controller.activity, url, null) return true } SingleAction.LPRESS_OPEN_OTHERS -> { controller.activity.startActivity(PackageUtils.createChooser(controller.activity, url, controller.applicationContextInfo.getText(R.string.open_other_app))) return true } SingleAction.LPRESS_COPY_URL -> { controller.applicationContextInfo.setClipboardWithToast(url) return true } SingleAction.LPRESS_SAVE_PAGE_AS -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 1) } else { DownloadDialog(url, target.webView.webSettings.userAgentString)//TODO referer .show() } return true } SingleAction.LPRESS_SAVE_PAGE -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 2) } else { val file = DownloadFile(url, null, DownloadRequest(null, target.webView.webSettings.userAgentString, null)) file.download() } return true } SingleAction.LPRESS_PATTERN_MATCH -> { controller.activity.startActivity(Intent(controller.activity, PatternUrlActivity::class.java).apply { putExtra(Intent.EXTRA_TEXT, url) }) return true } SingleAction.LPRESS_COPY_LINK_TEXT -> { target.webView.requestFocusNodeHref(WebSrcLinkCopyHandler(controller.activity).obtainMessage()) return true } SingleAction.LPRESS_ADD_BLACK_LIST -> { AddAdBlockDialog.addBackListInstance(result.extra) .show(controller.activity.supportFragmentManager, "add black") return true } SingleAction.LPRESS_ADD_WHITE_LIST -> { AddAdBlockDialog.addWhiteListInstance(result.extra) .show(controller.activity.supportFragmentManager, "add white") return true } else -> return run(action, target, null) } } WebView.HitTestResult.IMAGE_TYPE -> { when (action.id) { SingleAction.LPRESS_OPEN_IMAGE -> { controller.openInCurrentTab(url) return true } SingleAction.LPRESS_OPEN_IMAGE_NEW -> { controller.openInNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_BG -> { controller.openInBackground(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_NEW_RIGHT -> { controller.openInRightNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_BG_RIGHT -> { controller.openInRightBgTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_SHARE_IMAGE_URL -> { WebUtils.shareWeb(controller.activity, url, null) return true } SingleAction.LPRESS_OPEN_IMAGE_OTHERS -> { controller.activity.startActivity(PackageUtils.createChooser(controller.activity, url, controller.activity.getText(R.string.open_other_app))) return true } SingleAction.LPRESS_COPY_IMAGE_URL -> { controller.applicationContextInfo.setClipboardWithToast(url) return true } SingleAction.LPRESS_SAVE_IMAGE_AS -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 1) } else { DownloadDialog(url, target.webView.webSettings.userAgentString, target.webView.url, ".jpg") .show() } return true } SingleAction.LPRESS_GOOGLE_IMAGE_SEARCH -> { controller.openInNewTab(url.makeGoogleImageSearch(), TabType.WINDOW) return true } SingleAction.LPRESS_IMAGE_RES_BLOCK -> { controller.activity.startActivity(Intent(controller.activity, ResourceBlockListActivity::class.java).apply { setAction(Constants.intent.ACTION_BLOCK_IMAGE) putExtra(Intent.EXTRA_TEXT, url) }) return true } SingleAction.LPRESS_PATTERN_MATCH -> { controller.activity.startActivity(Intent(controller.activity, PatternUrlActivity::class.java).apply { putExtra(Intent.EXTRA_TEXT, url) }) return true } SingleAction.LPRESS_SHARE_IMAGE -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 3) } else { val intent = FastDownloadActivity.intent( controller.activity, url, target.webView.url, target.webView.getUserAgent(), ".jpg") controller.startActivity(intent, BrowserController.REQUEST_SHARE_IMAGE) } return true } SingleAction.LPRESS_SAVE_IMAGE -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 2) } else { val file = DownloadFile(url, null, DownloadRequest(target.webView.url, target.webView.webView.settings.userAgentString, ".jpg")) file.download() } return true } SingleAction.LPRESS_ADD_IMAGE_BLACK_LIST -> { AddAdBlockDialog.addBackListInstance(url) .show(controller.activity.supportFragmentManager, "add black") return true } SingleAction.LPRESS_ADD_IMAGE_WHITE_LIST -> { AddAdBlockDialog.addWhiteListInstance(url) .show(controller.activity.supportFragmentManager, "add white") return true } else -> return run(action, target, null) } } WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> { when (action.id) { SingleAction.LPRESS_OPEN -> { target.webView.requestFocusNodeHref(WebSrcImageLoadUrlHandler(controller).obtainMessage()) return true } SingleAction.LPRESS_OPEN_NEW -> { target.webView.requestFocusNodeHref(WebSrcImageOpenNewTabHandler(controller).obtainMessage())//TODO check stratActionMode's Nullpo exception return true } SingleAction.LPRESS_OPEN_BG -> { target.webView.requestFocusNodeHref(WebSrcImageOpenBackgroundHandler(controller).obtainMessage()) return true } SingleAction.LPRESS_OPEN_NEW_RIGHT -> { target.webView.requestFocusNodeHref(WebSrcImageOpenRightNewTabHandler(controller).obtainMessage())//TODO check stratActionMode's Nullpo exception return true } SingleAction.LPRESS_OPEN_BG_RIGHT -> { target.webView.requestFocusNodeHref(WebSrcImageOpenRightBgTabHandler(controller).obtainMessage()) return true } SingleAction.LPRESS_SHARE -> { target.webView.requestFocusNodeHref(WebSrcImageShareWebHandler(controller.activity).obtainMessage()) return true } SingleAction.LPRESS_OPEN_OTHERS -> { target.webView.requestFocusNodeHref(WebSrcImageOpenOtherAppHandler(controller.activity).obtainMessage()) return true } SingleAction.LPRESS_COPY_URL -> { target.webView.requestFocusNodeHref(WebSrcImageCopyUrlHandler(controller.applicationContextInfo).obtainMessage()) return true } SingleAction.LPRESS_SAVE_PAGE_AS -> { target.webView.requestFocusNodeHref(WebImageHandler(controller.activity, target.webView.webSettings.userAgentString ?: WebSettings.getDefaultUserAgent(controller.applicationContextInfo)).obtainMessage()) return true } SingleAction.LPRESS_OPEN_IMAGE -> { controller.openInCurrentTab(url) return true } SingleAction.LPRESS_OPEN_IMAGE_NEW -> { controller.openInNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_BG -> { controller.openInBackground(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_NEW_RIGHT -> { controller.openInRightNewTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_OPEN_IMAGE_BG_RIGHT -> { controller.openInRightBgTab(url, TabType.WINDOW) return true } SingleAction.LPRESS_SHARE_IMAGE_URL -> { WebUtils.shareWeb(controller.activity, url, null) return true } SingleAction.LPRESS_OPEN_IMAGE_OTHERS -> { controller.activity.startActivity(PackageUtils.createChooser(controller.activity, url, controller.activity.getText(R.string.open_other_app))) return true } SingleAction.LPRESS_COPY_IMAGE_URL -> { controller.applicationContextInfo.setClipboardWithToast(url) return true } SingleAction.LPRESS_SAVE_IMAGE_AS -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 1) } else { DownloadDialog(url, target.webView.webSettings.userAgentString, target.webView.url, ".jpg") .show() } return true } SingleAction.LPRESS_GOOGLE_IMAGE_SEARCH -> { controller.openInNewTab(url.makeGoogleImageSearch(), TabType.WINDOW) return true } SingleAction.LPRESS_IMAGE_RES_BLOCK -> { controller.activity.startActivity(Intent(controller.activity, ResourceBlockListActivity::class.java).apply { setAction(Constants.intent.ACTION_BLOCK_IMAGE) putExtra(Intent.EXTRA_TEXT, url) }) return true } SingleAction.LPRESS_PATTERN_MATCH -> { controller.activity.startActivity(Intent(controller.activity, PatternUrlActivity::class.java).apply { putExtra(Intent.EXTRA_TEXT, url) }) return true } SingleAction.LPRESS_SHARE_IMAGE -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 3) } else { val webView = target.webView val intent = FastDownloadActivity.intent( controller.activity, url, webView.url, webView.getUserAgent(), ".jpg") controller.startActivity(intent, BrowserController.REQUEST_SHARE_IMAGE) } return true } SingleAction.LPRESS_SAVE_IMAGE -> { if (url.startsWith("blob:")) { target.webView.saveBlob(url, 2) } else { val file = DownloadFile(url, null, DownloadRequest(target.webView.url, target.webView.webView.settings.userAgentString, ".jpg")) file.download() } return true } SingleAction.LPRESS_ADD_BLACK_LIST -> { target.webView.requestFocusNodeHref(WebSrcImageBlackListHandler(controller.activity).obtainMessage()) return true } SingleAction.LPRESS_ADD_IMAGE_BLACK_LIST -> { AddAdBlockDialog.addBackListInstance(url) .show(controller.activity.supportFragmentManager, "add black") return true } SingleAction.LPRESS_ADD_WHITE_LIST -> { target.webView.requestFocusNodeHref(WebSrcImageWhiteListHandler(controller.activity).obtainMessage()) AddAdBlockDialog.addWhiteListInstance(url) .show(controller.activity.supportFragmentManager, "add white") return true } SingleAction.LPRESS_ADD_IMAGE_WHITE_LIST -> { AddAdBlockDialog.addWhiteListInstance(url).show(controller.activity.supportFragmentManager, "add white") return true } else -> return run(action, target, null) } } } return false } override fun run(action: SingleAction, target: ActionController.TargetInfo?, button: View?): Boolean { val actionTarget = if (target != null && target.target >= 0) target.target else controller.tabManager.currentTabNo if (actionTarget < 0 || actionTarget >= controller.tabSize) { return false } when (action.id) { SingleAction.GO_BACK -> { val tab = controller.getTab(actionTarget) if (tab.mWebView.canGoBack()) { if (tab.isNavLock) { val item = tab.mWebView.copyMyBackForwardList().prev if (item != null) { performNewTabLink(BrowserManager.LOAD_URL_TAB_NEW_RIGHT, tab, item.url, TabType.WINDOW) return true } } tab.mWebView.goBack() controller.superFrameLayoutInfo.postDelayed(takeCurrentTabScreen, 500) controller.superFrameLayoutInfo.postDelayed(paddingReset, 50) } else { checkAndRun((action as GoBackSingleAction).defaultAction, target) } } SingleAction.GO_FORWARD -> { val tab = controller.getTab(actionTarget) if (tab.mWebView.canGoForward()) { if (tab.isNavLock) { val item = tab.mWebView.copyMyBackForwardList().next if (item != null) { performNewTabLink(BrowserManager.LOAD_URL_TAB_NEW_RIGHT, tab, item.url, TabType.WINDOW) return true } } tab.mWebView.goForward() controller.superFrameLayoutInfo.postDelayed(takeCurrentTabScreen, 500) controller.superFrameLayoutInfo.postDelayed(paddingReset, 50) } } SingleAction.WEB_RELOAD_STOP -> { val tab = controller.getTab(actionTarget) if (tab.isInPageLoad) tab.mWebView.stopLoading() else tab.mWebView.reload() } SingleAction.WEB_RELOAD -> controller.getTab(actionTarget).mWebView.reload() SingleAction.WEB_STOP -> controller.getTab(actionTarget).mWebView.stopLoading() SingleAction.GO_HOME -> controller.loadUrl(controller.getTab(actionTarget), AppPrefs.home_page.get()) SingleAction.ZOOM_IN -> controller.getTab(actionTarget).mWebView.zoomIn() SingleAction.ZOOM_OUT -> controller.getTab(actionTarget).mWebView.zoomOut() SingleAction.PAGE_UP -> controller.getTab(actionTarget).mWebView.pageUp(false) SingleAction.PAGE_DOWN -> controller.getTab(actionTarget).mWebView.pageDown(false) SingleAction.PAGE_TOP -> controller.getTab(actionTarget).mWebView.pageUp(true) SingleAction.PAGE_BOTTOM -> controller.getTab(actionTarget).mWebView.pageDown(true) SingleAction.PAGE_SCROLL -> (action as WebScrollSingleAction).scrollWebView(controller.applicationContextInfo, controller.getTab(actionTarget).mWebView) SingleAction.PAGE_FAST_SCROLL -> { if (controller.isEnableFastPageScroller) { controller.closeFastPageScroller() } else { controller.showFastPageScroller(actionTarget) } } SingleAction.PAGE_AUTO_SCROLL -> { if (controller.isEnableAutoScroll) { controller.stopAutoScroll() } else { controller.startAutoScroll(actionTarget, action as AutoPageScrollAction) } } SingleAction.FOCUS_UP -> { controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP)) controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP)) } SingleAction.FOCUS_DOWN -> { controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN)) controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN)) } SingleAction.FOCUS_LEFT -> { controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)) controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)) } SingleAction.FOCUS_RIGHT -> { controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)) controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT)) } SingleAction.FOCUS_CLICK -> { controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER)) controller.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER)) } SingleAction.TOGGLE_JS -> { val web = controller.getTab(actionTarget).mWebView val to = !web.webSettings.javaScriptEnabled Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() web.webSettings.javaScriptEnabled = to web.reload() } SingleAction.TOGGLE_IMAGE -> { val web = controller.getTab(actionTarget).mWebView val to = !web.webSettings.loadsImagesAutomatically Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() web.webSettings.loadsImagesAutomatically = to web.reload() } SingleAction.TOGGLE_COOKIE -> { val cookie = !AppPrefs.accept_cookie.get() AppPrefs.accept_cookie.set(cookie) AppPrefs.commit(controller.applicationContextInfo, AppPrefs.accept_cookie) CookieManager.getInstance().setAcceptCookie(cookie) Toast.makeText(controller.applicationContextInfo, if (cookie) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() } SingleAction.TOGGLE_USERJS -> { val to = !controller.isEnableUserScript controller.isEnableUserScript = to Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() } SingleAction.TOGGLE_NAV_LOCK -> { val tab = controller.getTab(actionTarget) tab.isNavLock = !tab.isNavLock tab.invalidateView(actionTarget == controller.currentTabNo, controller.resourcesByInfo, controller.themeByInfo) controller.notifyChangeWebState()//icon change } SingleAction.PAGE_INFO -> { val tab = controller.getTab(actionTarget) val v = View.inflate(controller.activity, R.layout.page_info_dialog, null) val titleTextView: TextView = v.findViewById(R.id.titleTextView) val urlTextView: TextView = v.findViewById(R.id.urlTextView) titleTextView.text = tab.title val url = tab.url urlTextView.text = url.decodePunyCodeUrl() urlTextView.setOnLongClickListener { controller.applicationContextInfo.setClipboardWithToast(url) true } AlertDialog.Builder(controller.activity) .setTitle(R.string.page_info) .setView(v) .setPositiveButton(android.R.string.ok, null) .show() } SingleAction.COPY_URL -> controller.applicationContextInfo.setClipboardWithToast(controller.getTab(actionTarget).url) SingleAction.COPY_TITLE -> controller.applicationContextInfo.setClipboardWithToast(controller.getTab(actionTarget).title) SingleAction.COPY_TITLE_URL -> { val tab = controller.getTab(actionTarget) val url = tab.url val title = tab.title when { url == null -> controller.applicationContextInfo.setClipboardWithToast(title) title == null -> controller.applicationContextInfo.setClipboardWithToast(url) else -> controller.applicationContextInfo.setClipboardWithToast("$title $url") } } SingleAction.TAB_HISTORY -> controller.showTabHistory(actionTarget) SingleAction.MOUSE_POINTER -> { if (controller.isEnableMousePointer) { controller.closeMousePointer() } else { controller.showMousePointer((action as MousePointerSingleAction).isBackFinish) } } SingleAction.FIND_ON_PAGE -> { if (controller.isEnableFindOnPage) { controller.isEnableFindOnPage = false } else { controller.setEnableFindOnPage(true, (action as FindOnPageAction).isAutoClose) } } SingleAction.SAVE_SCREENSHOT -> { val saveSsAction = action as SaveScreenshotSingleAction val fileName = "ss_${System.currentTimeMillis()}" val type = saveSsAction.type try { when (type) { SaveScreenshotSingleAction.SS_TYPE_ALL -> { if (controller.getTab(actionTarget).mWebView.savePictureOverall(fileName)) Toast.makeText(controller.applicationContextInfo, R.string.saved_file, Toast.LENGTH_SHORT).show() else Toast.makeText(controller.applicationContextInfo, R.string.failed, Toast.LENGTH_SHORT).show() } SaveScreenshotSingleAction.SS_TYPE_PART -> { if (controller.getTab(actionTarget).mWebView.savePicturePart(fileName)) Toast.makeText(controller.applicationContextInfo, getString(R.string.saved_file), Toast.LENGTH_SHORT).show() else Toast.makeText(controller.applicationContextInfo, R.string.failed, Toast.LENGTH_SHORT).show() } else -> Toast.makeText(controller.applicationContextInfo, "Unknown screenshot type : $type", Toast.LENGTH_LONG).show() } } catch (e: IOException) { ErrorReport.printAndWriteLog(e) Toast.makeText(controller.applicationContextInfo, "IOException : " + e.message, Toast.LENGTH_LONG).show() } } SingleAction.SHARE_SCREENSHOT -> { val file = File(controller.activity.externalCacheDir, "ss_" + System.currentTimeMillis() + ".png") val type = (action as ShareScreenshotSingleAction).type try { var result = false when (type) { ShareScreenshotSingleAction.SS_TYPE_ALL -> result = WebViewUtils.savePictureOverall(controller.getTab(actionTarget).mWebView, file) ShareScreenshotSingleAction.SS_TYPE_PART -> result = WebViewUtils.savePicturePart(controller.getTab(actionTarget).mWebView.webView, file) else -> Toast.makeText(controller.applicationContextInfo, "Unknown screenshot type : $type", Toast.LENGTH_LONG).show() } if (result) { val provider = (controller.activity.applicationContext as BrowserApplication) .providerManager.downloadFileProvider val intent = Intent(Intent.ACTION_SEND) intent.type = "image/png" intent.putExtra(Intent.EXTRA_STREAM, provider.getUriForFile(file)) try { controller.activity.startActivity(PackageUtils.createChooser(controller.activity, intent, null)) } catch (e: ActivityNotFoundException) { e.printStackTrace() } } else { Toast.makeText(controller.applicationContextInfo, R.string.failed, Toast.LENGTH_SHORT).show() } } catch (e: IOException) { ErrorReport.printAndWriteLog(e) Toast.makeText(controller.applicationContextInfo, "IOException : " + e.message, Toast.LENGTH_LONG).show() } } SingleAction.SAVE_PAGE -> { val tab = controller.getTab(actionTarget) SaveWebArchiveDialog(controller.activity, tab.url, tab.mWebView, actionTarget) .show(controller.activity.supportFragmentManager, "saveArchive") } SingleAction.OPEN_URL -> { val openUrlAction = action as OpenUrlSingleAction controller.loadUrl(controller.getTab(actionTarget), openUrlAction.url, openUrlAction.targetTab, TabType.WINDOW) } SingleAction.TRANSLATE_PAGE -> { val translateAction = action as TranslatePageSingleAction val tab = controller.getTab(actionTarget) val from = translateAction.translateFrom val to = translateAction.translateTo if (TextUtils.isEmpty(to)) { AlertDialog.Builder(controller.activity) .setItems(R.array.translate_language_list) { _, which -> val to1 = controller.resourcesByInfo.getStringArray(R.array.translate_language_values)[which] val url = URLUtil.composeSearchUrl(tab.url, "http://translate.google.com/translate?sl=${from ?: ""}&tl=$to1&u=%s", "%s") controller.loadUrl(tab, url) } .show() } else { val url = URLUtil.composeSearchUrl(tab.url, "http://translate.google.com/translate?sl=$from&tl=$to&u=%s", "%s") controller.loadUrl(tab, url) } } SingleAction.NEW_TAB -> controller.openInNewTab(AppPrefs.home_page.get(), TabType.DEFAULT) SingleAction.CLOSE_TAB -> if (!controller.removeTab(actionTarget)) { checkAndRun((action as CloseTabSingleAction).defaultAction, target) } SingleAction.CLOSE_ALL -> { controller.openInNewTab(AppPrefs.home_page.get(), TabType.DEFAULT) for (i in controller.tabManager.lastTabNo - 1 downTo 0) { controller.removeTab(i, false) } } SingleAction.CLOSE_OTHERS -> { for (i in controller.tabManager.lastTabNo downTo actionTarget + 1) { controller.removeTab(i, false) } for (i in actionTarget - 1 downTo 0) { controller.removeTab(i, false) } } SingleAction.CLOSE_AUTO_SELECT -> { when (controller.getTab(actionTarget).tabType) { TabType.DEFAULT -> checkAndRun((action as CloseAutoSelectAction).defaultAction, target) TabType.INTENT -> checkAndRun((action as CloseAutoSelectAction).intentAction, target) TabType.WINDOW -> checkAndRun((action as CloseAutoSelectAction).windowAction, target) } } SingleAction.LEFT_TAB -> if (controller.tabManager.isFirst) { if ((action as LeftRightTabSingleAction).isTabLoop) { controller.setCurrentTab(controller.tabManager.lastTabNo) controller.toolbarManager.scrollTabRight() } } else { val to = controller.tabManager.currentTabNo - 1 controller.setCurrentTab(to) controller.toolbarManager.scrollTabTo(to) } SingleAction.RIGHT_TAB -> if (controller.tabManager.isLast) { if ((action as LeftRightTabSingleAction).isTabLoop) { controller.setCurrentTab(0) controller.toolbarManager.scrollTabLeft() } } else { val to = controller.tabManager.currentTabNo + 1 controller.setCurrentTab(to) controller.toolbarManager.scrollTabTo(to) } SingleAction.SWAP_LEFT_TAB -> if (!controller.tabManager.isFirst(actionTarget)) { val to = actionTarget - 1 controller.swapTab(to, actionTarget) controller.toolbarManager.scrollTabTo(to) } SingleAction.SWAP_RIGHT_TAB -> if (!controller.tabManager.isLast(actionTarget)) { val to = actionTarget + 1 controller.swapTab(to, actionTarget) controller.toolbarManager.scrollTabTo(to) } SingleAction.TAB_LIST -> controller.showTabList(action as TabListSingleAction) SingleAction.CLOSE_ALL_LEFT -> for (i in actionTarget - 1 downTo 0) { controller.removeTab(i, false) } SingleAction.CLOSE_ALL_RIGHT -> for (i in controller.tabManager.lastTabNo downTo actionTarget + 1) { controller.removeTab(i, false) } SingleAction.RESTORE_TAB -> controller.restoreTab() SingleAction.REPLICATE_TAB -> controller.openInNewTab(controller.getTab(actionTarget)) SingleAction.SHOW_SEARCHBOX -> controller.showSearchBox( controller.getTab(actionTarget).url ?: "", actionTarget, (action as ShowSearchBoxAction).openNewTabMode, action.isReverse) SingleAction.PASTE_SEARCHBOX -> controller.showSearchBox(controller.applicationContextInfo.clipboardText, actionTarget, (action as PasteSearchBoxAction).openNewTabMode, action.isReverse) SingleAction.PASTE_GO -> { val text = controller.applicationContextInfo.clipboardText if (TextUtils.isEmpty(text)) { Toast.makeText(controller.applicationContextInfo, R.string.clipboard_empty, Toast.LENGTH_SHORT).show() return true } controller.loadUrl(controller.getTab(actionTarget), text.makeUrlFromQuery(AppPrefs.search_url.get(), "%s"), (action as PasteGoSingleAction).targetTab, TabType.WINDOW) } SingleAction.SHOW_BOOKMARK -> { val intent = Intent(controller.applicationContextInfo, BookmarkActivity::class.java) intent.putExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, controller.isFullscreenMode && DisplayUtils.isNeedFullScreenFlag()) intent.putExtra(Constants.intent.EXTRA_MODE_ORIENTATION, controller.requestedOrientationByCtrl) controller.startActivity(intent, BrowserController.REQUEST_BOOKMARK) } SingleAction.SHOW_HISTORY -> { val intent = Intent(controller.applicationContextInfo, BrowserHistoryActivity::class.java) intent.putExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, controller.isFullscreenMode && DisplayUtils.isNeedFullScreenFlag()) intent.putExtra(Constants.intent.EXTRA_MODE_ORIENTATION, controller.requestedOrientationByCtrl) controller.startActivity(intent, BrowserController.REQUEST_HISTORY) } SingleAction.SHOW_DOWNLOADS -> { startActivity(Intent(controller.applicationContextInfo, DownloadListActivity::class.java).apply { putExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, controller.isFullscreenMode && DisplayUtils.isNeedFullScreenFlag()) putExtra(Constants.intent.EXTRA_MODE_ORIENTATION, controller.requestedOrientationByCtrl) }) } SingleAction.SHOW_SETTINGS -> { val intent = Intent(controller.applicationContextInfo, MainSettingsActivity::class.java) controller.startActivity(intent, BrowserController.REQUEST_SETTING) } SingleAction.OPEN_SPEED_DIAL -> controller.loadUrl(controller.getTab(actionTarget), "yuzu:speeddial") SingleAction.ADD_BOOKMARK -> controller.addBookmark(controller.getTab(actionTarget)) SingleAction.ADD_SPEED_DIAL -> { val tab = controller.getTab(actionTarget) startActivity(Intent(controller.activity, SpeedDialSettingActivity::class.java).also { it.action = SpeedDialSettingActivity.ACTION_ADD_SPEED_DIAL it.putExtra(Intent.EXTRA_TITLE, tab.title) it.putExtra(Intent.EXTRA_TEXT, tab.url) it.putExtra(SpeedDialSettingActivity.EXTRA_ICON, ImageUtils.trimSquare(tab.mWebView.favicon, 200)) }) } SingleAction.ADD_PATTERN -> { val tab = controller.getTab(actionTarget) val intent = Intent(controller.activity, PatternUrlActivity::class.java) intent.putExtra(Intent.EXTRA_TEXT, tab.url) startActivity(intent) } SingleAction.ADD_TO_HOME -> { val tab = controller.getTab(actionTarget) tab.mWebView.evaluateJavascript(Scripts.GET_ICON_URL) { val iconUrl = if (it.startsWith('"') && it.endsWith('"')) it.substring(1, it.length - 1) else it createShortCut(tab, iconUrl) } } SingleAction.SUB_GESTURE -> controller.showSubGesture() SingleAction.CLEAR_DATA -> ClearBrowserDataAlertDialog(controller.activity).show(controller.activity.supportFragmentManager) SingleAction.SHOW_PROXY_SETTING -> ProxySettingDialog(controller.activity).show(controller.activity.supportFragmentManager) SingleAction.ORIENTATION_SETTING -> AlertDialog.Builder(controller.activity) .setItems(R.array.pref_oritentation_list ) { _, which -> controller.requestedOrientationByCtrl = controller.resourcesByInfo.getIntArray(R.array.pref_oritentation_values)[which] } .show() SingleAction.OPEN_LINK_SETTING -> AlertDialog.Builder(controller.activity) .setItems(R.array.pref_newtab_list ) { _, which -> AppPrefs.newtab_link.set(controller.resourcesByInfo.getIntArray(R.array.pref_newtab_values)[which]) } .show() SingleAction.USERAGENT_SETTING -> { val uaIntent = Intent(controller.applicationContextInfo, UserAgentListActivity::class.java) uaIntent.putExtra(Intent.EXTRA_TEXT, controller.getTab(actionTarget).mWebView.webSettings.userAgentString) controller.startActivity(uaIntent, BrowserController.REQUEST_USERAGENT) } SingleAction.TEXTSIZE_SETTING -> { val setting = controller.getTab(actionTarget).mWebView.webSettings SeekBarDialog(controller.activity) .setTitle(R.string.pref_text_size) .setSeekMin(1) .setSeekMax(300) .setValue(setting.textZoom) .setPositiveButton(android.R.string.ok) { _, _, value -> setting.textZoom = value } .setNegativeButton(android.R.string.cancel, null) .show() } SingleAction.USERJS_SETTING -> controller.startActivity(Intent(controller.applicationContextInfo, UserScriptListActivity::class.java), BrowserController.REQUEST_USERJS_SETTING) SingleAction.WEB_ENCODE_SETTING -> { val webEncode = Intent(controller.applicationContextInfo, WebTextEncodeListActivity::class.java) webEncode.putExtra(Intent.EXTRA_TEXT, controller.getTab(actionTarget).mWebView.webSettings.defaultTextEncodingName) controller.startActivity(webEncode, BrowserController.REQUEST_WEB_ENCODE_SETTING) } SingleAction.DEFALUT_USERAGENT_SETTING -> { val uaIntent = Intent(controller.applicationContextInfo, UserAgentListActivity::class.java) uaIntent.putExtra(Intent.EXTRA_TEXT, controller.getTab(actionTarget).mWebView.webSettings.userAgentString) controller.startActivity(uaIntent, BrowserController.REQUEST_DEFAULT_USERAGENT) } SingleAction.RENDER_SETTING -> { val builder = AlertDialog.Builder(controller.activity) val mode = controller.getTab(actionTarget).mWebView.renderingMode builder.setTitle(R.string.pref_rendering) .setSingleChoiceItems(R.array.pref_rendering_list, mode) { dialog, which -> dialog.dismiss() controller.applyRenderingMode(controller.getTab(actionTarget), which) } .setNegativeButton(android.R.string.cancel, null) builder.create().show() } SingleAction.RENDER_ALL_SETTING -> { val builder = AlertDialog.Builder(controller.activity) val mode = controller.defaultRenderingMode builder.setTitle(R.string.pref_rendering) .setSingleChoiceItems(R.array.pref_rendering_list, mode) { dialog, which -> dialog.dismiss() controller.defaultRenderingMode = which controller.tabManager.loadedData.forEach { controller.applyRenderingMode(it, which) } } .setNegativeButton(android.R.string.cancel, null) builder.create().show() } SingleAction.TOGGLE_VISIBLE_TAB -> controller.toolbarManager.tabBar.toggleVisibility() SingleAction.TOGGLE_VISIBLE_URL -> controller.toolbarManager.urlBar.toggleVisibility() SingleAction.TOGGLE_VISIBLE_PROGRESS -> controller.toolbarManager.progressBar.toggleVisibility() SingleAction.TOGGLE_VISIBLE_CUSTOM -> controller.toolbarManager.customBar.toggleVisibility() SingleAction.TOGGLE_WEB_TITLEBAR -> controller.toolbarManager.setWebViewTitleBar(controller.tabManager.currentTabData.mWebView, false) SingleAction.TOGGLE_WEB_GESTURE -> controller.isEnableGesture = !controller.isEnableGesture SingleAction.TOGGLE_FLICK -> { val to = !controller.isEnableFlick Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() controller.isEnableFlick = to } SingleAction.TOGGLE_QUICK_CONTROL -> { val to = !controller.isEnableQuickControl Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() controller.isEnableQuickControl = to } SingleAction.TOGGLE_MULTI_FINGER_GESTURE -> { val to = !controller.isEnableMultiFingerGesture Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() controller.isEnableMultiFingerGesture = to } SingleAction.TOGGLE_AD_BLOCK -> { val to = !controller.isEnableAdBlock controller.isEnableAdBlock = to controller.getTab(actionTarget).mWebView.reload() if ((action as WithToastAction).showToast) { Toast.makeText(controller.applicationContextInfo, if (to) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() } } SingleAction.OPEN_BLACK_LIST -> startActivity( Intent(controller.activity, AdBlockActivity::class.java) .setAction(AdBlockActivity.ACTION_OPEN_BLACK)) SingleAction.OPEN_WHITE_LIST -> startActivity( Intent(controller.activity, AdBlockActivity::class.java) .setAction(AdBlockActivity.ACTION_OPEN_WHITE)) SingleAction.OPEN_WHITE_PATE_LIST -> startActivity( Intent(controller.activity, AdBlockActivity::class.java) .setAction(AdBlockActivity.ACTION_OPEN_WHITE_PAGE)) SingleAction.ADD_WHITE_LIST_PAGE -> AddAdBlockDialog.addWhitePageListInstance(controller.getTab(actionTarget).url) .show(controller.activity.supportFragmentManager, "add white page") SingleAction.SHARE_WEB -> { val tab = controller.getTab(actionTarget) WebUtils.shareWeb(controller.activity, tab.url, tab.title) } SingleAction.OPEN_OTHER -> WebUtils.openInOtherApp(controller.activity, controller.getTab(actionTarget).url) SingleAction.START_ACTIVITY -> { val intent = (action as StartActivitySingleAction).getIntent(controller.getTab(actionTarget)) if (intent != null) { try { startActivity(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(controller.activity, R.string.app_notfound, Toast.LENGTH_SHORT).show() } } } SingleAction.TOGGLE_FULL_SCREEN -> controller.isFullscreenMode = !controller.isFullscreenMode SingleAction.OPEN_OPTIONS_MENU -> controller.showMenu(button, action as OpenOptionsMenuAction) SingleAction.CUSTOM_MENU -> { val tab = controller.getTab(actionTarget) val actionList = (action as CustomMenuSingleAction).actionList val builder = AlertDialog.Builder(controller.activity) if (target is ActionController.HitTestResultTargetInfo) { builder.setCustomTitle( ContextMenuTitleView(controller.activity, target.result.extra ?: "")) .setAdapter( ActionListViewAdapter(controller.activity, actionList, target.actionNameArray) ) { _, which -> checkAndRun(actionList[which], target) } } else { builder.setCustomTitle(ContextMenuTitleView(controller.activity, tab.url ?: "")) .setAdapter( ActionListViewAdapter(controller.activity, actionList, null) ) { _, which -> checkAndRun(actionList[which], target) } } builder.show() } SingleAction.FINISH -> { val finishAction = action as FinishSingleAction val closeTabTarget = if (finishAction.isCloseTab) actionTarget else -1 if (finishAction.isShowAlert) controller.finishAlert(closeTabTarget) else controller.finishQuick(closeTabTarget) } SingleAction.MINIMIZE -> controller.moveTaskToBack(true) SingleAction.CUSTOM_ACTION -> return if (target is ActionController.HitTestResultTargetInfo) { run((action as CustomSingleAction).action, target) } else { run((action as CustomSingleAction).action) } SingleAction.VIBRATION -> { val vibrator = controller.activity.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator.vibrate(VibrationEffect.createOneShot( (action as VibrationSingleAction).time.toLong(), VibrationEffect.DEFAULT_AMPLITUDE)) } else { @Suppress("DEPRECATION") vibrator.vibrate((action as VibrationSingleAction).time.toLong()) } } SingleAction.TOAST -> Toast.makeText(controller.applicationContextInfo, (action as ToastAction).text, Toast.LENGTH_SHORT).show() SingleAction.PRIVATE -> { val privateMode = !controller.isPrivateMode controller.isPrivateMode = privateMode if ((action as WithToastAction).showToast) { Toast.makeText(controller.applicationContextInfo, if (privateMode) R.string.toggle_enable else R.string.toggle_disable, Toast.LENGTH_SHORT).show() } } SingleAction.VIEW_SOURCE -> { val webView = controller.getTab(actionTarget).mWebView controller.openInCurrentTab("view-source:" + webView.url) } SingleAction.PRINT -> if (PrintHelper.systemSupportsPrint()) { val tab = controller.getTab(actionTarget) var title = tab.title if (TextUtils.isEmpty(title)) title = tab.mWebView.title if (TextUtils.isEmpty(title)) title = "document" var jobName = tab.url if (TextUtils.isEmpty(jobName)) jobName = "about:blank" val adapter = tab.mWebView.createPrintDocumentAdapter(title) controller.printManager.print(jobName, adapter, null) } else { Toast.makeText(controller.activity, R.string.print_not_support, Toast.LENGTH_SHORT).show() } SingleAction.TAB_PINNING -> { val tab = controller.getTab(actionTarget) tab.isPinning = !tab.isPinning tab.invalidateView(actionTarget == controller.tabManager.currentTabNo, controller.resourcesByInfo, controller.themeByInfo) controller.toolbarManager.notifyChangeWebState()//icon change } SingleAction.ALL_ACTION -> controller.startActivity( ActionActivity.Builder(controller.activity) .setTitle(R.string.action_list) .create() .setAction(ActionActivity.ACTION_ALL_ACTION) .putExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, controller.isFullscreenMode && DisplayUtils.isNeedFullScreenFlag()) .putExtra(Constants.intent.EXTRA_MODE_ORIENTATION, controller.requestedOrientationByCtrl), BrowserController.REQUEST_ACTION_LIST) SingleAction.READER_MODE -> { val tab = controller.getTab(actionTarget) val intent = Intent(controller.activity, ReaderActivity::class.java) intent.putExtra(Constants.intent.EXTRA_URL, tab.originalUrl) intent.putExtra(Constants.intent.EXTRA_USER_AGENT, tab.mWebView.webSettings.userAgentString) intent.putExtra(Constants.intent.EXTRA_MODE_FULLSCREEN, controller.isFullscreenMode && DisplayUtils.isNeedFullScreenFlag()) intent.putExtra(Constants.intent.EXTRA_MODE_ORIENTATION, controller.requestedOrientationByCtrl) startActivity(intent) } SingleAction.READ_IT_LATER -> controller.savePage(controller.getTab(actionTarget)) SingleAction.READ_IT_LATER_LIST -> startActivity(Intent(controller.activity, ReadItLaterActivity::class.java)) SingleAction.WEB_THEME -> { val settings = controller.getTab(actionTarget).mWebView.webSettings AlertDialog.Builder(controller.activity) .setSingleChoiceItems(R.array.pref_web_theme_entries, settings.webTheme) { dialog, which -> settings.webTheme = which dialog.dismiss() } .setNegativeButton(R.string.cancel, null) .show() } else -> { Toast.makeText(controller.applicationContextInfo, "Unknown action:" + action.id, Toast.LENGTH_LONG).show() return false } } return true } private fun CustomWebView.saveBlob(url: String, type: Int) { requireStoragePermission { webView.evaluateJavascript(controller.activity.getBlobDownloadJavaScript(url, controller.secretKey, type), null) } } private fun DownloadDialog.show() { requireStoragePermission { show(controller.activity.supportFragmentManager, "") } } private fun DownloadFile.download() { requireStoragePermission { controller.activity.download(getDownloadFolderUri(controller.applicationContextInfo), this, null) } } private inline fun requireStoragePermission(crossinline block: () -> Unit) { if (controller.applicationContextInfo.checkStoragePermission()) { block() } else { ui { if (controller.requestStoragePermission()) { block() } } } } private fun performNewTabLink(perform: Int, tab: MainTabData, url: String, @TabType type: Int): Boolean { when (perform) { BrowserManager.LOAD_URL_TAB_CURRENT -> { controller.loadUrl(tab, url) return true } BrowserManager.LOAD_URL_TAB_NEW -> { controller.openInNewTab(url, type) return true } BrowserManager.LOAD_URL_TAB_BG -> { controller.openInBackground(url, type) return true } BrowserManager.LOAD_URL_TAB_NEW_RIGHT -> { controller.openInRightNewTab(url, type) return true } BrowserManager.LOAD_URL_TAB_BG_RIGHT -> { controller.openInRightBgTab(url, type) return true } else -> throw IllegalArgumentException("Unknown perform:$perform") } } private val takeCurrentTabScreen = Runnable { val data = controller.tabManager.currentTabData if (data != null && data.isShotThumbnail) controller.tabManager.forceTakeThumbnail(data) } private val paddingReset = Runnable { controller.adjustBrowserPadding(controller.tabManager.currentTabData) } private fun getString(id: Int): String = controller.activity.getString(id) private fun startActivity(intent: Intent) = controller.activity.startActivity(intent) private fun createShortCut(tab: MainTabData, iconUrl: String) = ui { val bitmap = if (iconUrl.isEmpty() || iconUrl == "null") { faviconManager[tab.originalUrl] } else { val userAgent = tab.mWebView.getUserAgent() withContext(Dispatchers.Default) { controller.okHttpClient .getImage(iconUrl, userAgent, tab.url, CookieManager.getInstance().getCookie(tab.url)) } ?: faviconManager[tab.originalUrl] } PackageUtils.createShortcut(controller.activity, tab.title, tab.url, bitmap) } }
apache-2.0
ba4c7d45c18b341e5c2f0bc71be0b93c
54.179982
188
0.575195
5.650962
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/cpu/InstructionDecoder.kt
1
11477
package com.soywiz.kpspemu.cpu import com.soywiz.kmem.* data class InstructionData(var value: Int, var pc: Int) { var lsb: Int get() = value.extract(6, 5); set(v) = run { value = value.insert(v, 6, 5) } var msb: Int get() = value.extract(11, 5); set(v) = run { value = value.insert(v, 11, 5) } var pos: Int get() = value.extract(6, 5); set(v) = run { value = value.insert(v, 6, 5) } var s_imm16: Int get() = value.extract(0, 16) shl 16 shr 16; set(v) = run { value = value.insert(v, 0, 16) } var u_imm16: Int get() = value.extract(0, 16); set(v) = run { value = value.insert(v, 0, 16) } var u_imm26: Int get() = value.extract(0, 26); set(v) = run { value = value.insert(v, 0, 26) } var rd: Int get() = value.extract(11, 5); set(v) = run { value = value.insert(v, 11, 5) } var rt: Int get() = value.extract(16, 5); set(v) = run { value = value.insert(v, 16, 5) } var rs: Int get() = value.extract(21, 5); set(v) = run { value = value.insert(v, 21, 5) } var jump_address get() = u_imm26 * 4; set(v) = run { u_imm26 = v / 4 } } // https://www.cs.umd.edu/users/meesh/411/SimpleMips.htm // http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html // https://electronics.stackexchange.com/questions/28444/mips-pic32-branch-vs-branch-likely open class InstructionDecoder { //val Int.lsb: Int get() = this.extract(6 + 5 * 0, 5) //val Int.msb: Int get() = this.extract(6 + 5 * 1, 5) //val Int.pos: Int get() = this.lsb //val Int.rd: Int get() = this.extract(11 + 5 * 0, 5) //val Int.rt: Int get() = this.extract(11 + 5 * 1, 5) //val Int.rs: Int get() = this.extract(11 + 5 * 2, 5) inline val Int.lsb: Int get() = (this ushr 6) and 0x1F inline val Int.msb: Int get() = (this ushr 11) and 0x1F inline val Int.pos: Int get() = lsb inline val Int.size_e: Int get() = msb + 1 inline val Int.size_i: Int get() = msb - lsb + 1 inline val Int.rd: Int get() = (this ushr 11) and 0x1F inline val Int.rt: Int get() = (this ushr 16) and 0x1F inline val Int.rs: Int get() = (this ushr 21) and 0x1F inline val Int.fd: Int get() = (this ushr 6) and 0x1F inline val Int.fs: Int get() = (this ushr 11) and 0x1F inline val Int.ft: Int get() = (this ushr 16) and 0x1F inline val Int.vd: Int get() = (this ushr 0) and 0x7F inline val Int.vs: Int get() = (this ushr 8) and 0x7F inline val Int.vt: Int get() = (this ushr 16) and 0x7F inline val Int.vt1: Int get() = this.extract(0, 1) inline val Int.vt2: Int get() = this.extract(0, 2) inline val Int.vt5: Int get() = this.extract(16, 5) inline val Int.vt5_1: Int get() = vt5 or (vt1 shl 5) inline val Int.vt5_2: Int get() = vt5 or (vt2 shl 5) val Int.imm8: Int get() = this.extract(16, 8) val Int.imm5: Int get() = this.extract(16, 5) val Int.imm3: Int get() = this.extract(16, 3) val Int.imm7: Int get() = this.extract(0, 7) val Int.imm4: Int get() = this.extract(0, 4) inline val Int.one: Int get() = this.extract(7, 1) inline val Int.two: Int get() = this.extract(15, 1) inline val Int.one_two: Int get() = (1 + 1 * this.one + 2 * this.two) inline val Int.syscall: Int get() = this.extract(6, 20) inline val Int.s_imm16: Int get() = (this shl 16) shr 16 inline val Int.u_imm16: Int get() = this and 0xFFFF inline val Int.s_imm14: Int get() = this.extract(2, 14).signExtend(14) inline val Int.u_imm26: Int get() = this.extract(0, 26) inline val Int.jump_address: Int get() = u_imm26 * 4 inline operator fun CpuState.invoke(callback: CpuState.() -> Unit) = this.normal(callback) inline fun CpuState.preadvance(callback: CpuState.() -> Unit) { advance_pc(4) this.run(callback) } inline fun CpuState.normal(callback: CpuState.() -> Unit) { this.run(callback) advance_pc(4) } inline fun CpuState.none(callback: CpuState.() -> Unit) { this.run(callback) } inline fun CpuState.branch(callback: CpuState.() -> Boolean) { val result = this.run(callback) // beq // if $s == $t advance_pc (offset << 2)); else advance_pc (4); if (result) { advance_pc(S_IMM16 * 4) } else { advance_pc(4) } } inline fun CpuState.branchLikely(callback: CpuState.() -> Boolean) { val result = this.run(callback) if (result) { //println("YAY!: $S_IMM16") advance_pc(S_IMM16 * 4) } else { //println("NON!: $S_IMM16") //println("-- %08X".format(_nPC)) //println("-- %08X".format(_PC)) _PC = _nPC + 4 _nPC = _PC + 4 } } inline var CpuState.VT: Float; get() = getVfpr(IR.vt); set(value) = run { setVfpr(IR.vt, value) } inline var CpuState.VD: Float; get() = getVfpr(IR.vd); set(value) = run { setVfpr(IR.vd, value) } inline var CpuState.VS: Float; get() = getVfpr(IR.vs); set(value) = run { setVfpr(IR.vs, value) } inline var CpuState.VT_I: Int; get() = getVfprI(IR.vt); set(value) = run { setVfprI(IR.vt, value) } inline var CpuState.VD_I: Int; get() = getVfprI(IR.vd); set(value) = run { setVfprI(IR.vd, value) } inline var CpuState.VS_I: Int; get() = getVfprI(IR.vs); set(value) = run { setVfprI(IR.vs, value) } inline var CpuState.RD: Int; get() = getGpr(IR.rd); set(value) = run { setGpr(IR.rd, value) } inline var CpuState.RT: Int; get() = getGpr(IR.rt); set(value) = run { setGpr(IR.rt, value) } inline var CpuState.RS: Int; get() = getGpr(IR.rs); set(value) = run { setGpr(IR.rs, value) } inline var CpuState.FD: Float; get() = getFpr(IR.fd); set(value) = run { setFpr(IR.fd, value) } inline var CpuState.FT: Float; get() = getFpr(IR.ft); set(value) = run { setFpr(IR.ft, value) } inline var CpuState.FS: Float; get() = getFpr(IR.fs); set(value) = run { setFpr(IR.fs, value) } inline var CpuState.FD_I: Int; get() = getFprI(IR.fd); set(value) = run { setFprI(IR.fd, value) } inline var CpuState.FT_I: Int; get() = getFprI(IR.ft); set(value) = run { setFprI(IR.ft, value) } inline var CpuState.FS_I: Int; get() = getFprI(IR.fs); set(value) = run { setFprI(IR.fs, value) } inline val CpuState.RS_IMM16: Int; get() = RS + S_IMM16 inline val CpuState.RS_IMM14: Int; get() = RS + S_IMM14 * 4 //val CpuState.IMM16: Int; get() = I.extract() //val CpuState.U_IMM16: Int get() = TODO() inline val CpuState.S_IMM14: Int; get() = IR.s_imm14 inline val CpuState.S_IMM16: Int; get() = IR.s_imm16 inline val CpuState.U_IMM16: Int get() = IR.u_imm16 inline val CpuState.POS: Int get() = IR.pos inline val CpuState.SIZE_E: Int get() = IR.size_e inline val CpuState.SIZE_I: Int get() = IR.size_i inline val CpuState.SYSCALL: Int get() = IR.syscall inline val CpuState.U_IMM26: Int get() = IR.u_imm26 inline val CpuState.JUMP_ADDRESS: Int get() = IR.jump_address } /* export class Instruction { constructor(public PC: number, public data: number) { } static fromMemoryAndPC(memory: Memory, PC: number) { return new Instruction(PC, memory.readInt32(PC)); } extract(offset: number, length: number) { return BitUtils.extract(this.data, offset, length); } extract_s(offset: number, length: number) { return BitUtils.extractSigned(this.data, offset, length); } insert(offset: number, length: number, value: number) { this.data = BitUtils.insert(this.data, offset, length, value); } get rd() { return this.extract(11 + 5 * 0, 5); } set rd(value: number) { this.insert(11 + 5 * 0, 5, value); } get rt() { return this.extract(11 + 5 * 1, 5); } set rt(value: number) { this.insert(11 + 5 * 1, 5, value); } get rs() { return this.extract(11 + 5 * 2, 5); } set rs(value: number) { this.insert(11 + 5 * 2, 5, value); } get fd() { return this.extract(6 + 5 * 0, 5); } set fd(value: number) { this.insert(6 + 5 * 0, 5, value); } get fs() { return this.extract(6 + 5 * 1, 5); } set fs(value: number) { this.insert(6 + 5 * 1, 5, value); } get ft() { return this.extract(6 + 5 * 2, 5); } set ft(value: number) { this.insert(6 + 5 * 2, 5, value); } get VD() { return this.extract(0, 7); } set VD(value: number) { this.insert(0, 7, value); } get VS() { return this.extract(8, 7); } set VS(value: number) { this.insert(8, 7, value); } get VT() { return this.extract(16, 7); } set VT(value: number) { this.insert(16, 7, value); } get VT5_1() { return this.VT5 | (this.VT1 << 5); } set VT5_1(value: number) { this.VT5 = value; this.VT1 = (value >>> 5); } get IMM14() { return this.extract_s(2, 14); } set IMM14(value: number) { this.insert(2, 14, value); } get ONE() { return this.extract(7, 1); } set ONE(value: number) { this.insert(7, 1, value); } get TWO() { return this.extract(15, 1); } set TWO(value: number) { this.insert(15, 1, value); } get ONE_TWO() { return (1 + 1 * this.ONE + 2 * this.TWO); } set ONE_TWO(value: number) { this.ONE = (((value - 1) >>> 0) & 1); this.TWO = (((value - 1) >>> 1) & 1); } get IMM8() { return this.extract(16, 8); } set IMM8(value: number) { this.insert(16, 8, value); } get IMM5() { return this.extract(16, 5); } set IMM5(value: number) { this.insert(16, 5, value); } get IMM3() { return this.extract(18, 3); } set IMM3(value: number) { this.insert(18, 3, value); } get IMM7() { return this.extract(0, 7); } set IMM7(value: number) { this.insert(0, 7, value); } get IMM4() { return this.extract(0, 4); } set IMM4(value: number) { this.insert(0, 4, value); } get VT1() { return this.extract(0, 1); } set VT1(value: number) { this.insert(0, 1, value); } get VT2() { return this.extract(0, 2); } set VT2(value: number) { this.insert(0, 2, value); } get VT5() { return this.extract(16, 5); } set VT5(value: number) { this.insert(16, 5, value); } get VT5_2() { return this.VT5 | (this.VT2 << 5); } get IMM_HF() { return HalfFloat.toFloat(this.imm16); } get pos() { return this.lsb; } set pos(value: number) { this.lsb = value; } get size_e() { return this.msb + 1; } set size_e(value: number) { this.msb = value - 1; } get size_i() { return this.msb - this.lsb + 1; } set size_i(value: number) { this.msb = this.lsb + value - 1; } get lsb() { return this.extract(6 + 5 * 0, 5); } set lsb(value: number) { this.insert(6 + 5 * 0, 5, value); } get msb() { return this.extract(6 + 5 * 1, 5); } set msb(value: number) { this.insert(6 + 5 * 1, 5, value); } get c1cr() { return this.extract(6 + 5 * 1, 5); } set c1cr(value: number) { this.insert(6 + 5 * 1, 5, value); } get syscall() { return this.extract(6, 20); } set syscall(value: number) { this.insert(6, 20, value); } get imm16() { var res = this.u_imm16; if (res & 0x8000) res |= 0xFFFF0000; return res; } set imm16(value: number) { this.insert(0, 16, value); } get u_imm16() { return this.extract(0, 16); } set u_imm16(value: number) { this.insert(0, 16, value); } get u_imm26() { return this.extract(0, 26); } set u_imm26(value: number) { this.insert(0, 26, value); } get jump_bits() { return this.extract(0, 26); } set jump_bits(value: number) { this.insert(0, 26, value); } get jump_real() { return (this.jump_bits * 4) >>> 0; } set jump_real(value: number) { this.jump_bits = (value / 4) >>> 0; } set branch_address(value:number) { this.imm16 = (value - this.PC - 4) / 4; } set jump_address(value:number) { this.u_imm26 = value / 4; } get branch_address() { return this.PC + this.imm16 * 4 + 4; } get jump_address() { return this.u_imm26 * 4; } } */
mit
5d005a31094f2f8d3a4f02739049f5d3
50.936652
167
0.605298
2.81299
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/utils/TextUtils.kt
1
4530
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Romain Bertozzi <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.utils import android.text.TextUtils import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.text.format.DateUtils import cx.ring.R import net.jami.model.Interaction.InteractionStatus import java.util.* object TextUtils { val TAG = TextUtils::class.simpleName!! fun copyToClipboard(context: Context, text: String?) { if (TextUtils.isEmpty(text)) { return } val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.setPrimaryClip(ClipData.newPlainText(context.getText(R.string.clip_contact_uri), text)) } fun getShortenedNumber(number: String): String { val size = number.length if (size > 18) return number.substring(0, 9) + "\u2026" + number.substring(size - 9, size) return number } /** * Computes the string to set in text details between messages, indicating time separation. * * @param timestamp The timestamp used to launch the computation with Date().getTime(). * Can be the last received message timestamp for example. * @return The string to display in the text details between messages. */ fun timestampToDetailString(context: Context, timestamp: Long): String { val diff = Date().time - timestamp val timeStr: String = if (diff < DateUtils.WEEK_IN_MILLIS) { if (diff < DateUtils.DAY_IN_MILLIS && DateUtils.isToday(timestamp)) { // 11:32 A.M. DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_TIME) } else { DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_NO_YEAR or DateUtils.FORMAT_ABBREV_ALL or DateUtils.FORMAT_SHOW_TIME) } } else if (diff < DateUtils.YEAR_IN_MILLIS) { DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_NO_YEAR or DateUtils.FORMAT_ABBREV_ALL or DateUtils.FORMAT_SHOW_TIME) } else { DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_WEEKDAY or DateUtils.FORMAT_ABBREV_ALL) } return timeStr.uppercase(Locale.getDefault()) } fun getReadableFileTransferStatus(context: Context, transferStatus: InteractionStatus): String { return when (transferStatus) { InteractionStatus.TRANSFER_CREATED -> context.getString(R.string.file_transfer_status_created) InteractionStatus.TRANSFER_AWAITING_PEER -> context.getString(R.string.file_transfer_status_wait_peer_acceptance) InteractionStatus.TRANSFER_AWAITING_HOST -> context.getString(R.string.file_transfer_status_wait_host_acceptance) InteractionStatus.TRANSFER_ONGOING -> context.getString(R.string.file_transfer_status_ongoing) InteractionStatus.TRANSFER_FINISHED -> context.getString(R.string.file_transfer_status_finished) InteractionStatus.TRANSFER_CANCELED -> context.getString(R.string.file_transfer_status_cancelled) InteractionStatus.TRANSFER_UNJOINABLE_PEER -> context.getString(R.string.file_transfer_status_unjoinable_peer) InteractionStatus.TRANSFER_ERROR -> context.getString(R.string.file_transfer_status_error) InteractionStatus.TRANSFER_TIMEOUT_EXPIRED -> context.getString(R.string.file_transfer_status_timed_out) else -> "" } } }
gpl-3.0
e161aa6b94eeb59ec2b701fa0dd7a8dd
48.23913
125
0.695364
4.402332
false
false
false
false
juanavelez/crabzilla
crabzilla-pg-client/src/test/java/io/github/crabzilla/pgc/example1/Example1Fixture.kt
1
1408
package io.github.crabzilla.pgc.example1 import io.github.crabzilla.example1.customer.* import io.github.crabzilla.framework.UnitOfWork import io.github.crabzilla.internal.EntityComponent import io.github.crabzilla.pgc.PgcEntityComponent import io.vertx.core.Vertx import io.vertx.pgclient.PgPool import java.time.Instant import java.util.* object Example1Fixture { const val CUSTOMER_ENTITY = "customer" const val customerId1 = 1 val createCmd1 = CreateCustomer("customer1") val created1 = CustomerCreated(customerId1, "customer1") val createdUow1 = UnitOfWork(CUSTOMER_ENTITY, customerId1, UUID.randomUUID(), "create", createCmd1, 1, listOf(Pair("CustomerCreated", created1))) val activateCmd1 = ActivateCustomer("I want it") val activated1 = CustomerActivated("a good reason", Instant.now()) val activatedUow1 = UnitOfWork(CUSTOMER_ENTITY, customerId1, UUID.randomUUID(), "activate", activateCmd1, 2, listOf(Pair("CustomerActivated", activated1))) val createActivateCmd1 = CreateActivateCustomer("customer1", "bcz I can") val deactivated1 = CustomerDeactivated("a good reason", Instant.now()) val customerJson = CustomerJsonAware() val customerPgcComponent: (vertx: Vertx, writeDb: PgPool) -> EntityComponent<Customer> = { vertx: Vertx, writeDb: PgPool -> PgcEntityComponent(vertx, writeDb, CUSTOMER_ENTITY, customerJson, CustomerCommandAware()) } }
apache-2.0
f1b4819ff1a7e828cac3adf4a2b1be83
35.102564
95
0.768466
3.826087
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/files/ui/FilesFragment.kt
2
5121
package chat.rocket.android.files.ui import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.DividerItemDecoration.HORIZONTAL import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.files.adapter.FilesAdapter import chat.rocket.android.files.presentation.FilesPresenter import chat.rocket.android.files.presentation.FilesView import chat.rocket.android.files.uimodel.FileUiModel import chat.rocket.android.helper.EndlessRecyclerViewScrollListener import chat.rocket.android.helper.ImageHelper import chat.rocket.android.player.PlayerActivity import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_files.* import javax.inject.Inject fun newInstance(chatRoomId: String): Fragment = FilesFragment().apply { arguments = Bundle(1).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) } } internal const val TAG_FILES_FRAGMENT = "FilesFragment" private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id" class FilesFragment : Fragment(), FilesView { @Inject lateinit var presenter: FilesPresenter @Inject lateinit var analyticsManager: AnalyticsManager private val adapter: FilesAdapter = FilesAdapter { fileUiModel -> presenter.openFile(fileUiModel) } private val linearLayoutManager = LinearLayoutManager(context) private lateinit var chatRoomId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_files) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() presenter.loadFiles(chatRoomId) analyticsManager.logScreenView(ScreenViewEvent.Files) } override fun showFiles(dataSet: List<FileUiModel>, total: Long) { ui { setupToolbar(total) if (adapter.itemCount == 0) { adapter.prependData(dataSet) if (dataSet.size >= 30) { recycler_view.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore( page: Int, totalItemsCount: Int, recyclerView: RecyclerView ) { presenter.loadFiles(chatRoomId) } }) } group_no_file.isVisible = dataSet.isEmpty() } else { adapter.appendData(dataSet) } } } override fun playMedia(url: String) { ui { PlayerActivity.play(it, url) } } override fun openImage(url: String, name: String) { ui { ImageHelper.openImage(root_layout.context, url, name) } } override fun openDocument(uri: Uri) { ui { startActivity(Intent(Intent.ACTION_VIEW, uri)) } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() { showMessage(getString(R.string.msg_generic_error)) } override fun showLoading() { ui { view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false } } private fun setupRecyclerView() { ui { recycler_view.layoutManager = linearLayoutManager recycler_view.addItemDecoration(DividerItemDecoration(it, HORIZONTAL)) recycler_view.adapter = adapter } } private fun setupToolbar(totalFiles: Long) { (activity as ChatRoomActivity).setupToolbarTitle( (getString( R.string.title_files_total, totalFiles )) ) } }
mit
7a8b09b74d5d75d516d8a591be1e3086
31.624204
101
0.660808
4.962209
false
false
false
false
luks91/Team-Bucket
app/src/main/java/com/github/luks91/teambucket/main/home/HomeAdapter.kt
2
5817
/** * Copyright (c) 2017-present, Team Bucket Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package com.github.luks91.teambucket.main.home import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import com.github.luks91.teambucket.R import com.github.luks91.teambucket.main.base.PullRequestViewHolder import com.github.luks91.teambucket.model.AvatarLoadRequest import com.github.luks91.teambucket.model.PullRequest import com.github.luks91.teambucket.model.ReviewersInformation import com.github.luks91.teambucket.util.BounceInterpolator import com.github.luks91.teambucket.util.ImageViewTarget import com.github.luks91.teambucket.util.childImageView import com.github.luks91.teambucket.util.childTextView import io.reactivex.functions.Consumer class HomeAdapter(private val context: Context, private val avatarRequestsConsumer: Consumer<AvatarLoadRequest>): RecyclerView.Adapter<RecyclerView.ViewHolder>() { val EMPTY_VIEW_TYPE = 0 val SUGGESTION_VIEW_TYPE = 1 val HEADER_VIEW_TYPE = 2 val PULL_REQUEST_VIEW_TYPE = 3 private var reviewers: ReviewersInformation = ReviewersInformation.EMPTY private var pullRequests = listOf<PullRequest>() fun onUserPullRequestsReceived(pullRequests: List<PullRequest>) { this.pullRequests = pullRequests } fun onReviewersReceived(reviewers: ReviewersInformation) { this.reviewers = reviewers notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent!!.context) when (viewType) { EMPTY_VIEW_TYPE -> return object: RecyclerView.ViewHolder(inflater.inflate(R.layout.no_data_view, parent, false)) {} SUGGESTION_VIEW_TYPE -> return SuggestedReviewersViewHolder( inflater.inflate(R.layout.suggested_reviewers_card, parent, false)) HEADER_VIEW_TYPE -> return HeaderViewHolder(inflater.inflate(R.layout.header_card, parent, false)) else -> return PullRequestViewHolder(inflater.inflate(R.layout.pull_request_card, parent, false), avatarRequestsConsumer) } } override fun getItemCount() = if (reviewers.reviewers.isEmpty()) 1 else 2 + pullRequests.size override fun getItemViewType(position: Int): Int = when { reviewers.reviewers.isEmpty() -> EMPTY_VIEW_TYPE position == 0 -> SUGGESTION_VIEW_TYPE position == 1 -> HEADER_VIEW_TYPE else -> PULL_REQUEST_VIEW_TYPE } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is SuggestedReviewersViewHolder -> holder.fillIn(reviewers) is HeaderViewHolder -> holder.fillIn( if (pullRequests.isEmpty()) context.getString(R.string.no_pull_requests) else context.getString( R.string.pull_requests_assigned_to_you, pullRequests.size)) is PullRequestViewHolder -> { holder.fillIn(pullRequests[position - 2]) holder.showDivider(position != 2) } } } private inner class SuggestedReviewersViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { private val suggestedReviewersViews: Array<Pair<ImageView, TextView>> by lazy { arrayOf(itemView.childImageView(R.id.firstReviewer) to itemView.childTextView(R.id.firstReviewerName), itemView.childImageView(R.id.leadReviewer) to itemView.childTextView(R.id.leadReviewerName), itemView.childImageView(R.id.secondReviewer) to itemView.childTextView(R.id.secondReviewerName)) } fun fillIn(reviewersInformation: ReviewersInformation) { reviewersInformation.apply { val reviewersCount = preferredReviewers.size for (index in 0..Math.min(reviewersCount - 1, suggestedReviewersViews.size - 1)) { suggestedReviewersViews[index].apply { val reviewerUser = preferredReviewers[index].user first.visibility = View.VISIBLE second.visibility = View.VISIBLE avatarRequestsConsumer.accept(AvatarLoadRequest(reviewerUser, ImageViewTarget(first))) second.text = reviewerUser.displayName } } for (index in reviewersCount..suggestedReviewersViews.size - 1) { suggestedReviewersViews[index].apply { first.visibility = View.GONE second.visibility = View.GONE } } } } } private inner class HeaderViewHolder constructor(itemView: View): RecyclerView.ViewHolder(itemView) { fun fillIn(text: String) { (itemView as TextView).text = text } } }
apache-2.0
950df604e023cf2c7d0079fa3de0def2
45.544
128
0.673027
4.925487
false
false
false
false
mukeshsolanki/Android-Shared-Preferences-TinyDB-
app/src/main/java/in/madapps/easypreferences/example/MainActivity.kt
1
868
package `in`.madapps.easypreferences.example import `in`.madapps.prefrences.EasyPreferences import `in`.madapps.prefrences.EasyPreferences.get import `in`.madapps.prefrences.EasyPreferences.set import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log class MainActivity : AppCompatActivity() { private val KEY = "TestKey" private val VALUE = "HelloWorkd" private val DEFAULT_VALUE = "Hello" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val prefs = EasyPreferences.defaultPrefs(this) prefs[KEY] = VALUE val value: String? = prefs[KEY] Log.d("value=>", value) prefs.edit() .clear() .apply() val defaultVal: String? = prefs[KEY, DEFAULT_VALUE] Log.d("defaultValue=>", defaultVal) } }
apache-2.0
3dae5e43da075ab92579a889647d0d67
30
55
0.728111
3.807018
false
false
false
false
FirebaseExtended/make-it-so-android
app/src/main/java/com/example/makeitso/screens/tasks/TasksViewModel.kt
1
2474
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.screens.tasks import androidx.compose.runtime.mutableStateOf import com.example.makeitso.EDIT_TASK_SCREEN import com.example.makeitso.SETTINGS_SCREEN import com.example.makeitso.TASK_ID import com.example.makeitso.model.Task import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.screens.MakeItSoViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class TasksViewModel @Inject constructor( logService: LogService, private val storageService: StorageService, private val configurationService: ConfigurationService ) : MakeItSoViewModel(logService) { val options = mutableStateOf<List<String>>(listOf()) val tasks = storageService.tasks fun loadTaskOptions() { val hasEditOption = configurationService.isShowTaskEditButtonConfig options.value = TaskActionOption.getOptions(hasEditOption) } fun onTaskCheckChange(task: Task) { launchCatching { storageService.update(task.copy(completed = !task.completed)) } } fun onAddClick(openScreen: (String) -> Unit) = openScreen(EDIT_TASK_SCREEN) fun onSettingsClick(openScreen: (String) -> Unit) = openScreen(SETTINGS_SCREEN) fun onTaskActionClick(openScreen: (String) -> Unit, task: Task, action: String) { when (TaskActionOption.getByTitle(action)) { TaskActionOption.EditTask -> openScreen("$EDIT_TASK_SCREEN?$TASK_ID={${task.id}}") TaskActionOption.ToggleFlag -> onFlagTaskClick(task) TaskActionOption.DeleteTask -> onDeleteTaskClick(task) } } private fun onFlagTaskClick(task: Task) { launchCatching { storageService.update(task.copy(flag = !task.flag)) } } private fun onDeleteTaskClick(task: Task) { launchCatching { storageService.delete(task.id) } } }
apache-2.0
0ada6d5c0674ba4e91fe5bb49260e0f6
34.855072
88
0.779305
4.179054
false
true
false
false
terracotta-ko/Android_Treasure_House
RecyclerView_In_ScrollView/app/src/main/java/com/kobe/recyclerview_in_scrollview/MyRecyclerViewAdapter.kt
1
1325
package com.kobe.recyclerview_in_scrollview import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_layout.view.* class MyRecyclerViewAdapter(private val context: Context) : RecyclerView.Adapter<MyRecyclerViewAdapter.BaseViewHolder>() { private val items = ArrayList<Int>() init { for (i: Int in 0..100) { items.add(i) } } class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val titleView: TextView? = itemView.titleTextView val contentView: TextView? = itemView.contentTextView } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder { return BaseViewHolder(LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false)) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { val titleStr: String = "Title " + items[position] val contentStr: String = "Content " + items[position] holder.titleView?.text = titleStr holder.contentView?.text = contentStr } }
mit
85c47f0ce706e0b8ee4245e7109de9d7
31.341463
122
0.713208
4.600694
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/stage/OptimisedStage.kt
1
4190
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.stage import uk.co.nickthecoder.tickle.Actor import uk.co.nickthecoder.tickle.Role interface FindRolesStrategy { fun <T : Role> findRoles(stage: Stage, type: Class<T>): List<T> fun add(actor: Actor) fun remove(actor: Actor) } class SlowFindRolesStrategy : FindRolesStrategy { override fun <T : Role> findRoles(stage: Stage, type: Class<T>): List<T> { @Suppress("UNCHECKED_CAST") return stage.actors.filter { type.isInstance(it.role) }.map { it.role as T } } override fun add(actor: Actor) {} override fun remove(actor: Actor) {} companion object { val instance = SlowFindRolesStrategy() } } /** * Optimises calls to [Stage.findRoles] by keeping a cache of roles keyed by class. * * Initially the cache is empty, then when findRoles is called, the slow implementation is used to fill the cache * for that particular class. * * Whenever an actor is added to the stage, if its role is an instance of a cached class, then the actor's role * is added to the cached list. * * Whenever an actor is remove from the stage, it is removed from all cached lists. * * Note, a single actor's role can be in multiple lists. For example, findRoles<Ball> followed by findRoles<BlueBall> * will create two lists (one for Ball and one for BlueBall). If BlueBall is a subclass of Ball, then Actors with a * BlueBall Role will be in both lists. * * The net result is a small penalty when adding/removing actors, and a large improvement when finding roles. */ open class CachedFindRolesStrategy : FindRolesStrategy { val actorsByType = mutableMapOf<Class<*>, MutableList<Role>>() override fun <T : Role> findRoles(stage: Stage, type: Class<T>): List<T> { val cached = actorsByType[type] if (cached == null) { val result = SlowFindRolesStrategy.instance.findRoles(stage, type) actorsByType[type] = (result as List<Role>).toMutableList() return result } else { @Suppress("UNCHECKED_CAST") return cached as List<T> } } override fun add(actor: Actor) { actor.role?.let { role -> actorsByType.forEach { type, list -> if (type.isInstance(actor.role)) { list.add(role) } } } } override fun remove(actor: Actor) { actorsByType.values.forEach { it.remove(actor.role) } } } /** * A subclass of [GameStage], which optimises [findRoles] using a [FindRolesStrategy]. * * The default strategy is [CachedFindRolesStrategy], because this is generic enough to work for any game. * * However, you could implement your own, customised strategy optimised specifically your specific game. * For example, if you never find roles which have subclasses, you don't need the isInstance calls required by * CachedFindRolesStrategy, and use "===" instead. */ open class OptimisedStage : GameStage() { var findRolesStrategy: FindRolesStrategy = CachedFindRolesStrategy() set(v) { field = v actors.forEach { v.add(it) } } override fun <T : Role> findRolesByClass(type: Class<T>): List<T> { return findRolesStrategy.findRoles(this, type) } override fun add(actor: Actor) { super.add(actor) findRolesStrategy.add(actor) } override fun remove(actor: Actor) { super.remove(actor) findRolesStrategy.remove(actor) } }
gpl-3.0
0d18fc4188cfec221f7ab20889aeb530
30.984733
117
0.677804
4.19
false
false
false
false
cketti/k-9
backend/jmap/src/main/java/com/fsck/k9/backend/jmap/CommandMove.kt
1
2150
package com.fsck.k9.backend.jmap import com.fsck.k9.logging.Timber import rs.ltt.jmap.client.JmapClient import rs.ltt.jmap.common.method.call.email.SetEmailMethodCall import rs.ltt.jmap.common.method.response.email.SetEmailMethodResponse import rs.ltt.jmap.common.util.Patches class CommandMove( private val jmapClient: JmapClient, private val accountId: String ) { fun moveMessages(targetFolderServerId: String, messageServerIds: List<String>) { Timber.v("Moving %d messages to %s", messageServerIds.size, targetFolderServerId) val mailboxPatch = Patches.set("mailboxIds", mapOf(targetFolderServerId to true)) updateEmails(messageServerIds, mailboxPatch) } fun moveMessagesAndMarkAsRead(targetFolderServerId: String, messageServerIds: List<String>) { Timber.v("Moving %d messages to %s and marking them as read", messageServerIds.size, targetFolderServerId) val mailboxPatch = Patches.builder() .set("mailboxIds", mapOf(targetFolderServerId to true)) .set("keywords/\$seen", true) .build() updateEmails(messageServerIds, mailboxPatch) } fun copyMessages(targetFolderServerId: String, messageServerIds: List<String>) { Timber.v("Copying %d messages to %s", messageServerIds.size, targetFolderServerId) val mailboxPatch = Patches.set("mailboxIds/$targetFolderServerId", true) updateEmails(messageServerIds, mailboxPatch) } private fun updateEmails(messageServerIds: List<String>, patch: Map<String, Any>?) { val session = jmapClient.session.get() val maxObjectsInSet = session.maxObjectsInSet messageServerIds.chunked(maxObjectsInSet).forEach { emailIds -> val updates = emailIds.map { emailId -> emailId to patch }.toMap() val setEmailCall = jmapClient.call( SetEmailMethodCall.builder() .accountId(accountId) .update(updates) .build() ) setEmailCall.getMainResponseBlocking<SetEmailMethodResponse>() } } }
apache-2.0
a014d43096b3054a6f20d528312b7bcc
37.392857
114
0.678605
4.953917
false
false
false
false
google/fhir-app-examples
demo/src/main/java/com/google/fhir/examples/demo/EditPatientFragment.kt
1
3740
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.fhir.examples.demo import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.fragment.app.viewModels import androidx.navigation.fragment.NavHostFragment import com.google.android.fhir.datacapture.QuestionnaireFragment /** A fragment representing Edit Patient screen. This fragment is contained in a [MainActivity]. */ class EditPatientFragment : Fragment(R.layout.add_patient_fragment) { private val viewModel: EditPatientViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) (requireActivity() as AppCompatActivity).supportActionBar?.apply { title = requireContext().getString(R.string.edit_patient) } requireArguments() .putString(QUESTIONNAIRE_FILE_PATH_KEY, "new-patient-registration-paginated.json") viewModel.livePatientData.observe(viewLifecycleOwner) { addQuestionnaireFragment(it) } viewModel.isPatientSaved.observe(viewLifecycleOwner) { if (!it) { Toast.makeText(requireContext(), R.string.message_input_missing, Toast.LENGTH_SHORT).show() return@observe } Toast.makeText(requireContext(), R.string.message_patient_updated, Toast.LENGTH_SHORT).show() NavHostFragment.findNavController(this).navigateUp() } (activity as MainActivity).setDrawerEnabled(false) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.add_patient_fragment_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { NavHostFragment.findNavController(this).navigateUp() true } R.id.action_add_patient_submit -> { onSubmitAction() true } else -> super.onOptionsItemSelected(item) } } private fun addQuestionnaireFragment(pair: Pair<String, String>) { val fragment = QuestionnaireFragment() fragment.arguments = bundleOf( QuestionnaireFragment.EXTRA_QUESTIONNAIRE_JSON_STRING to pair.first, QuestionnaireFragment.EXTRA_QUESTIONNAIRE_RESPONSE_JSON_STRING to pair.second ) childFragmentManager.commit { add(R.id.add_patient_container, fragment, QUESTIONNAIRE_FRAGMENT_TAG) } } private fun onSubmitAction() { val questionnaireFragment = childFragmentManager.findFragmentByTag(QUESTIONNAIRE_FRAGMENT_TAG) as QuestionnaireFragment viewModel.updatePatient(questionnaireFragment.getQuestionnaireResponse()) } companion object { const val QUESTIONNAIRE_FILE_PATH_KEY = "edit-questionnaire-file-path-key" const val QUESTIONNAIRE_FRAGMENT_TAG = "edit-questionnaire-fragment-tag" } }
apache-2.0
ccb7ea7e3fe305c7bb1a23bdb2005f93
35.666667
99
0.747594
4.54435
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/6.HelloKotlin-Array.kt
1
819
package com.zj.example.kotlin.shengshiyuan.helloworld /** * Created by zhengjiong * date: 2017/10/28 13:38 */ fun main(args: Array<String>) { HelloKotlin6_Array().test1() } class HelloKotlin6_Array { fun test1() { var array = intArrayOf(1, 2, 3) for (item: Int in array) { println(item) } println("------------------------") /** array[0] = 1 array[1] = 2 array[2] = 3 */ for (i: Int in array.indices) { println("array[$i] = ${array[i]}") } println("-----------------------") /** array[0] = 1 array[1] = 2 array[2] = 3 */ for ((index, value) in array.withIndex()) { println("array[$index] = $value") } } }
mit
b2c24ccb5774cd2bc8b18c23c6157f46
17.636364
53
0.429792
3.774194
false
false
false
false
Kotlin/anko
anko/library/static/commons/src/main/java/Dimensions.kt
2
4204
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package org.jetbrains.anko import android.app.Fragment import android.content.Context import android.support.annotation.DimenRes import android.util.DisplayMetrics import android.view.View const val LDPI: Int = DisplayMetrics.DENSITY_LOW const val MDPI: Int = DisplayMetrics.DENSITY_MEDIUM const val HDPI: Int = DisplayMetrics.DENSITY_HIGH const val TVDPI: Int = DisplayMetrics.DENSITY_TV const val XHDPI: Int = DisplayMetrics.DENSITY_XHIGH const val XXHDPI: Int = DisplayMetrics.DENSITY_XXHIGH const val XXXHDPI: Int = DisplayMetrics.DENSITY_XXXHIGH const val MAXDPI: Int = 0xfffe //returns dip(dp) dimension value in pixels fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt() fun Context.dip(value: Float): Int = (value * resources.displayMetrics.density).toInt() //return sp dimension value in pixels fun Context.sp(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt() fun Context.sp(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt() //converts px value into dip or sp fun Context.px2dip(px: Int): Float = px.toFloat() / resources.displayMetrics.density fun Context.px2sp(px: Int): Float = px.toFloat() / resources.displayMetrics.scaledDensity fun Context.dimen(@DimenRes resource: Int): Int = resources.getDimensionPixelSize(resource) //the same for nested DSL components inline fun AnkoContext<*>.dip(value: Int): Int = ctx.dip(value) inline fun AnkoContext<*>.dip(value: Float): Int = ctx.dip(value) inline fun AnkoContext<*>.sp(value: Int): Int = ctx.sp(value) inline fun AnkoContext<*>.sp(value: Float): Int = ctx.sp(value) inline fun AnkoContext<*>.px2dip(px: Int): Float = ctx.px2dip(px) inline fun AnkoContext<*>.px2sp(px: Int): Float = ctx.px2sp(px) inline fun AnkoContext<*>.dimen(@DimenRes resource: Int): Int = ctx.dimen(resource) //the same for the views inline fun View.dip(value: Int): Int = context.dip(value) inline fun View.dip(value: Float): Int = context.dip(value) inline fun View.sp(value: Int): Int = context.sp(value) inline fun View.sp(value: Float): Int = context.sp(value) inline fun View.px2dip(px: Int): Float = context.px2dip(px) inline fun View.px2sp(px: Int): Float = context.px2sp(px) inline fun View.dimen(@DimenRes resource: Int): Int = context.dimen(resource) //the same for Fragments @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.dip(value: Int): Int = activity.dip(value) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.dip(value: Float): Int = activity.dip(value) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.sp(value: Int): Int = activity.sp(value) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.sp(value: Float): Int = activity.sp(value) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.px2dip(px: Int): Float = activity.px2dip(px) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.px2sp(px: Int): Float = activity.px2sp(px) @Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.") inline fun Fragment.dimen(@DimenRes resource: Int): Int = activity.dimen(resource)
apache-2.0
4847a5f2e3a68cbc2b4e8b01de5bd8b4
49.047619
110
0.763559
3.811423
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/undertale/textbox/PortraitSelectMenuExecutor.kt
1
2750
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.undertale.textbox import dev.kord.core.entity.User import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.gabrielaimageserver.handleExceptions import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.undertale.TextBoxExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.undertale.TextBoxHelper import net.perfectdreams.loritta.cinnamon.discord.interactions.components.CinnamonSelectMenuExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext import net.perfectdreams.loritta.cinnamon.discord.interactions.components.SelectMenuExecutorDeclaration class PortraitSelectMenuExecutor( loritta: LorittaBot, val client: GabrielaImageServerClient ) : CinnamonSelectMenuExecutor(loritta) { companion object : SelectMenuExecutorDeclaration(ComponentExecutorIds.PORTRAIT_SELECT_MENU_EXECUTOR) override suspend fun onSelect( user: User, context: ComponentContext, values: List<String> ) { // We will already defer to avoid issues // Also because we want to edit the message with a file... later! context.deferUpdateMessage() // Yes, this is unused because we haven't implemented buttons yet :( val (_, interactionDataId) = context.decodeDataFromComponentAndRequireUserToMatch<SelectGenericData>() val textBoxOptionsData = TextBoxHelper.getInteractionDataAndFailIfItDoesNotExist(context, interactionDataId) if (textBoxOptionsData !is TextBoxWithGamePortraitOptionsData) error("Trying to select a portrait while the type is not TextBoxWithGamePortraitOptionsData!") val newData = textBoxOptionsData.copy(portrait = values.first()) // Delete the old interaction data ID from the database, the "createMessage" will create a new one anyways :) context.loritta.pudding.interactionsData.deleteInteractionData(interactionDataId) val builtMessage = TextBoxExecutor.createMessage( context.loritta, context.user, context.i18nContext, newData ) val dialogBox = client.handleExceptions(context) { TextBoxExecutor.createDialogBox(client, newData) } context.updateMessage { attachments = mutableListOf() // Remove all attachments from the message! addFile("undertale_box.gif", dialogBox) apply(builtMessage) } } }
agpl-3.0
0b652819eb3dac2d419099ff15b6aea7
47.263158
117
0.766545
5.278311
false
false
false
false
signed/intellij-community
python/src/com/jetbrains/python/testing/universalTests/PyUniversalTestLegacyInterop.kt
1
13963
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing.universalTests import com.intellij.execution.RunManager import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectLifecycleListener import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.JDOMExternalizable import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyQualifiedNameOwner import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.run.PythonConfigurationFactoryBase import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration.TestType import com.jetbrains.python.testing.PythonTestConfigurationType import com.jetbrains.python.testing.PythonTestLegacyConfigurationProducer import com.jetbrains.python.testing.doctest.PythonDocTestConfigurationProducer import com.jetbrains.python.testing.nosetest.PythonNoseTestRunConfiguration import com.jetbrains.python.testing.pytest.PyTestRunConfiguration import com.jetbrains.python.testing.unittest.PythonUnitTestRunConfiguration import org.jdom.Element /** * Module to support legacy configurations. * * When legacy configuration is ought to be dropped, just remove this module and all references to it. * It supports switching back to old runners (see [isNewTestsModeEnabled]) and importing old configs to new one. * [projectInitialized] shall be called for that. * * @author Ilya.Kazakevich */ /** * @return is new mode enabled or not */ fun isNewTestsModeEnabled(): Boolean = Registry.`is`("python.tests.enableUniversalTests") /** * Should be installed as application component */ class PyUniversalTestLegacyInteropInitializer { init { disableUnneededConfigurationProducer() // Delegate to project initialization ApplicationManager.getApplication().messageBus.connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener { override fun projectComponentsInitialized(project: Project) { if (project.isDefault) return if (project.isInitialized) { projectInitialized(project) return } StartupManager.getInstance(project).runWhenProjectIsInitialized { projectInitialized(project) } } }) } } /** * To be called when project initialized to copy old configs to new one */ private fun projectInitialized(project: Project) { assert(project.isInitialized, { "Project is not initialized yet" }) RunManager.getInstance(project).allConfigurationsList.filterIsInstance(PyUniversalTestConfiguration::class.java).forEach { it.legacyConfigurationAdapter.copyFromLegacyIfNeeded() } } /** * It is impossible to have 2 producers for one type (class cast exception may take place), so we need to disable either old or new one */ private fun disableUnneededConfigurationProducer() { val extensionPoint = Extensions.getArea(null).getExtensionPoint(RunConfigurationProducer.EP_NAME) val newMode = isNewTestsModeEnabled() extensionPoint.extensions.filter { it !is PythonDocTestConfigurationProducer }.forEach { if ((it is PyUniversalTestsConfigurationProducer && !newMode) || (it is PythonTestLegacyConfigurationProducer<*> && newMode)) { extensionPoint.unregisterExtension(it) } } } private fun getVirtualFileByPath(path: String): VirtualFile? { return LocalFileSystem.getInstance().findFileByPath(path) ?: return null } private fun VirtualFile.asPyFile(project: Project): PyFile? { assert(project.isInitialized, { "This function can't be used on uninitialized project" }) if (this.isDirectory) { return null } var file: PyFile? = null ApplicationManager.getApplication() .invokeAndWait({ val document = FileDocumentManager.getInstance().getDocument(this) if (document != null) { file = PyUtil.`as`(PsiDocumentManager.getInstance(project).getPsiFile(document), PyFile::class.java) } }) return file } /** * Manages legacy-to-new configuration binding * Attach it to new configuration and mark with [com.jetbrains.reflection.DelegationProperty] */ class PyUniversalTestLegacyConfigurationAdapter<in T : PyUniversalTestConfiguration>(newConfig: T) : JDOMExternalizable { private val configManager: LegacyConfigurationManager<*, *> private val project = newConfig.project /** * Does configuration contain legacy information or was it created as new config? * Null is unknown */ private var containsLegacyInformation: Boolean? = null /** * True if configuration [containsLegacyInformation] and this information is already copied to new config, so it should not be * copied second time. * * Null means "false" and used here to prevent saving useless "false" value in .xml for new configurations. */ @ConfigField var legacyInformationCopiedToNew: Boolean? = null init { when (newConfig) { is PyUniversalPyTestConfiguration -> { configManager = LegacyConfigurationManagerPyTest(newConfig) } is PyUniversalNoseTestConfiguration -> { configManager = LegacyConfigurationManagerNose(newConfig) } is PyUniversalUnitTestConfiguration -> { configManager = LegacyConfigurationManagerUnit(newConfig) } else -> { throw IllegalAccessException("Unknown config: $newConfig") } } } override fun readExternal(element: Element) { val legacyConfig = configManager.legacyConfig if (legacyConfig is RunConfiguration) { (legacyConfig as RunConfiguration).readExternal(element) } else { (legacyConfig as JDOMExternalizable).readExternal(element) } containsLegacyInformation = configManager.isLoaded() if (project.isInitialized) { copyFromLegacyIfNeeded() } } override fun writeExternal(element: Element) { if (containsLegacyInformation ?: return) { val legacyConfig = configManager.legacyConfig if (legacyConfig is RunConfiguration) { (legacyConfig as RunConfiguration).writeExternal(element) } else { (legacyConfig as JDOMExternalizable).writeExternal(element) } } } fun copyFromLegacyIfNeeded() { assert(project.isInitialized, { "Initialized project required" }) if (containsLegacyInformation ?: return && !(legacyInformationCopiedToNew ?: false)) { configManager.copyFromLegacy() legacyInformationCopiedToNew = true } } } /** * Manages legacy-to-new configuration copying process */ private abstract class LegacyConfigurationManager< LEGACY_CONF_T : AbstractPythonLegacyTestRunConfiguration<LEGACY_CONF_T>, out NEW_CONF_T : PyUniversalTestConfiguration >(legacyConfFactory: PythonConfigurationFactoryBase, val newConfig: NEW_CONF_T) { @Suppress("UNCHECKED_CAST") // Factory-to-config mapping should be checked by developer: createTemplateConfiguration is not generic val legacyConfig = legacyConfFactory.createTemplateConfiguration(newConfig.project) as LEGACY_CONF_T /** * Checks test type to interpret target correctly. It could be function, class or method */ private fun getElementFromConfig(script: PyFile): PyQualifiedNameOwner? { if (legacyConfig.testType == TestType.TEST_FUNCTION) { return script.findTopLevelFunction(legacyConfig.methodName) } val clazz = script.findTopLevelClass(legacyConfig.className) ?: return null if (legacyConfig.testType == TestType.TEST_CLASS) { return clazz } return clazz.findMethodByName(legacyConfig.methodName, true, TypeEvalContext.userInitiated(legacyConfig.project, script)) } /** * If one of these fields is not empty -- legacy configuration makes sence */ open protected fun getFieldsToCheckForEmptiness() = listOf(legacyConfig.scriptName, legacyConfig.className, legacyConfig.methodName) /** * @return true of legacy configuration loaded, false if configuration is pure new */ fun isLoaded() = getFieldsToCheckForEmptiness().find { !it.isNullOrBlank() } != null /** * Copies config from legacy to new configuration. * Used by all runners but py.test which has very different settings */ open fun copyFromLegacy() { when (legacyConfig.testType) { TestType.TEST_CLASS, TestType.TEST_FUNCTION, TestType.TEST_METHOD -> { val virtualFile = getVirtualFileByPath(legacyConfig.scriptName) ?: return val pyFile = virtualFile.asPyFile(legacyConfig.project) ?: return val qualifiedName = getElementFromConfig(pyFile)?.qualifiedName ?: return newConfig.target.targetType = TestTargetType.PYTHON newConfig.target.target = qualifiedName } TestType.TEST_FOLDER -> { newConfig.target.targetType = TestTargetType.PATH newConfig.target.target = legacyConfig.folderName } TestType.TEST_SCRIPT -> { newConfig.target.targetType = TestTargetType.PATH newConfig.target.target = legacyConfig.scriptName } else -> { Logger.getInstance(LegacyConfigurationManager::class.java).warn("Unknown type {${legacyConfig.testType}") } } } } private class LegacyConfigurationManagerPyTest(newConfig: PyUniversalPyTestConfiguration) : LegacyConfigurationManager<PyTestRunConfiguration, PyUniversalPyTestConfiguration>( PythonTestConfigurationType.getInstance().LEGACY_PYTEST_FACTORY, newConfig) { /** * In Py.test target is provided as keywords, joined with "and". * "function_foo", "MyClass" or "MyClass and my_method" could be used here. */ private val KEYWORDS_SPLIT_PATTERN = java.util.regex.Pattern.compile("\\s+and\\s+", java.util.regex.Pattern.CASE_INSENSITIVE) override fun getFieldsToCheckForEmptiness() = super.getFieldsToCheckForEmptiness() + listOf(legacyConfig.keywords, legacyConfig.testToRun) override fun copyFromLegacy() { // Do not call parent since target is always provided as testToRun here newConfig.additionalArguments = legacyConfig.params // Default is PATH newConfig.target.targetType = TestTargetType.PATH val oldKeywords = legacyConfig.keywords val virtualFile = getVirtualFileByPath(legacyConfig.testToRun) ?: return if (virtualFile.isDirectory) { // If target is directory, then it can't point to any symbol newConfig.target.target = virtualFile.path newConfig.target.targetType = TestTargetType.PATH newConfig.keywords = oldKeywords return } // If it is file -- it could be file, class, method or functions (see keywords) val script = virtualFile.asPyFile(newConfig.project) ?: return val keywordsList = oldKeywords.split(KEYWORDS_SPLIT_PATTERN).filter(String::isNotEmpty) if (keywordsList.isEmpty() || keywordsList.size > 2 || keywordsList.find { it.contains(" ") } != null) { //Give up with interpreting newConfig.keywords = oldKeywords newConfig.target.target = script.virtualFile.path newConfig.target.targetType = TestTargetType.PATH return } val classOrFunctionName = keywordsList[0] val clazz = script.findTopLevelClass(classOrFunctionName) if (keywordsList.size == 1) { // Class or function val classOrFunction = PyUtil.`as`(clazz ?: script.findTopLevelFunction(classOrFunctionName), PyQualifiedNameOwner::class.java) ?: return newConfig.target.target = classOrFunction.qualifiedName ?: return newConfig.target.targetType = TestTargetType.PYTHON } if (keywordsList.size == 2) { // Class and method clazz ?: return val method = clazz.findMethodByName(keywordsList[1], true, TypeEvalContext.userInitiated(newConfig.project, script)) ?: return newConfig.target.target = method.qualifiedName ?: return newConfig.target.targetType = TestTargetType.PYTHON } } } private class LegacyConfigurationManagerUnit(newConfig: PyUniversalUnitTestConfiguration) : LegacyConfigurationManager<PythonUnitTestRunConfiguration, PyUniversalUnitTestConfiguration>( PythonTestConfigurationType.getInstance().LEGACY_UNITTEST_FACTORY, newConfig) { override fun copyFromLegacy() { super.copyFromLegacy() newConfig.additionalArguments = legacyConfig.params newConfig.pattern = legacyConfig.pattern } } private class LegacyConfigurationManagerNose(newConfig: PyUniversalNoseTestConfiguration) : LegacyConfigurationManager<PythonNoseTestRunConfiguration, PyUniversalNoseTestConfiguration>( PythonTestConfigurationType.getInstance().LEGACY_NOSETEST_FACTORY, newConfig) { override fun copyFromLegacy() { super.copyFromLegacy() newConfig.additionalArguments = legacyConfig.params } }
apache-2.0
3dda52c8236dd207d6cd39f0ffcb66e2
38.667614
140
0.747475
5.141016
false
true
false
false
vitoling/CloudMusicTV
api/src/main/kotlin/com/vitoling/cloudmusictv/data/source/CloudMusicRepo.kt
1
4298
package com.vitoling.cloudmusictv.data.source import com.google.gson.GsonBuilder import com.vitoling.cloudmusictv.data.model.LoginResponse import com.vitoling.cloudmusictv.data.model.user.PlaylistResponse import com.vitoling.cloudmusictv.data.model.v3.playlist.PlaylistDetailResponse import okhttp3.* import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path import java.net.CookieManager import java.net.CookiePolicy import java.net.HttpCookie import java.net.URI /** * Created by lingzhiyuan. * Date : 2/24/17. * Time : 14:57. * Description: * */ private const val COOKIE_DOMAIN = "http://music.163.com" private const val BASE_API_URL = "http://music.163.com/weapi/" private const val HEADER_ORIGIN = "Origin" private const val HEADER_ORIGIN_VALUE = "http://music.163.com" private const val HEADER_REFERER = "Referer" private const val HEADER_REFERER_VALUE = "http://music.163.com/" private const val HEADER_USER_AGENT = "User-Agent" private const val HEADER_USER_AGENT_VALUE = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" private const val HEADER_HOST = "Host" private const val HEADER_HOST_VALUE = "music.163.com" private const val HEADER_CONTENT_TYPE = "Content-Type" private const val HEADER_CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded" private const val COOKIE_APP_VER = "appver" private const val COOKIE_APP_VER_VALUE = "1.5.2" internal interface CloudMusicAPI { companion object { private val gson = GsonBuilder() .setDateFormat("yyyy-MM-dd hh:mm:ss") .create() // 通用请求头信息 private val headerInterceptor = Interceptor { chain -> val originalRequest = chain.request() val requestBuilder = originalRequest.newBuilder() .header(HEADER_ORIGIN, HEADER_ORIGIN_VALUE) .header(HEADER_HOST, HEADER_HOST_VALUE) .header(HEADER_REFERER, HEADER_REFERER_VALUE) .header(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE) .header(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_VALUE) .method(originalRequest.method(), originalRequest.body()) val request = requestBuilder.build() chain.proceed(request) } // 设置cookie private val cookieManager = CookieManager().apply { setCookiePolicy(CookiePolicy.ACCEPT_ALL) cookieStore.add(URI(BASE_API_URL), HttpCookie(COOKIE_APP_VER, COOKIE_APP_VER_VALUE).apply { domain = COOKIE_DOMAIN }) } val CLOUD_MUSIC_API_ADAPTER: Retrofit by lazy { // Build retrofit Retrofit.Builder().run { addConverterFactory(GsonConverterFactory.create(gson)) baseUrl(BASE_API_URL) client(OkHttpClient.Builder().run { addInterceptor(headerInterceptor) cookieJar(JavaNetCookieJar(cookieManager)) // build okhttp client build() }) build() } } } /** * 账号登录 * */ @POST("login") fun login(@Body body: RequestBody): Call<LoginResponse> /** * 手机号登录 * */ @POST("login/cellphone") fun login_cellphone(@Body body: RequestBody): Call<LoginResponse> @POST("feedback/weblog") fun feedback_weblog(@Body body: RequestBody): Call<Map<String, Any>> /** * 获取验证码 * */ @GET("/captcha?id={id}") fun captcha(@Path("id") id: String): Call<ResponseBody> /** * 获取用户的歌单 * */ @POST("user/playlist") fun user_playlist(@Body body: RequestBody): Call<PlaylistResponse> /** * 获取歌单的详情 * */ @POST("v3/playlist/detail") fun v3_playlist_detail(@Body body: RequestBody): Call<PlaylistDetailResponse> /** * * */ @POST("user/getfollows/{id}") fun user_getfollows(@Path("id") id: Long, @Body body: RequestBody): Call<PlaylistResponse> }
lgpl-3.0
6034d0bd6b6b168cd5e32ac55e3e4636
31.5
166
0.639205
3.973659
false
false
false
false
ericberman/MyFlightbookAndroid
app/src/main/java/com/myflightbook/android/ExpandableListFragment.kt
1
19015
// https://github.com/domoritz/open-mensa-android/blob/master/src/android/support/v4/app/ExpandableListFragment.java package com.myflightbook.android import android.content.Context import android.os.Bundle import android.os.Handler import android.view.* import android.view.ContextMenu.ContextMenuInfo import android.view.View.OnCreateContextMenuListener import android.view.animation.AnimationUtils import android.widget.* import android.widget.AdapterView.OnItemClickListener import android.widget.ExpandableListView.* import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment open class ExpandableListFragment : Fragment(), OnCreateContextMenuListener, OnChildClickListener, OnGroupCollapseListener, OnGroupExpandListener { private val mHandler = Handler() private val mRequestFocus = Runnable { mExpandableList!!.focusableViewAvailable(mExpandableList) } private val mOnClickListener = OnItemClickListener { parent: AdapterView<*>?, v: View, position: Int, id: Long -> onListItemClick( parent as ExpandableListView?, v, position, id ) } /** * Get the ExpandableListAdapter associated with this activity's * ExpandableListView. */ private var expandableListAdapter: ExpandableListAdapter? = null private var mExpandableList: ExpandableListView? = null private var mFinishedStart = false private var mEmptyView: View? = null private var mStandardEmptyView: TextView? = null private var mProgressContainer: View? = null private var mExpandableListContainer: View? = null private var mEmptyText: CharSequence? = null private var mExpandableListShown = false /** * Provide default implementation to return a simple list view. Subclasses * can override to replace with their own layout. If doing so, the * returned view hierarchy *must* have a ListView whose id * is [android.R.id.list] and can optionally * have a sibling view id [android.R.id.empty] * that is to be shown when the list is empty. * * * If you are overriding this method with your own custom content, * consider including the standard layout [android.R.layout.list_content] * in your layout file, so that you continue to retain all of the standard * behavior of ListFragment. In particular, this is currently the only * way to have the built-in indeterminant progress state be shown. */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val context: Context = requireActivity() val root = FrameLayout(context) // ------------------------------------------------------------------ val pframe = LinearLayout(context) pframe.id = INTERNAL_PROGRESS_CONTAINER_ID pframe.orientation = LinearLayout.VERTICAL pframe.visibility = View.GONE pframe.gravity = Gravity.CENTER val progress = ProgressBar( context, null, android.R.attr.progressBarStyleLarge ) pframe.addView( progress, FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) ) root.addView( pframe, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) // ------------------------------------------------------------------ val lframe = FrameLayout(context) lframe.id = INTERNAL_LIST_CONTAINER_ID val tv = TextView(activity) tv.id = INTERNAL_EMPTY_ID tv.gravity = Gravity.CENTER lframe.addView( tv, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) val lv = ExpandableListView(activity) lv.id = android.R.id.list lv.isDrawSelectorOnTop = false lframe.addView( lv, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) root.addView( lframe, FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) // ------------------------------------------------------------------ root.layoutParams = FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) return root } /** * Attach to list view once the view hierarchy has been created. */ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ensureList() } /** * Detach from list view. */ override fun onDestroyView() { mHandler.removeCallbacks(mRequestFocus) mExpandableList = null mExpandableListShown = false mExpandableListContainer = null mProgressContainer = mExpandableListContainer mEmptyView = mProgressContainer mStandardEmptyView = null super.onDestroyView() } /** * This method will be called when an item in the list is selected. * Subclasses should override. Subclasses can call * getListView().getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param l The ListView where the click happened * @param v The view that was clicked within the ListView * @param position The position of the view in the list * @param id The row id of the item that was clicked */ private fun onListItemClick(l: ExpandableListView?, v: View, position: Int, id: Long) {} /** * Set the currently selected list item to the specified * position with the adapter's data * */ fun setSelection(position: Int) { ensureList() mExpandableList!!.setSelection(position) } /** * Get the position of the currently selected list item. */ val selectedItemPosition: Int get() { ensureList() return mExpandableList!!.selectedItemPosition } /** * Get the cursor row ID of the currently selected list item. */ val selectedItemId: Long get() { ensureList() return mExpandableList!!.selectedItemId } /** * Get the activity's list view widget. */ val listView: ExpandableListView? get() { ensureList() return mExpandableList } /** * The default content for a ListFragment has a TextView that can * be shown when the list is empty. If you would like to have it * shown, call this method to supply the text it should use. */ fun setEmptyText(text: CharSequence?) { ensureList() checkNotNull(mStandardEmptyView) { "Can't be used with a custom content view" } mStandardEmptyView!!.text = text if (mEmptyText == null) { mExpandableList!!.emptyView = mStandardEmptyView } mEmptyText = text } /** * Control whether the list is being displayed. You can make it not * displayed if you are waiting for the initial data to show in it. During * this time an indeterminant progress indicator will be shown instead. * * * Applications do not normally need to use this themselves. The default * behavior of ListFragment is to start with the list not being shown, only * showing it once an adapter is given with ListAdapter. * If the list at that point had not been shown, when it does get shown * it will be do without the user ever seeing the hidden state. * * @param shown If true, the list view is shown; if false, the progress * indicator. The initial value is true. */ fun setListShown(shown: Boolean) { setListShown(shown, true) } /** * Like [.setListShown], but no animation is used when * transitioning from the previous state. */ fun setListShownNoAnimation(shown: Boolean) { setListShown(shown, false) } /** * Control whether the list is being displayed. You can make it not * displayed if you are waiting for the initial data to show in it. During * this time an indeterminant progress indicator will be shown instead. * * @param shown If true, the list view is shown; if false, the progress * indicator. The initial value is true. * @param animate If true, an animation will be used to transition to the * new state. */ private fun setListShown(shown: Boolean, animate: Boolean) { ensureList() checkNotNull(mProgressContainer) { "Can't be used with a custom content view" } if (mExpandableListShown == shown) { return } mExpandableListShown = shown if (shown) { if (animate) { mProgressContainer!!.startAnimation( AnimationUtils.loadAnimation( activity, android.R.anim.fade_out ) ) mExpandableListContainer!!.startAnimation( AnimationUtils.loadAnimation( activity, android.R.anim.fade_in ) ) } else { mProgressContainer!!.clearAnimation() mExpandableListContainer!!.clearAnimation() } mProgressContainer!!.visibility = View.GONE mExpandableListContainer!!.visibility = View.VISIBLE } else { if (animate) { mProgressContainer!!.startAnimation( AnimationUtils.loadAnimation( activity, android.R.anim.fade_in ) ) mExpandableListContainer!!.startAnimation( AnimationUtils.loadAnimation( activity, android.R.anim.fade_out ) ) } else { mProgressContainer!!.clearAnimation() mExpandableListContainer!!.clearAnimation() } mProgressContainer!!.visibility = View.VISIBLE mExpandableListContainer!!.visibility = View.GONE } } /** * Get the ListAdapter associated with this activity's ListView. */// The list was hidden, and previously didn't have an // adapter. It is now time to show it. /** * Provide the cursor for the list view. */ var listAdapter: ExpandableListAdapter? get() = expandableListAdapter set(adapter) { val hadAdapter = expandableListAdapter != null expandableListAdapter = adapter if (mExpandableList != null) { mExpandableList!!.setAdapter(adapter) if (!mExpandableListShown && !hadAdapter) { // The list was hidden, and previously didn't have an // adapter. It is now time to show it. val v = view if (v != null) setListShown(true, requireView().windowToken != null) } } } private fun ensureList() { if (mExpandableList != null) { return } val root = view ?: throw IllegalStateException("Content view not yet created") if (root is ExpandableListView) { mExpandableList = root } else { mStandardEmptyView = root.findViewById(INTERNAL_EMPTY_ID) if (mStandardEmptyView == null) { mEmptyView = root.findViewById(android.R.id.empty) } else { mStandardEmptyView!!.visibility = View.GONE } mProgressContainer = root.findViewById(INTERNAL_PROGRESS_CONTAINER_ID) mExpandableListContainer = root.findViewById(INTERNAL_LIST_CONTAINER_ID) val rawExpandableListView = root.findViewById<View>(android.R.id.list) if (rawExpandableListView !is ExpandableListView) { if (rawExpandableListView == null) { throw RuntimeException( "Your content must have a ListView whose id attribute is " + "'android.R.id.list'" ) } throw RuntimeException( "Content has view with id attribute 'android.R.id.list' " + "that is not a ListView class" ) } mExpandableList = rawExpandableListView if (mEmptyView != null) { mExpandableList!!.emptyView = mEmptyView } else if (mEmptyText != null) { val ev = mStandardEmptyView ev!!.text = mEmptyText mExpandableList!!.emptyView = ev } } mExpandableListShown = true mExpandableList!!.onItemClickListener = mOnClickListener // add invisible indicator mExpandableList!!.setGroupIndicator( ContextCompat.getDrawable( requireContext(), R.drawable.expander_group ) ) if (expandableListAdapter != null) { val adapter = expandableListAdapter!! expandableListAdapter = null listAdapter = adapter } else { // We are starting without an adapter, so assume we won't // have our data right away and start with the progress indicator. if (mProgressContainer != null) { setListShown( shown = false, animate = false ) } } mHandler.post(mRequestFocus) } /** * Override this to populate the context menu when an item is long pressed. menuInfo * will contain an [android.widget.ExpandableListView.ExpandableListContextMenuInfo] * whose packedPosition is a packed position * that should be used with [ExpandableListView.getPackedPositionType] and * the other similar methods. * * * {@inheritDoc} */ override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) {} /** * Override this for receiving callbacks when a child has been clicked. * * * {@inheritDoc} */ override fun onChildClick( parent: ExpandableListView, v: View, groupPosition: Int, childPosition: Int, id: Long ): Boolean { return false } /** * Override this for receiving callbacks when a group has been collapsed. */ override fun onGroupCollapse(groupPosition: Int) {} /** * Override this for receiving callbacks when a group has been expanded. */ override fun onGroupExpand(groupPosition: Int) {} // /** // * Ensures the expandable list view has been created before Activity restores all // * of the view states. // * // *@see Activity#onRestoreInstanceState(Bundle) // */ // @Override // protected void onRestoreInstanceState(Bundle state) { // ensureList(); // super.onRestoreInstanceState(state); // } /** * Updates the screen state (current list and other views) when the * content changes. * */ fun onContentChanged() { // super.onContentChanged(); val v = view ?: return val emptyView = requireView().findViewById<View>(android.R.id.empty) mExpandableList = requireView().findViewById(android.R.id.list) if (mExpandableList == null) { throw RuntimeException( "Your content must have a ExpandableListView whose id attribute is " + "'android.R.id.list'" ) } if (emptyView != null) { mExpandableList!!.emptyView = emptyView } mExpandableList!!.setOnChildClickListener(this) mExpandableList!!.setOnGroupExpandListener(this) mExpandableList!!.setOnGroupCollapseListener(this) if (mFinishedStart) { listAdapter = expandableListAdapter } mFinishedStart = true } /** * Get the activity's expandable list view widget. This can be used to get the selection, * set the selection, and many other useful functions. * * @see ExpandableListView */ val expandableListView: ExpandableListView? get() { ensureList() return mExpandableList } /** * Gets the ID of the currently selected group or child. * * @return The ID of the currently selected group or child. */ val selectedId: Long get() = mExpandableList!!.selectedId /** * Gets the position (in packed position representation) of the currently * selected group or child. Use * [ExpandableListView.getPackedPositionType], * [ExpandableListView.getPackedPositionGroup], and * [ExpandableListView.getPackedPositionChild] to unpack the returned * packed position. * * @return A packed position representation containing the currently * selected group or child's position and type. */ val selectedPosition: Long get() = mExpandableList!!.selectedPosition /** * Sets the selection to the specified child. If the child is in a collapsed * group, the group will only be expanded and child subsequently selected if * shouldExpandGroup is set to true, otherwise the method will return false. * * @param groupPosition The position of the group that contains the child. * @param childPosition The position of the child within the group. * @param shouldExpandGroup Whether the child's group should be expanded if * it is collapsed. * @return Whether the selection was successfully set on the child. */ fun setSelectedChild( groupPosition: Int, childPosition: Int, shouldExpandGroup: Boolean ): Boolean { return mExpandableList!!.setSelectedChild(groupPosition, childPosition, shouldExpandGroup) } /** * Sets the selection to the specified group. * @param groupPosition The position of the group that should be selected. */ fun setSelectedGroup(groupPosition: Int) { mExpandableList!!.setSelectedGroup(groupPosition) } companion object { private val INTERNAL_EMPTY_ID = View.generateViewId() private val INTERNAL_PROGRESS_CONTAINER_ID = View.generateViewId() private val INTERNAL_LIST_CONTAINER_ID = View.generateViewId() } }
gpl-3.0
ff0aa273462bcef41ecbc6a11f9a7f62
35.852713
116
0.609045
5.481407
false
false
false
false
kotlintest/kotlintest
kotest-assertions/src/commonMain/kotlin/io.kotlintest/aliases.kt
1
1788
package io.kotlintest import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.string.endWith import io.kotest.matchers.string.haveLength import io.kotest.matchers.string.match import io.kotest.matchers.string.startWith @Deprecated( "All packages are now io.kotest", ReplaceWith("shouldThrowAnyUnit(block)", "io.kotest.assertions.throwables") ) inline fun shouldThrowAnyUnit(block: () -> Unit) = io.kotest.assertions.throwables.shouldThrowAnyUnit(block) @Deprecated("All packages are now io.kotest", ReplaceWith("io.kotest.assertions.throwables.shouldThrow(block)", "io")) inline fun <reified T : Throwable> shouldThrow(block: () -> Any?): T = io.kotest.assertions.throwables.shouldThrow(block) @Deprecated("All package names are now io.kotest") infix fun String?.shouldHaveLength(length: Int) = this should haveLength(length) @Deprecated("All package names are now io.kotest") infix fun String?.shouldMatch(regex: String) = this should match(regex) @Deprecated("All package names are now io.kotest") infix fun String?.shouldMatch(regex: Regex) = this should match(regex) @Deprecated("All package names are now io.kotest") infix fun String?.shouldEndWith(suffix: String) = this should endWith(suffix) @Deprecated("All package names are now io.kotest") infix fun String?.shouldStartWith(prefix: String) = this should startWith(prefix) @Deprecated("All package names are now io.kotest") infix fun <T, U : T> T.shouldBe(any: U?) = this shouldBe any @Deprecated("All package names are now io.kotest") infix fun <T> T.shouldNotBe(any: Any?) = this shouldNotBe any @Deprecated("All package names are now io.kotest") fun <T> assertSoftly(block: () -> T): T = io.kotest.assertions.assertSoftly(block)
apache-2.0
8755689f986b4d083cd6ce427b9e0ed9
40.581395
118
0.770134
3.820513
false
true
false
false
jsargent7089/android
src/main/java/com/nextcloud/client/account/AnonymousUser.kt
2
3048
/* * Nextcloud Android client application * * @author Chris Narkiewicz <[email protected]> * Copyright (C) 2020 Chris Narkiewicz * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.account import android.accounts.Account import android.content.Context import android.net.Uri import android.os.Parcel import android.os.Parcelable import com.owncloud.android.MainApp import com.owncloud.android.R import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.lib.common.OwnCloudBasicCredentials import java.net.URI /** * This object represents anonymous user, ie. user that did not log in the Nextcloud server. * It serves as a semantically correct "empty value", allowing simplification of logic * in various components requiring user data, such as DB queries. */ internal data class AnonymousUser(private val accountType: String) : User, Parcelable { companion object { @JvmStatic fun fromContext(context: Context): AnonymousUser { val type = context.getString(R.string.account_type) return AnonymousUser(type) } @JvmField val CREATOR: Parcelable.Creator<AnonymousUser> = object : Parcelable.Creator<AnonymousUser> { override fun createFromParcel(source: Parcel): AnonymousUser = AnonymousUser(source) override fun newArray(size: Int): Array<AnonymousUser?> = arrayOfNulls(size) } } private constructor(source: Parcel) : this( source.readString() as String ) override val accountName: String = "anonymous@nohost" override val server = Server(URI.create(""), MainApp.MINIMUM_SUPPORTED_SERVER_VERSION) override val isAnonymous = true override fun toPlatformAccount(): Account { return Account(accountName, accountType) } override fun toOwnCloudAccount(): OwnCloudAccount { return OwnCloudAccount(Uri.EMPTY, OwnCloudBasicCredentials("", "")) } override fun nameEquals(user: User?): Boolean { return user?.accountName.equals(accountName, true) } override fun nameEquals(accountName: CharSequence?): Boolean { return accountName?.toString().equals(this.accountType, true) } override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(accountType) } }
gpl-2.0
618dce3719db79084df6034d3d75cd47
35.285714
101
0.724409
4.618182
false
false
false
false
mua-uniandes/weekly-problems
codeforces/1374/C/1374C.kt
1
785
package codeforces import java.io.BufferedReader import java.io.InputStreamReader fun main() { val In = BufferedReader(InputStreamReader(System.`in`)) val test = In.readLine().toInt() tailrec fun sol(l : List<Char>, count : Int, ans : Int) : Int { if(l.isEmpty()) return ans else { val h = l.first() if (h == '(') return sol(l.drop(1), count + 1, ans) else { if (count - 1 == -1) return sol(l.drop(1), 0, ans + 1) else return sol(l.drop(1), count - 1, ans) } } } for(i in 1..test) { In.readLine() val paren = In.readLine().toList() println(sol(paren, 0, 0)) } }
gpl-3.0
43ea7ab6d43cf5f8e57abbd13e2902f5
24.354839
68
0.467516
3.81068
false
true
false
false
marvec/engine
lumeer-core/src/main/kotlin/io/lumeer/core/adapter/CollectionAdapter.kt
2
3258
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 io.lumeer.core.adapter import io.lumeer.api.model.Collection import io.lumeer.api.util.ResourceUtils import io.lumeer.storage.api.dao.CollectionDao import io.lumeer.storage.api.dao.DocumentDao import io.lumeer.storage.api.dao.FavoriteItemDao import java.time.ZonedDateTime class CollectionAdapter(val collectionDao: CollectionDao, val favoriteItemDao: FavoriteItemDao, val documentDao: DocumentDao) { fun getFavoriteCollectionIds(userId: String, projectId: String): Set<String> = favoriteItemDao.getFavoriteCollectionIds(userId, projectId) fun isFavorite(collectionId: String, userId: String, projectId: String): Boolean = getFavoriteCollectionIds(userId, projectId).contains(collectionId) fun getDocumentsCountByCollection(collectionId: String) = documentDao.getDocumentsCountByCollection(collectionId) fun getDocumentsCounts() = documentDao.documentsCounts fun getDocumentsCount() = getDocumentsCounts().values.sum() fun mapCollectionComputedProperties(collection: Collection, userId: String, projectId: String) = collection.apply { isFavorite = isFavorite(collection.id, userId, projectId) documentsCount = getDocumentsCountByCollection(collection.id) } fun mapCollectionsComputedProperties(collections: List<Collection>, userId: String, projectId: String): List<Collection> { val favoriteCollectionIds = getFavoriteCollectionIds(userId, projectId) val documentsCounts = getDocumentsCounts() return collections.onEach { it.isFavorite = favoriteCollectionIds.contains(it.id) it.documentsCount = documentsCounts[it.id] ?: 0 } } fun updateCollectionMetadata(collection: Collection, attributesIdsToInc: Set<String>, attributesIdsToDec: Set<String>) { val originalCollection = collection.copy() collection.attributes = HashSet(ResourceUtils.incOrDecAttributes(collection.attributes, attributesIdsToInc, attributesIdsToDec)) collection.lastTimeUsed = ZonedDateTime.now() collectionDao.updateCollection(collection.id, collection, originalCollection) } fun updateCollectionMetadata(collection: Collection, attributesToInc: Map<String, Int>) { val originalCollection = collection.copy() collection.attributes = HashSet(ResourceUtils.incAttributes(collection.attributes, attributesToInc)) collection.lastTimeUsed = ZonedDateTime.now() collectionDao.updateCollection(collection.id, collection, originalCollection) } }
gpl-3.0
1040ae4ba202d2a84136b9927ee8a35c
46.217391
152
0.776243
4.608204
false
false
false
false
koesie10/AdventOfCode-Solutions-Kotlin
2015/src/main/kotlin/com/koenv/adventofcode/Day16.kt
1
2893
package com.koenv.adventofcode object Day16 { public fun getIdOfMatchedSue(input: String, rangedValues: Boolean = false): Int { val aunts = input.lines().map { val result = INSTRUCTION_REGEX.find(it)!! val id = result.groups[1]!!.value.toInt() var children: Int? = null var cats: Int? = null var samoyeds: Int? = null var pomeranians: Int? = null var akitas: Int? = null var vizslas: Int? = null var goldfish: Int? = null var trees: Int? = null var cars: Int? = null var perfumes: Int? = null val rest = result.groups[2]!!.value.trim().split(", ") rest.forEach { val parts = it.split(": ") val key = parts[0] val value = parts[1].toInt() when (key) { "children" -> children = value "cats" -> cats = value "samoyeds" -> samoyeds = value "pomeranians" -> pomeranians = value "akitas" -> akitas = value "vizslas" -> vizslas = value "goldfish" -> goldfish = value "trees" -> trees = value "cars" -> cars = value "perfumes" -> perfumes = value } } Sue(id, children, cats, samoyeds, pomeranians, akitas, vizslas, goldfish, trees, cars, perfumes) } return aunts.find { 3.matches(it.children) && 7.matches(it.cats, greaterThan = rangedValues) && 2.matches(it.samoyeds) && 3.matches(it.pomeranians, fewerThan = rangedValues) && 0.matches(it.akitas) && 0.matches(it.vizslas) && 5.matches(it.goldfish, fewerThan = rangedValues) && 3.matches(it.trees, greaterThan = rangedValues) && 2.matches(it.cars) && 1.matches(it.perfumes) }!!.id } fun Int.matches(actual: Int?, greaterThan: Boolean = false, fewerThan: Boolean = false): Boolean { if (actual == null) { return true } if (greaterThan) { return actual > this } if (fewerThan) { return this > actual } return this == actual } data class Sue( val id: Int, val children: Int?, val cats: Int?, val samoyeds: Int?, val pomeranians: Int?, val akitas: Int?, val vizslas: Int?, val goldfish: Int?, val trees: Int?, val cars: Int?, val perfumes: Int? ) val INSTRUCTION_REGEX = "Sue (\\d+): (.*)".toRegex() }
mit
79ecde711337863a01ba829d2aa7b38f
34.292683
108
0.460076
4.410061
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/full_image/ImagePagerAdapter.kt
3
1760
package com.bl_lia.kirakiratter.presentation.adapter.full_image import android.content.Context import android.support.v4.content.ContextCompat import android.support.v4.view.PagerAdapter import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.bumptech.glide.Glide import com.github.chrisbanes.photoview.PhotoView class ImagePagerAdapter( private val context: Context, private val imageUrls: List<String>, private val previewUrls: List<String> ) : PagerAdapter() { var currentImageView: ImageView? = null private set override fun getCount(): Int = imageUrls.size override fun instantiateItem(container: ViewGroup?, position: Int): Any { val imageView: ImageView = PhotoView(context).apply { setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent)) layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) } val previewReq = Glide.with(context).load(previewUrls[position]) Glide.with(context) .load(imageUrls[position]) .thumbnail(previewReq) .into(imageView) container?.addView(imageView) return imageView } override fun isViewFromObject(view: View?, obj: Any?): Boolean = view == obj as ImageView override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) { container?.removeView(`object` as ImageView) } override fun setPrimaryItem(container: ViewGroup?, position: Int, `object`: Any?) { super.setPrimaryItem(container, position, `object`) currentImageView = `object` as ImageView } }
mit
1d300cb4308be2e6fc308999d4028c66
34.22
123
0.698864
4.680851
false
false
false
false
square/leakcanary
shark-graph/src/main/java/shark/internal/hppc/HPPC.kt
2
2548
/* * Copyright 2010-2013, Carrot Search s.c., Boznicza 11/56, Poznan, Poland * * 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 shark.internal.hppc import java.util.Locale import kotlin.math.ceil import kotlin.math.max import kotlin.math.min /** * Code from https://github.com/carrotsearch/hppc copy pasted, inlined and converted to Kotlin. */ internal object HPPC { private const val PHI_C64 = -0x61c8864680b583ebL fun mixPhi(k: Long): Int { val h = k * PHI_C64 return (h xor h.ushr(32)).toInt() } private const val MIN_HASH_ARRAY_LENGTH = 4 private const val MAX_HASH_ARRAY_LENGTH = (-0x80000000).ushr(1) fun minBufferSize( elements: Int, loadFactor: Double ): Int { var length = ceil(elements / loadFactor) .toLong() if (length == elements.toLong()) { length++ } length = max(MIN_HASH_ARRAY_LENGTH.toLong(), nextHighestPowerOfTwo(length)) if (length > MAX_HASH_ARRAY_LENGTH) { throw RuntimeException( String.format( Locale.ROOT, "Maximum array size exceeded for this load factor (elements: %d, load factor: %f)", elements, loadFactor ) ) } return length.toInt() } fun nextHighestPowerOfTwo(input: Long): Long { var v = input v-- v = v or (v shr 1) v = v or (v shr 2) v = v or (v shr 4) v = v or (v shr 8) v = v or (v shr 16) v = v or (v shr 32) v++ return v } fun expandAtCount( arraySize: Int, loadFactor: Double ): Int { return min(arraySize - 1, ceil(arraySize * loadFactor).toInt()) } fun nextBufferSize( arraySize: Int, elements: Int, loadFactor: Double ): Int { if (arraySize == MAX_HASH_ARRAY_LENGTH) { throw RuntimeException( String.format( Locale.ROOT, "Maximum array size exceeded for this load factor (elements: %d, load factor: %f)", elements, loadFactor ) ) } return arraySize shl 1 } }
apache-2.0
057b97b5edd5bc59ec3b824806d697e7
23.980392
95
0.631083
3.682081
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/handler/rpl/isupport/Rpl005ChanModesHandler.kt
1
1509
package chat.willow.warren.handler.rpl.isupport import chat.willow.kale.irc.CharacterCodes import chat.willow.warren.helper.loggerFor import chat.willow.warren.state.ChannelModesState interface IRpl005ChanModesHandler { fun handle(rawValue: String, state: ChannelModesState): Boolean } object Rpl005ChanModesHandler : IRpl005ChanModesHandler { private val LOGGER = loggerFor<Rpl005ChanModesHandler>() override fun handle(rawValue: String, state: ChannelModesState): Boolean { // CHANMODES: eIb,k,l,imnpstSr val value = rawValue if (value.isNullOrEmpty()) { LOGGER.warn("CHANMODES value null or empty, bailing") return false } val modeValues = value.split(delimiters = CharacterCodes.COMMA) if (modeValues.size < 4) { LOGGER.warn("CHANMODES has less than 4 types, bailing") return false } val typeA = parseModes(modeValues[0]) val typeB = parseModes(modeValues[1]) val typeC = parseModes(modeValues[2]) val typeD = parseModes(modeValues[3]) state.typeA = typeA state.typeB = typeB state.typeC = typeC state.typeD = typeD LOGGER.debug("handled 005 CHANMODES: $state") return true } private fun parseModes(typeValues: String): Set<Char> { val parsedModes = (0..typeValues.length - 1) .map { typeValues[it] } .toSet() return parsedModes } }
isc
2b998c450bad875e6ce22fa96c57c16f
25.964286
78
0.641484
4.250704
false
false
false
false
Forinil/JavaScriptLogger
javascript-logger-servlet/src/main/kotlin/com/github/forinil/javascriptlogger/servlet/util/LogData.kt
1
436
package com.github.forinil.javascriptlogger.servlet.util /** * Created by Konrad Botor on 16.04.2017T13:50 * in package com.github.forinil.javascriptlogger.servlet.util in project JavaScriptLogger. */ data class LogData (var level: String = "INFO", var page: String = "", var function: String = "", var message: String = "", var errorCode: Int? = null)
agpl-3.0
7f1afcd90990cad404fcf7c1c49e871c
38.727273
91
0.598624
4.44898
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/utils.kt
1
1748
package org.jetbrains.dokka.gradle import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.UnknownDomainObjectException import org.gradle.api.provider.HasMultipleValues import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.util.Path import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import org.jetbrains.kotlin.gradle.plugin.KotlinTarget internal infix fun <T> Property<T>.by(value: T?) { this.set(value) } internal infix fun <T> Property<T>.by(value: Provider<T>) { this.set(value) } internal infix fun <T> HasMultipleValues<in T>.by(values: Iterable<T>) { this.set(values) } internal infix fun <T> HasMultipleValues<in T>.by(values: Provider<out Iterable<T>>) { this.set(values) } internal fun parsePath(path: String): Path = Path.path(path) internal val Project.kotlinOrNull: KotlinProjectExtension? get() = try { project.extensions.findByType(KotlinProjectExtension::class.java) } catch (e: NoClassDefFoundError) { null } internal val Project.kotlin: KotlinProjectExtension get() = project.extensions.getByType(KotlinProjectExtension::class.java) internal fun Project.isAndroidProject() = try { project.extensions.getByName("android") true } catch (e: UnknownDomainObjectException) { false } catch (e: ClassNotFoundException) { false } internal fun KotlinTarget.isAndroidTarget() = this.platformType == KotlinPlatformType.androidJvm internal fun <T : Any> NamedDomainObjectContainer<T>.maybeCreate(name: String, configuration: T.() -> Unit): T { return findByName(name) ?: create(name, configuration) }
apache-2.0
7dc73f76048815991078a71808588222
30.781818
112
0.762014
3.92809
false
false
false
false
FredJul/TaskGame
TaskGame/src/main/java/net/fred/taskgame/activities/CategoryActivity.kt
1
5706
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.activities import android.app.Activity import android.app.AlertDialog import android.graphics.Color import android.os.Bundle import android.os.Parcelable import android.view.View import com.larswerkman.holocolorpicker.ColorPicker.OnColorChangedListener import com.larswerkman.holocolorpicker.SaturationBar import com.larswerkman.holocolorpicker.ValueBar import kotlinx.android.synthetic.main.activity_category.* import net.fred.taskgame.R import net.fred.taskgame.models.Category import net.fred.taskgame.utils.Constants import net.fred.taskgame.utils.DbUtils import net.fred.taskgame.utils.NavigationUtils import net.frju.androidquery.gen.CATEGORY import org.jetbrains.anko.doAsync import org.jetbrains.anko.sdk21.coroutines.onClick import org.parceler.Parcels class CategoryActivity : Activity() { internal var category: Category? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_category) // Retrieving intent category = Parcels.unwrap<Category>(intent.getParcelableExtra<Parcelable>(Constants.EXTRA_CATEGORY)) // Getting Views from layout initViews() if (category == null) { category = Category() } else { populateViews() } } private fun initViews() { colorpicker_category.onColorChangedListener = OnColorChangedListener { colorpicker_category.oldCenterColor = colorpicker_category.color } // Long click on color picker to remove color colorpicker_category.setOnLongClickListener { colorpicker_category.color = Color.WHITE true } colorpicker_category.onClick { colorpicker_category.color = Color.WHITE } // Added invisible saturation and value bars to get achieve pastel colors val saturationBar = findViewById<SaturationBar>(R.id.saturationbar_category) saturationBar.setSaturation(0.4f) colorpicker_category.addSaturationBar(saturationBar) val valueBar = findViewById<ValueBar>(R.id.valuebar_category) valueBar.setValue(0.9f) colorpicker_category.addValueBar(valueBar) // discardBtn = (Button) findViewById(R.id.discard); // Buttons events delete.onClick { deleteCategory() } save.onClick { // In case category name is not compiled a message will be shown if (category_title.text.toString().isNotEmpty()) { saveCategory() } else { category_title.error = getString(R.string.category_missing_title) } } } private fun populateViews() { category?.let { cat -> category_title.setText(cat.name) category_description.setText(cat.description) // Reset picker to saved color colorpicker_category.color = cat.color colorpicker_category.oldCenterColor = cat.color delete.visibility = View.VISIBLE } } /** * Category saving */ private fun saveCategory() { category?.let { cat -> cat.name = category_title.text.toString() cat.description = category_description.text.toString() cat.color = colorpicker_category.color // Saved to DB and new id or update result catched CATEGORY.save(cat).query() cat.saveInFirebase() // Sets result to show proper message intent.putExtra(Constants.EXTRA_CATEGORY, Parcels.wrap<Category>(cat)) setResult(Activity.RESULT_OK, intent) finish() } } private fun deleteCategory() { category?.let { cat -> // Retrieving how many tasks are categorized with category to be deleted val count = DbUtils.getActiveTaskCountByCategory(cat) var msg = "" if (count > 0) { msg = getString(R.string.delete_category_confirmation).replace("$1$", count.toString()) } AlertDialog.Builder(this) .setTitle(R.string.delete_unused_category_confirmation) .setMessage(msg) .setPositiveButton(R.string.confirm) { dialog, id -> // Changes navigation if actually are shown tasks associated with this category if (NavigationUtils.isDisplayingCategory(cat)) { NavigationUtils.navigation = NavigationUtils.TASKS } // Removes category and edit tasks associated with it doAsync { DbUtils.deleteCategory(cat) } // Sets result to show proper message setResult(Activity.RESULT_FIRST_USER) finish() }.show() } } }
gpl-3.0
5910f17c75407b025ffc4d6fc0bd607b
36.294118
145
0.639327
4.807077
false
false
false
false
googleapis/gax-kotlin
kgax-grpc-android/src/main/kotlin/com/google/api/kgax/grpc/LongRunningCall.kt
1
3167
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kgax.grpc import com.google.common.util.concurrent.ListenableFuture import com.google.longrunning.GetOperationRequest import com.google.longrunning.Operation import com.google.longrunning.OperationsClientStub import com.google.protobuf.ByteString import com.google.protobuf.MessageLite import io.grpc.Status import io.grpc.stub.AbstractStub import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope /** Resolves long running operations. */ class LongRunningCall<T : MessageLite>( private val stub: GrpcClientStub<OperationsClientStub>, deferred: Deferred<Operation>, responseType: Class<T> ) : LongRunningCallBase<T, Operation>(deferred, responseType) { override suspend fun nextOperation(op: Operation) = stub.execute { it.getOperation( GetOperationRequest.newBuilder() .setName(operation!!.name) .build() ) } override fun isOperationDone(op: Operation) = op.done override fun parse(operation: Operation, type: Class<T>): T { if (operation.error == null || operation.error.code == Status.Code.OK.value()) { @Suppress("UNCHECKED_CAST") return type.getMethod( "parseFrom", ByteString::class.java ).invoke(null, operation.response.value) as T } throw RuntimeException("Operation completed with error: ${operation.error.code}\n details: ${operation.error.message}") } } /** * Execute a long running operation. For example: * * ``` * val response = stub.executeLongRunning(MyLongRunningResponse::class.java) { * it.myLongRunningMethod(...) * } * print("${response.body}") * ``` * * The [method] lambda should perform a future method call on the stub given as the * first parameter. The result along with any additional information, such as * [ResponseMetadata], will be returned as a [LongRunningCall]. The [type] given * must match the return type of the Operation. * * An optional [context] can be supplied to enable arbitrary retry strategies. */ suspend fun <RespT : MessageLite, T : AbstractStub<T>> GrpcClientStub<T>.executeLongRunning( type: Class<RespT>, context: String = "", method: (T) -> ListenableFuture<Operation> ): LongRunningCall<RespT> = coroutineScope { val operationsStub = GrpcClientStub(OperationsClientStub(stubWithContext().channel), options) val deferred = async { execute(context, method) } LongRunningCall(operationsStub, deferred, type) }
apache-2.0
f162577974dc9a834f8e8b68ac5bba67
35.825581
127
0.713925
4.268194
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/entities/TiviEntity.kt
1
1700
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.entities interface TiviEntity { val id: Long } interface TraktIdEntity { val traktId: Int? } interface TmdbIdEntity { val tmdbId: Int? } interface TmdbImageEntity : TiviEntity { val path: String val type: ImageType val language: String? val rating: Float val isPrimary: Boolean } enum class ImageType(val storageKey: String) { BACKDROP("backdrop"), POSTER("poster"), LOGO("logo") } internal fun <T : TmdbImageEntity> Collection<T>.findHighestRatedPoster(): T? { if (size <= 1) return firstOrNull() @Suppress("DEPRECATION") // Can't use maxByOrNull until we're API version 1.4 return filter { it.type == ImageType.POSTER } .maxByOrNull { it.rating + (if (it.isPrimary) 10f else 0f) } } internal fun <T : TmdbImageEntity> Collection<T>.findHighestRatedBackdrop(): T? { if (size <= 1) return firstOrNull() @Suppress("DEPRECATION") // Can't use maxByOrNull until we're API version 1.4 return filter { it.type == ImageType.BACKDROP } .maxByOrNull { it.rating + (if (it.isPrimary) 10f else 0f) } }
apache-2.0
3c4bb12f1c0c3120bd80cc1f94ac8b66
28.824561
81
0.696471
3.908046
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/entity/traits/feat/SpellPenetration.kt
1
2118
/* * The MIT License * * Copyright 2015 Nathan Templon. * * 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.jupiter.europa.entity.traits.feat import com.badlogic.gdx.graphics.g2d.Sprite import com.badlogic.gdx.utils.Json import com.badlogic.gdx.utils.JsonValue import com.jupiter.europa.entity.effects.AttributeModifierEffect import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.entity.traits.FeatNotPresentQualifier /** * Created by nathan on 5/18/15. */ public class SpellPenetration : AttributeModifierEffect(), Feat { // Feat Implementation override val qualifier = FeatNotPresentQualifier(javaClass<SpellPenetration>()) override val icon = Sprite() override val name = "Spell Penetration" override val description = "Your spells ignore 10 of their targets' Spell Resistance." override val modifiers = mapOf(Pair(AttributeSet.Attributes.SPELL_PENETRATION, 10)) // Serializable (json) implementation override fun write(json: Json) { } override fun read(json: Json, jsonData: JsonValue) { } }
mit
22a7c331b8f72f8fa0ef14e17ea88c49
36.821429
90
0.760151
4.358025
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/event/ItemLogService.kt
1
1611
package org.stt.event import net.engio.mbassy.bus.MBassador import net.engio.mbassy.listener.Handler import org.stt.Service import org.stt.command.CommandFormatter import org.stt.model.ItemDeleted import org.stt.model.ItemInserted import org.stt.model.ItemReplaced import org.stt.model.TimeTrackingItem import org.stt.time.DateTimes import java.io.PrintWriter import java.time.LocalDateTime import javax.inject.Inject import javax.inject.Named /** * Created by dante on 20.03.15. */ class ItemLogService @Inject constructor(@Named("itemLog") val out: PrintWriter, val eventBus: MBassador<Any>, val formatter: CommandFormatter) : Service { @Handler fun itemInserted(event: ItemInserted) = log("inserted", event.newItem) private fun log(eventType: String, item: TimeTrackingItem) { val command = formatter.asNewItemCommandText(item) val outputLine = StringBuilder() addCurrentTimeTo(outputLine) outputLine.append(", ").append(eventType).append(": ") outputLine.append(command) out.println(outputLine) } private fun addCurrentTimeTo(outputLine: StringBuilder) = outputLine.append(DateTimes.DATE_TIME_FORMATTER_YYYY_MM_DD_HH_MM_SS.format(LocalDateTime.now())) @Handler fun itemDeleted(event: ItemDeleted) = log("deleted", event.deletedItem) @Handler fun itemReplaced(event: ItemReplaced) { log("before_update", event.beforeUpdate) log("after_update", event.afterUpdate) } override fun start() = eventBus.subscribe(this) override fun stop() = out.close() }
gpl-3.0
d4d75ed98da331b6d945f1eb6b3208a0
29.980769
108
0.719429
3.948529
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/wheelchair_access/AddWheelchairAccessBusiness.kt
1
5485
package de.westnordost.streetcomplete.quests.wheelchair_access import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.WHEELCHAIR import de.westnordost.streetcomplete.ktx.arrayOfNotNull import java.util.concurrent.FutureTask class AddWheelchairAccessBusiness( private val featureDictionaryFuture: FutureTask<FeatureDictionary> ) : OsmFilterQuestType<WheelchairAccess>() { override val elementFilter = """ nodes, ways, relations with access !~ no|private and ( shop and shop !~ no|vacant or amenity = parking and parking = multi-storey or amenity = recycling and recycling_type = centre or tourism = information and information = office or """.trimIndent() + // The common list is shared by the name quest, the opening hours quest and the wheelchair quest. // So when adding other tags to the common list keep in mind that they need to be appropriate for all those quests. // Independent tags can by added in the "wheelchair only" tab. mapOf( "amenity" to arrayOf( // common "restaurant", "cafe", "ice_cream", "fast_food", "bar", "pub", "biergarten", "food_court", "nightclub", // eat & drink "cinema", "planetarium", "casino", // amenities "townhall", "courthouse", "embassy", "community_centre", "youth_centre", "library", // civic "bank", "bureau_de_change", "money_transfer", "post_office", "marketplace", "internet_cafe", // commercial "car_wash", "car_rental", "fuel", // car stuff "dentist", "doctors", "clinic", "pharmacy", "veterinary", // health "animal_boarding", "animal_shelter", "animal_breeding", // animals // name & wheelchair only "theatre", // culture "conference_centre", "arts_centre", // events "police", "ranger_station", // civic "ferry_terminal", // transport "place_of_worship", // religious "hospital" // health care ), "tourism" to arrayOf( // common "zoo", "aquarium", "theme_park", "gallery", "museum", // name & wheelchair "attraction", "hotel", "guest_house", "motel", "hostel", "alpine_hut", "apartment", "resort", "camp_site", "caravan_site", "chalet", // accommodations // wheelchair only "viewpoint" // and tourism = information, see above ), "leisure" to arrayOf( // common "fitness_centre", "golf_course", "water_park", "miniature_golf", "bowling_alley", "amusement_arcade", "adult_gaming_centre", "tanning_salon", // name & wheelchair "sports_centre", "stadium" ), "office" to arrayOf( // common "insurance", "government", "travel_agent", "tax_advisor", "religion", "employment_agency", "diplomatic", // name & wheelchair "lawyer", "estate_agent", "political_party", "therapist" ), "craft" to arrayOf( // common "carpenter", "shoemaker", "tailor", "photographer", "dressmaker", "electronics_repair", "key_cutter", "stonemason", // name & wheelchair "winery" ) ).map { it.key + " ~ " + it.value.joinToString("|") }.joinToString("\n or ") + "\n) and !wheelchair and (name or brand)" override val commitMessage = "Add wheelchair access" override val wikiLink = "Key:wheelchair" override val icon = R.drawable.ic_quest_wheelchair_shop override val isReplaceShopEnabled = true override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside override val questTypeAchievements = listOf(WHEELCHAIR) override fun getTitle(tags: Map<String, String>) = if (hasFeatureName(tags)) R.string.quest_wheelchairAccess_name_type_title else R.string.quest_wheelchairAccess_name_title override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> { val name = tags["name"] ?: tags["brand"] return arrayOfNotNull(name, featureName.value) } override fun createForm() = AddWheelchairAccessBusinessForm() override fun applyAnswerTo(answer: WheelchairAccess, changes: StringMapChangesBuilder) { changes.add("wheelchair", answer.osmValue) } private fun hasFeatureName(tags: Map<String, String>): Boolean = featureDictionaryFuture.get().byTags(tags).isSuggestion(false).find().isNotEmpty() }
gpl-3.0
4dfc0fb2a718628baa7fee0ff629a03f
47.114035
152
0.561896
4.582289
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/PublishersActivity.kt
1
2081
package com.boardgamegeek.ui import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.viewModels import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.extensions.setActionBarCount import com.boardgamegeek.ui.viewmodel.PublishersViewModel import com.boardgamegeek.ui.viewmodel.PublishersViewModel.SortType class PublishersActivity : SimpleSinglePaneActivity() { private var numberOfPublishers = -1 private var sortBy = SortType.ITEM_COUNT private val viewModel by viewModels<PublishersViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.publishers.observe(this) { numberOfPublishers = it?.size ?: 0 invalidateOptionsMenu() } viewModel.sort.observe(this) { sortBy = it.sortType invalidateOptionsMenu() } } override fun onCreatePane(intent: Intent): Fragment = PublishersFragment() override val optionsMenuId = R.menu.publishers override fun onPrepareOptionsMenu(menu: Menu): Boolean { super.onPrepareOptionsMenu(menu) menu.findItem(when (sortBy) { SortType.NAME -> R.id.menu_sort_name SortType.ITEM_COUNT -> R.id.menu_sort_item_count SortType.WHITMORE_SCORE -> R.id.menu_sort_whitmore_score })?.isChecked = true menu.setActionBarCount(R.id.menu_list_count, numberOfPublishers, getString(R.string.by_prefix, title)) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_sort_name -> viewModel.sort(SortType.NAME) R.id.menu_sort_item_count -> viewModel.sort(SortType.ITEM_COUNT) R.id.menu_sort_whitmore_score -> viewModel.sort(SortType.WHITMORE_SCORE) R.id.menu_refresh -> viewModel.refresh() else -> return super.onOptionsItemSelected(item) } return true } }
gpl-3.0
565c895027f4a311bd723e053c2a26b4
35.508772
110
0.693417
4.504329
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/magic/CommandMagic.kt
1
16145
@file:Suppress("MemberVisibilityCanBePrivate") package nl.hannahsten.texifyidea.util.magic import com.intellij.openapi.project.Project import nl.hannahsten.texifyidea.lang.alias.CommandManager import nl.hannahsten.texifyidea.lang.commands.LatexBiblatexCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexCommand import nl.hannahsten.texifyidea.lang.commands.LatexGenericMathCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexGlossariesCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexIfCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexListingCommand.LSTINPUTLISTING import nl.hannahsten.texifyidea.lang.commands.LatexMathtoolsRegularCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexNatbibCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexNewDefinitionCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexOperatorCommand.* import nl.hannahsten.texifyidea.lang.commands.LatexUncategorizedStmaryrdSymbols.BIG_SQUARE_CAP import nl.hannahsten.texifyidea.lang.commands.LatexXparseCommand.* import java.awt.Color object CommandMagic { /** * LaTeX commands that make the text take up more vertical space. */ val high = hashSetOf( FRAC.cmd, DFRAC.cmd, SQUARE_ROOT.cmd, SUM.cmd, INTEGRAL.cmd, DOUBLE_INTEGRAL.cmd, TRIPLE_INTEGRAL.cmd, QUADRUPLE_INTEGRAL.cmd, N_ARY_PRODUCT.cmd, N_ARY_UNION.cmd, N_ARY_INTERSECTION.cmd, N_ARY_SQUARE_UNION.cmd, BIG_SQUARE_CAP.cmd ) /** * Level of labeled commands. */ val labeledLevels: Map<LatexCommand, Int> = mapOf( // See page 23 of the LaTeX Companion PART to -1, // actually, it is level 0 in classes that do not define \chapter and -1 in book and report CHAPTER to 0, SECTION to 1, SUBSECTION to 2, SUBSUBSECTION to 3, PARAGRAPH to 4, SUBPARAGRAPH to 5 ) /** Section commands sorted from large to small. */ val sectioningCommands = labeledLevels.entries.sortedBy { it.value }.map { it.key } /** * Commands that define a label via an optional parameter */ @JvmField val labelAsParameter = hashSetOf(LSTINPUTLISTING.cmd) /** * All commands that mark some kind of section. */ val sectionMarkers = listOf( PART, CHAPTER, SECTION, SUBSECTION, SUBSUBSECTION, PARAGRAPH, SUBPARAGRAPH ).map { it.cmd } /** * The colours that each section separator has. */ val sectionSeparatorColors = mapOf( PART.cmd to Color(152, 152, 152), CHAPTER.cmd to Color(172, 172, 172), SECTION.cmd to Color(182, 182, 182), SUBSECTION.cmd to Color(202, 202, 202), SUBSUBSECTION.cmd to Color(212, 212, 212), PARAGRAPH.cmd to Color(222, 222, 222), SUBPARAGRAPH.cmd to Color(232, 232, 232) ) /** * LaTeX commands that increase a counter that can be labeled. */ val increasesCounter = hashSetOf(CAPTION.cmd, CAPTIONOF.cmd, CHAPTER.cmd, SECTION.cmd, SUBSECTION.cmd, ITEM.cmd, LSTINPUTLISTING.cmd) /** * All commands that represent a reference to a label, excluding user defined commands. */ val labelReferenceWithoutCustomCommands = hashSetOf( REF, EQREF, NAMEREF, AUTOREF, FULLREF, PAGEREF, VREF, AUTOREF_CAPITAL, CREF, CREF_CAPITAL, LABELCREF, CPAGEREF ).map { it.cmd }.toSet() /** * All commands that represent a reference to a bibliography entry/item. */ val bibliographyReference = hashSetOf( CITE, NOCITE, CITEP, CITEP_STAR, CITET, CITET_STAR, CITEP, CITEP_STAR_CAPITALIZED, CITET_CAPITALIZED, CITET_STAR_CAPITALIZED, CITEALP, CITEALP_STAR, CITEALT, CITEALT_STAR, CITEALP_CAPITALIZED, CITEALP_STAR_CAPITALIZED, CITEALT_CAPITALIZED, CITEALT_STAR_CAPITALIZED, CITEAUTHOR, CITEAUTHOR_STAR, CITEAUTHOR_CAPITALIZED, CITEAUTHOR_STAR_CAPITALIZED, CITEYEAR, CITEYEARPAR, PARENCITE, PARENCITE_CAPITALIZED, FOOTCITE, FOOTCITETEXT, TEXTCITE, TEXTCITE_CAPITALIZED, SMARTCITE, SMARTCITE_CAPITALIZED, CITE_STAR, PARENCITE_STAR, SUPERCITE, AUTOCITE, AUTOCITE_CAPITALIZED, AUTOCITE_STAR, AUTOCITE_STAR_CAPITALIZED, CITETITLE, CITETITLE_STAR, CITEYEAR_STAR, CITEDATE, CITEDATE_STAR, CITEURL, VOLCITE, VOLCITE_CAPITALIZED, PVOLCITE, PVOLCITE_CAPITALIZED, FVOLCITE, FVOLCITE_CAPITALIZED, FTVOLCITE, SVOLCITE, SVOLCITE_CAPITALIZED, TVOLCITE, TVOLCITE_CAPITALIZED, AVOLCITE, AVOLCITE_CAPITALIZED, FULLCITE, FOOTFULLCITE, NOTECITE, NOTECITE_CAPITALIZED, PNOTECITE, FNOTECITE ).map { it.cmd }.toSet() /** * All commands that define a glossary entry of the glossaries package (e.g. \newacronym). */ val glossaryEntry = hashSetOf(NEWGLOSSARYENTRY, LONGNEWGLOSSARYENTRY, NEWACRONYM, NEWABBREVIATION).map { it.cmd }.toSet() /** * All commands that reference a glossary entry from the glossaries package (e.g. \gls). */ val glossaryReference = hashSetOf(GLS, GLSUPPER, GLSPLURAL, GLSPLURALUPPER).map { it.cmd }.toSet() /** * All commands that represent some kind of reference (think \ref and \cite). */ val reference = labelReferenceWithoutCustomCommands + bibliographyReference /** * Commands from the import package which require an absolute path as first parameter. */ val absoluteImportCommands = setOf(INCLUDEFROM.cmd, INPUTFROM.cmd, IMPORT.cmd) /** * Commands from the import package which require a relative path as first parameter. */ val relativeImportCommands = setOf(SUBIMPORT.cmd, SUBINPUTFROM.cmd, SUBINCLUDEFROM.cmd) /** * All commands that define labels and that are present by default. * To include user defined commands, use [getLabelDefinitionCommands] (may be significantly slower). */ val labelDefinitionsWithoutCustomCommands = setOf(LABEL.cmd) /** * Get all commands defining labels, including user defined commands. * If you need to know which parameters of user defined commands define a label, use [CommandManager.labelAliasesInfo]. * * This will check if the cache of user defined commands needs to be updated, based on the given project, and therefore may take some time. */ fun getLabelDefinitionCommands(project: Project): Set<String> { // Check if updates are needed CommandManager.updateAliases(labelDefinitionsWithoutCustomCommands, project) return CommandManager.getAliases(labelDefinitionsWithoutCustomCommands.first()) } /** * Get all commands defining labels, including user defined commands. This will not check if the aliases need to be updated. */ fun getLabelDefinitionCommands() = CommandManager.getAliases(labelDefinitionsWithoutCustomCommands.first()) /** * All commands that define bibliography items. */ val bibliographyItems = setOf(BIBITEM.cmd) /** * All math operators without a leading slash. * * Reference [Unofficial LaTeX2e reference manual](https://latexref.xyz/Math-functions.html) */ @JvmField val slashlessMathOperators = hashSetOf( INVERSE_COSINE, INVERSE_SINE, INVERSE_TANGENT, ARGUMENT, BMOD, COSINE, HYPERBOLIC_COSINE, COTANGENT, HYPERBOLIC_COTANGENT, COSECANT, DEGREES, DERMINANT, DIMENSION, EXPONENTIAL, GREATEST_COMMON_DIVISOR, HOMOMORPHISM, INFINUM, KERNEL, BASE_2_LOGARITHM, LIMIT, LIMIT_INFERIOR, LIMIT_SUPERIOR, NATURAL_LOGARITHM, LOGARITHM, MAXIMUM, MINIMUM, PMOD, PROBABILITY, SECANT, SINE, HYPERBOLIC_SINE, SUPREMUM, TANGENT, HBOLICTANGENT ) /** * All commands that define regular commands, and that require that the command is not already defined. */ val regularStrictCommandDefinitions = hashSetOf( NEWCOMMAND.cmd, NEWCOMMAND_STAR.cmd, NEWIF.cmd, NEWDOCUMENTCOMMAND.cmd, ) /** * Commands that define other command but don't complain if it is already defined. */ val flexibleCommandDefinitions = setOf( PROVIDECOMMAND, // Does nothing if command exists PROVIDECOMMAND_STAR, PROVIDEDOCUMENTCOMMAND, // Does nothing if command exists DECLAREDOCUMENTCOMMAND, DEF, LET, ).map { it.cmd } /** * All commands that define or redefine other commands, whether it exists or not. */ val commandRedefinitions = setOf( RENEWCOMMAND, RENEWCOMMAND_STAR, CATCODE, // Not really redefining commands, but characters ).map { it.cmd } + flexibleCommandDefinitions /** * All commands that define or redefine regular commands. */ val regularCommandDefinitionsAndRedefinitions = regularStrictCommandDefinitions + commandRedefinitions /** * All commands that define commands that should be used exclusively * in math mode. */ val mathCommandDefinitions = hashSetOf( DECLARE_MATH_OPERATOR.cmd, DECLARE_PAIRED_DELIMITER.cmd, DECLARE_PAIRED_DELIMITER_X.cmd, DECLARE_PAIRED_DELIMITER_XPP.cmd ) /** * All commands that can define regular commands. */ val commandDefinitions = regularStrictCommandDefinitions + mathCommandDefinitions + flexibleCommandDefinitions /** * All commands that (re)define new commands. */ val commandDefinitionsAndRedefinitions = regularCommandDefinitionsAndRedefinitions + mathCommandDefinitions /** * All commands that define new documentclasses. */ val classDefinitions = hashSetOf(PROVIDESCLASS.cmd) /** * All commands that define new packages. */ val packageDefinitions = hashSetOf(PROVIDESPACKAGE.cmd) /** * All commands that define new environments. */ val environmentDefinitions = hashSetOf( NEWENVIRONMENT, NEWTHEOREM, NEWDOCUMENTENVIRONMENT, PROVIDEDOCUMENTENVIRONMENT, DECLAREDOCUMENTENVIRONMENT ).map { it.cmd } /** * All commands that define or redefine other environments, whether it exists or not. */ val environmentRedefinitions = hashSetOf(RENEWENVIRONMENT.cmd) /** * All commands that define stuff like classes, environments, and definitions. */ val definitions = commandDefinitionsAndRedefinitions + classDefinitions + packageDefinitions + environmentDefinitions /** * Commands for which TeXiFy-IDEA has essential custom behaviour and which should not be redefined. */ val fragile = hashSetOf( "\\addtocounter", "\\begin", "\\chapter", "\\def", "\\documentclass", "\\end", "\\include", "\\includeonly", "\\input", "\\label", "\\let", "\\newcommand", "\\overline", "\\paragraph", "\\part", "\\renewcommand", "\\section", "\\setcounter", "\\sout", "\\subparagraph", "\\subsection", "\\subsubsection", "\\textbf", "\\textit", "\\textsc", "\\textsl", "\\texttt", "\\underline", "\\[", "\\]", "\\newenvironment", "\\bibitem", "\\NewDocumentCommand", "\\ProvideDocumentCommand", "\\DeclareDocumentCommand", "\\NewDocumentEnvironment", "\\ProvideDocumentEnvironment", "\\DeclareDocumentEnvironment" ) /** * Commands that should not have the given file extensions. */ val illegalExtensions = mapOf( INCLUDE.cmd to listOf(".tex"), SUBFILEINCLUDE.cmd to listOf(".tex"), BIBLIOGRAPHY.cmd to listOf(".bib"), INCLUDEGRAPHICS.cmd to FileMagic.graphicFileExtensions.map { ".$it" }, // https://tex.stackexchange.com/a/1075/98850 USEPACKAGE.cmd to listOf(".sty"), EXTERNALDOCUMENT.cmd to listOf(".tex"), ) /** * Commands which can include packages in optional or required arguments. */ val packageInclusionCommands = setOf( USEPACKAGE, REQUIREPACKAGE, DOCUMENTCLASS, LOADCLASS ).map { it.cmd }.toSet() val tikzLibraryInclusionCommands = setOf(USETIKZLIBRARY.cmd) val pgfplotsLibraryInclusionCommands = setOf(USEPGFPLOTSLIBRARY.cmd) /** * Commands that should have the given file extensions. */ val requiredExtensions = mapOf( ADDBIBRESOURCE.cmd to listOf("bib") ) /** * Extensions that should only be scanned for the provided include commands. */ val includeOnlyExtensions: Map<String, Set<String>> = mapOf( INCLUDE.cmd to hashSetOf("tex"), INCLUDEONLY.cmd to hashSetOf("tex"), SUBFILE.cmd to hashSetOf("tex"), SUBFILEINCLUDE.cmd to hashSetOf("tex"), BIBLIOGRAPHY.cmd to hashSetOf("bib"), ADDBIBRESOURCE.cmd to hashSetOf("bib"), REQUIREPACKAGE.cmd to hashSetOf("sty"), USEPACKAGE.cmd to hashSetOf("sty"), DOCUMENTCLASS.cmd to hashSetOf("cls"), LOADCLASS.cmd to hashSetOf("cls"), EXTERNALDOCUMENT.cmd to hashSetOf("tex") // Not completely true, as it only includes labels. Technically it references an aux file ) /** * Commands that include bib files. */ val bibliographyIncludeCommands = includeOnlyExtensions.entries.filter { it.value.contains("bib") }.map { it.key } @Suppress("unused") val startIfs = hashSetOf( IF, IFCAT, IFX, IFCASE, IFNUM, IFODD, IFHMODE, IFVMODE, IFMMODE, IFINNER, IFDIM, IFVOID, IFHBOX, IFVBOX, IFEOF, IFTRUE, IFFALSE ).map { it.cmd } /** * All commands that end if. */ val endIfs = hashSetOf(FI.cmd) /** * All commands that at first glance look like \if-esque commands, but that actually aren't. */ val ignoredIfs = hashSetOf("\\newif", "\\iff", "\\ifthenelse", "\\iftoggle", "\\ifoot", "\\ifcsvstrcmp") /** * List of all TeX style primitives. */ val stylePrimitives = listOf( RM.cmd, SF.cmd, TT.cmd, IT.cmd, SL.cmd, SC.cmd, BF.cmd ) /** * The LaTeX counterparts of all [stylePrimitives] commands where %s is the content. */ val stylePrimitveReplacements = listOf( "\\textrm{%s}", "\\textsf{%s}", "\\texttt{%s}", "\\textit{%s}", "\\textsl{%s}", "\\textsc{%s}", "\\textbf{%s}" ) /** * Set of text styling commands */ val textStyles = setOf( TEXTRM, TEXTSF, TEXTTT, TEXTIT, TEXTSL, TEXTSC, TEXTBF, EMPH, TEXTUP, TEXTMD ).map { it.cmd } /** * All LaTeX commands that contain a url (in their first parameter). */ val urls = hashSetOf(URL.cmd, HREF.cmd) /** * All BibTeX tags that take a url as their parameter. */ val bibUrls = hashSetOf("url", "biburl") /** * Commands that always contain a certain language. * * Maps the name of the command to the registered Language id. */ val languageInjections = hashMapOf( DIRECTLUA.cmd to "Lua", LUAEXEC.cmd to "Lua" ) /** * Commands that have a verbatim argument. * * Maps a command to a boolean that is true when the required argument can be specified with any pair of characters. */ val verbatim = hashMapOf( "verb" to true, "verb*" to true, "directlua" to false, "luaexec" to false, "lstinline" to true ) }
mit
34d5a51ef6bdf3462545c3c125fe616a
33.573876
143
0.637411
4.367054
false
false
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/KotlinActivityGenerator.kt
1
8319
/* Copyright 2021 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.androidstudiopoet.generators.android_modules import com.google.androidstudiopoet.models.ActivityBlueprint import com.google.androidstudiopoet.models.AnnotationBlueprint import com.google.androidstudiopoet.models.FieldBlueprint import com.google.androidstudiopoet.models.LayoutBlueprint import com.google.androidstudiopoet.writers.FileWriter import com.squareup.kotlinpoet.* class KotlinActivityGenerator(var fileWriter: FileWriter): ActivityGenerator { override fun generate(blueprint: ActivityBlueprint) { val activityClassBuilder = blueprint.toClazzSpec() blueprint.fields.forEach { activityClassBuilder.addProperty(it.toPropertySpec()) } activityClassBuilder.addFunction(blueprint.toOnCreateFunSpec()) val fileSpec = FileSpec.builder(blueprint.packageName, blueprint.className) .addType(activityClassBuilder.build()) blueprint.toComposeFunc()?.let(fileSpec::addFunction) val content = buildString { fileSpec.build().writeTo(this) } fileWriter.writeToFile(content, "${blueprint.where}/${blueprint.className}.kt") } private fun ActivityBlueprint.toClazzSpec(): TypeSpec.Builder { val superClass = if (enableCompose) { ClassName("androidx.activity", "ComponentActivity") } else { ClassName("android.app", "Activity") } return TypeSpec.classBuilder(className) .superclass(superClass) } private fun FieldBlueprint.toPropertySpec(): PropertySpec { val propertySpec = PropertySpec.builder(name, ClassName.bestGuess(typeName)) .mutable() .addModifiers(KModifier.LATEINIT) annotations.forEach { propertySpec.addAnnotation(it.toAnnotationSpec()) } return propertySpec.build() } private fun AnnotationBlueprint.toAnnotationSpec(): AnnotationSpec { val builder = AnnotationSpec.builder(ClassName.bestGuess(className)) params.forEach { (key, value) -> builder.addMember("$key = %S", value) } return builder.build() } private fun ActivityBlueprint.toComposeFunc(): FunSpec? { if (enableCompose) { val text = MemberName("androidx.compose.material", "Text") val column = MemberName("androidx.compose.foundation.layout", "Column") val image = MemberName("androidx.compose.foundation", "Image") val clickable = MemberName("androidx.compose.foundation", "clickable") val rememberScrollableState = MemberName("androidx.compose.foundation", "rememberScrollState") val verticalScroll = MemberName("androidx.compose.foundation", "verticalScroll") val modifier = ClassName("androidx.compose.ui", "Modifier") val painterResource = MemberName("androidx.compose.ui.res", "painterResource") val stringResource = MemberName("androidx.compose.ui.res", "stringResource") val builder = FunSpec.builder("${className}Screen") .addAnnotation(ClassName("androidx.compose.runtime", "Composable")) .addStatement("val scrollState = %M()", rememberScrollableState) .beginControlFlow("%M(modifier = %T.%M(scrollState))", column, modifier, verticalScroll) layout.textViewsBlueprints.forEach { textViewBlueprint -> if (textViewBlueprint.actionClass != null) { builder.addStatement("%M(text = %M(R.string.%L), modifier = %T.%M { %T().%L() })", text, stringResource, textViewBlueprint.stringName, modifier, clickable, ClassName.bestGuess(textViewBlueprint.actionClass.fullClassName), textViewBlueprint.actionClass.getMethodToCallFromOutside()!!.methodName ) } else { builder.addStatement("%M(text = %M(R.string.%L))", text, stringResource, textViewBlueprint.stringName) } } layout.imageViewsBlueprints.forEach { imageViewBlueprint -> if (imageViewBlueprint.actionClass != null) { builder.addStatement("%M(painter = %M(R.drawable.%L), contentDescription = null, modifier = %T.%M { %T().%L() })", image, painterResource, imageViewBlueprint.imageName, modifier, clickable, ClassName.bestGuess(imageViewBlueprint.actionClass.fullClassName), imageViewBlueprint.actionClass.getMethodToCallFromOutside()!!.methodName ) } else { builder.addStatement("%M(painter = %M(R.drawable.%L), contentDescription = null)", image, painterResource, imageViewBlueprint.imageName ) } } builder.endControlFlow() layout.layoutsToInclude.forEach { screenFunctionFullQualifiedName -> val packageName = screenFunctionFullQualifiedName.substring(0, screenFunctionFullQualifiedName.lastIndexOf('.')) val functionName = screenFunctionFullQualifiedName.substring(1 + screenFunctionFullQualifiedName.lastIndexOf('.')) builder.addStatement("%M()", MemberName(packageName, functionName)) } return builder.build() } else { return null } } private fun ActivityBlueprint.toOnCreateFunSpec(): FunSpec { val builder = FunSpec.builder("onCreate") .addModifiers(KModifier.OVERRIDE) .addParameter("savedInstanceState", ClassName("android.os", "Bundle").copy(nullable = true)) .addStatement("super.onCreate(savedInstanceState)") classToReferFromActivity.getMethodToCallFromOutside()?.let { val className = ClassName.bestGuess(it.className) builder.addStatement("%T().%N()", className, it.methodName) } if (enableCompose) { val setContent = MemberName("androidx.activity.compose", "setContent") builder.beginControlFlow("%M", setContent) builder.addStatement("${className}Screen()") builder.endControlFlow() } else if (enableDataBinding) { val bindingClassName = ClassName.bestGuess(dataBindingClassName) val dataBindingUtil = ClassName("androidx.databinding", "DataBindingUtil") builder.addStatement("val binding: %T = %T.setContentView(this, R.layout.${layout.name})", bindingClassName, dataBindingUtil) listenerClassesForDataBinding.forEach { builder.addStatement("binding.%N = %T()", it.className.decapitalize(), ClassName.bestGuess(it.fullClassName)) } } else if (enableViewBinding) { val dataBindingClass = ClassName("$packageName.databinding", layout.findViewBindingClassName()) builder.addStatement("val binding = %T.inflate(layoutInflater)", dataBindingClass) builder.addStatement("setContentView(binding.root)") } else { builder.addStatement("setContentView(R.layout.${layout.name})") } return builder.build() } } private fun LayoutBlueprint.findViewBindingClassName(): String = name.split("_").joinToString(separator = "") { it.capitalize() } + "Binding"
apache-2.0
be551eb31fb4c4322540a32c8c862265
48.517857
137
0.626878
5.583221
false
false
false
false
PaulWoitaschek/Voice
app/src/main/kotlin/voice/app/features/bookmarks/dialogs/AddBookmarkDialog.kt
1
1819
package voice.app.features.bookmarks.dialogs import android.app.Dialog import android.os.Bundle import android.text.InputType import android.view.inputmethod.EditorInfo import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.input.getInputField import com.afollestad.materialdialogs.input.input import com.bluelinelabs.conductor.Controller import voice.app.R import voice.common.conductor.DialogController class AddBookmarkDialog : DialogController() { override fun onCreateDialog(savedViewState: Bundle?): Dialog { val inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT or InputType.TYPE_TEXT_FLAG_MULTI_LINE val dialog = MaterialDialog(activity!!).apply { title(R.string.bookmark) @Suppress("CheckResult") input(hintRes = R.string.bookmark_edit_hint, allowEmpty = true, inputType = inputType) { _, charSequence -> val title = charSequence.toString() val callback = targetController as Callback callback.onBookmarkNameChosen(title) } positiveButton(R.string.dialog_confirm) } val editText = dialog.getInputField() editText.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val title = editText.text.toString() val callback = targetController as Callback callback.onBookmarkNameChosen(title) dismissDialog() true } else { false } } return dialog } interface Callback { fun onBookmarkNameChosen(name: String) } companion object { operator fun <T> invoke(target: T) where T : Controller, T : Callback = AddBookmarkDialog().apply { targetController = target } } }
gpl-3.0
1e2f01c923a0be7302302c9c6373729f
31.482143
113
0.712479
4.581864
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/DoKitViewManagerInterface.kt
1
2020
package com.didichuxing.doraemonkit.kit.core import android.app.Activity /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-09-28-15:18 * 描 述:页面浮标管理类接口 * 修订历史: * ================================================ */ interface DoKitViewManagerInterface { /** * 在当前Activity中添加指定悬浮窗 * * @param doKitIntent */ fun attach(doKitIntent: DoKitIntent) /** * 移除每个activity指定的dokitView * * @param doKitView */ fun detach(doKitView: AbsDoKitView) /** * 移除每个activity指定的dokitView tag * * @param tag 一般为dokitView的className */ fun detach(tag: String) fun detach(doKitViewClass: Class<out AbsDoKitView>) /** * 移除所有activity的所有dokitView */ fun detachAll() /** * 获取页面上指定的dokitView * * @param activity * @param tag * @return */ fun <T : AbsDoKitView> getDoKitView(activity: Activity?, clazz: Class<T>): AbsDoKitView? /** * 获取页面上所有的dokitView * * @param activity * @return */ fun getDoKitViews(activity: Activity?): Map<String, AbsDoKitView>? /** * 当app进入后台时调用 */ fun notifyBackground() /** * 当app进入前台时调用 */ fun notifyForeground() /** * Activity销毁时调用 * * @param activity */ fun onActivityDestroyed(activity: Activity?) /** * 页面onPause时调用 * * @param activity */ fun onActivityPaused(activity: Activity?) /** * 页面onStop时调用 */ fun onActivityStopped(activity: Activity?) /** * Called on [Activity] resumed from activity lifecycle callbacks * * @param activity resumed activity */ fun dispatchOnActivityResumed(activity: Activity?) }
apache-2.0
c230d42486913267c8f29307d56058ed
17.842105
92
0.549721
4.105505
false
false
false
false
LachlanMcKee/gsonpath
compiler/standard/src/main/java/gsonpath/adapter/standard/extension/range/RangeFunctions.kt
1
1560
package gsonpath.adapter.standard.extension.range import com.squareup.javapoet.CodeBlock import gsonpath.adapter.standard.extension.addException import gsonpath.util.`if` /** * Creates the 'range' code validation code block. * * @param value the value being inspected * @param isFrom whether this is a 'from' or a 'to' range inspection * @param isInclusive whether the range validation is inclusive of the value * @param jsonPath the json path of the field being validated * @param variableName the name of the variable that is assigned back to the fieldName */ fun CodeBlock.Builder.handleRangeValue(value: String, isFrom: Boolean, isInclusive: Boolean, jsonPath: String, variableName: String): CodeBlock.Builder { val comparisonOperator: String = if (isFrom) { if (isInclusive) "<" else "<=" } else { if (isInclusive) ">" else ">=" } val expectedOperator: String = if (isFrom) { if (isInclusive) ">=" else ">" } else { if (isInclusive) "<=" else "<" } val label: String = if (isFrom) "from" else "to" return `if`("$variableName $comparisonOperator $value") { addException("Invalid '$label' range for JSON element '$jsonPath'. Expected: '$expectedOperator $value', " + """Found '" + $variableName + "'""") } }
mit
b89df28cbaec5b98f596cfede2b4df79
36.166667
116
0.56859
4.968153
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/statistics/main/StatisticsFragment.kt
1
35561
/* * Copyright 2016-2021 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.statistics.main import android.annotation.SuppressLint import com.apps.adrcotfas.goodtime.statistics.ChartMarker import android.widget.TextView import androidx.lifecycle.LiveData import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.charts.BarChart import com.google.android.material.card.MaterialCardView import com.github.mikephil.charting.charts.PieChart import android.widget.LinearLayout import android.widget.Spinner import com.apps.adrcotfas.goodtime.main.LabelsViewModel import com.apps.adrcotfas.goodtime.statistics.SessionViewModel import android.widget.ProgressBar import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import androidx.databinding.DataBindingUtil import com.apps.adrcotfas.goodtime.R import android.widget.ArrayAdapter import android.widget.AdapterView import com.github.mikephil.charting.interfaces.datasets.IBarDataSet import android.util.TypedValue import androidx.annotation.ColorInt import android.view.MotionEvent import com.github.mikephil.charting.formatter.PercentFormatter import android.text.TextPaint import android.text.format.DateFormat import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import com.apps.adrcotfas.goodtime.database.Label import com.apps.adrcotfas.goodtime.database.Session import com.apps.adrcotfas.goodtime.databinding.StatisticsFragmentMainBinding import com.apps.adrcotfas.goodtime.settings.PreferenceHelper import com.apps.adrcotfas.goodtime.util.* import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.animation.Easing import com.apps.adrcotfas.goodtime.util.StringUtils.formatLong import com.apps.adrcotfas.goodtime.util.StringUtils.formatMinutes import com.github.mikephil.charting.data.* import com.github.mikephil.charting.formatter.ValueFormatter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.time.* import java.time.format.DateTimeFormatter import java.time.temporal.ChronoField import java.time.temporal.TemporalAdjusters import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.math.ceil @AndroidEntryPoint class StatisticsFragment : Fragment() { private class Stats( var today: Long, var week: Long, var month: Long, var total: Long ) private var sessionsToObserve: LiveData<List<Session>>? = null private lateinit var chartHistory: LineChart private lateinit var chartProductiveHours: BarChart private var showPieChart = false private lateinit var pieChartSection: MaterialCardView private lateinit var pieChart: PieChart private var pieChartShowPercentages = false private lateinit var pieEmptyState: LinearLayout private lateinit var statsType: Spinner private lateinit var rangeType: Spinner private lateinit var productiveTimeType: Spinner private lateinit var pieChartType: Spinner private lateinit var headerOverview: TextView private lateinit var headerHistory: TextView private lateinit var headerProductiveTime: TextView private lateinit var xAxisFormatter: DayWeekMonthXAxisFormatter private val xValues: MutableList<LocalDate> = ArrayList() private val sessionViewModel: SessionViewModel by activityViewModels() private val labelsViewModel: LabelsViewModel by activityViewModels() @Inject lateinit var preferenceHelper: PreferenceHelper private lateinit var parentView: LinearLayout private lateinit var progressBar: ProgressBar private var displayDensity = 1f private lateinit var binding: StatisticsFragmentMainBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.statistics_fragment_main, container, false) val view = binding.root displayDensity = resources.displayMetrics.density setHasOptionsMenu(true) parentView = binding.parentLayout progressBar = binding.progressBar chartHistory = binding.history.chart chartProductiveHours = binding.productiveHours.barChart statsType = binding.overview.statsType rangeType = binding.history.rangeType productiveTimeType = binding.productiveHours.timeType pieChartType = binding.pieChartSection.pieChartType headerOverview = binding.overview.header headerHistory = binding.history.headerHistory headerProductiveTime = binding.productiveHours.headerProductiveTime pieChartSection = binding.pieChartSection.parent pieChart = binding.pieChartSection.pieChart pieEmptyState = binding.pieChartSection.emptyState setupPieChart() labelsViewModel.crtExtendedLabel.observe( viewLifecycleOwner, { refreshUi() }) setupSpinners() setupHistoryChart() setupProductiveTimeChart() // TODO: remove this later // for (int i = 0; i < 1000; ++i) { // Session session = new Session( // 0, // System.currentTimeMillis(), // 42, // null); // // mSessionViewModel.addSession(session); // } return view } private fun calculateOverviewStats(sessions: List<Session>, isDurationType: Boolean): Stats { val today = LocalDate.now() val thisWeekStart: LocalDate = today.with(TemporalAdjusters.previousOrSame(firstDayOfWeek())) val thisWeekEnd: LocalDate = today.with(TemporalAdjusters.nextOrSame(lastDayOfWeek())) val thisMonthStart: LocalDate = today.with(TemporalAdjusters.firstDayOfMonth()) val thisMonthEnd: LocalDate = today.with(TemporalAdjusters.lastDayOfMonth()) val stats = Stats(0, 0, 0, 0) for (s in sessions) { val crt = LocalDateTime.ofInstant(Instant.ofEpochMilli(s.timestamp), ZoneId.systemDefault()) .toLocalDate() val increment = if (isDurationType) s.duration.toLong() else 1L if (crt.isEqual(today)) { stats.today += increment } if ((crt >= thisWeekStart) && (crt <= thisWeekEnd)) { stats.week += increment } if ((crt >= thisMonthStart) && (crt <= thisMonthEnd)) { stats.month += increment } if (isDurationType) { stats.total += increment } } if (!isDurationType) { stats.total += sessions.size.toLong() } return stats } /** * @param value minutes or number of sessions, depending on isDurationType * @param isDurationType specifies if the value is in seconds or number of sessions */ private fun formatMinutesOrNumSessionsToOverviewTime( value: Long, isDurationType: Boolean ): String { return if (isDurationType) { formatMinutes(value) } else { formatLong(value) } } private fun getThisWeekNumber() = LocalDate.now().with(TemporalAdjusters.previousOrSame(firstDayOfWeek())).get( ChronoField.ALIGNED_WEEK_OF_YEAR ) private fun getCurrentMonthString(): String = LocalDate.now().format(DateTimeFormatter.ofPattern("MMMM")) @SuppressLint("SetTextI18n") private fun refreshStats(sessions: List<Session>) { val isDurationType = statsType.selectedItemPosition == SpinnerStatsType.DURATION.ordinal val stats = calculateOverviewStats(sessions, isDurationType) val overview = binding.overview overview.apply { todayValue.text = formatMinutesOrNumSessionsToOverviewTime(stats.today, isDurationType) weekValue.text = formatMinutesOrNumSessionsToOverviewTime(stats.week, isDurationType) monthValue.text = formatMinutesOrNumSessionsToOverviewTime(stats.month, isDurationType) totalValue.text = formatMinutesOrNumSessionsToOverviewTime(stats.total, isDurationType) weekDescription.text = "${resources.getString(R.string.statistics_week)} ${getThisWeekNumber()}" monthDescription.text = getCurrentMonthString() } } private fun setupSpinners() { val statsTypeAdapter = ArrayAdapter.createFromResource( requireContext(), R.array.spinner_stats_type, R.layout.spinner_item ) statsTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item) statsType.apply { adapter = statsTypeAdapter setSelection(1, false) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( adapterView: AdapterView<*>?, view: View, position: Int, id: Long ) { refreshUi() } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } val rangeTypeAdapter = ArrayAdapter.createFromResource( requireContext(), R.array.spinner_range_type, R.layout.spinner_item ) rangeTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item) rangeType.apply { adapter = rangeTypeAdapter setSelection(0, false) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( adapterView: AdapterView<*>?, view: View, position: Int, id: Long ) { xAxisFormatter.setRangeType(HistorySpinnerRangeType.values()[position]) refreshUi() } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } val timeTypeAdapter = ArrayAdapter.createFromResource( requireContext(), R.array.spinner_productive_time_type, R.layout.spinner_item ) timeTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item) productiveTimeType.apply { adapter = timeTypeAdapter setSelection(0, false) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( adapterView: AdapterView<*>?, view: View, i: Int, l: Long ) { refreshUi() } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } val pieTypeAdapter = ArrayAdapter.createFromResource( requireContext(), R.array.spinner_pie_time_type, R.layout.spinner_item ) pieTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item) pieChartType.apply { adapter = pieTypeAdapter setSelection(2, false) onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { refreshUi() } override fun onNothingSelected(parent: AdapterView<*>?) {} } } } private fun refreshProductiveTimeChart(sessions: List<Session>, color: Int) { val productiveTimeType = ProductiveTimeType.values()[productiveTimeType.selectedItemPosition] val visibleXCount = if (productiveTimeType == ProductiveTimeType.HOUR_OF_DAY) { ThemeHelper.pxToDp(requireContext(), chartHistory.width).toInt() / 36 } else { DayOfWeek.values().size } generateProductiveTimeChart(sessions, productiveTimeType, color) chartProductiveHours.apply { setVisibleXRangeMaximum(visibleXCount.toFloat()) setVisibleXRangeMinimum(visibleXCount.toFloat()) xAxis.labelCount = visibleXCount } chartProductiveHours.barData.setDrawValues(false) val b = chartProductiveHours.data.dataSets[0] var maxY = 0f var maxIdx = 0 for (i in 0 until b.entryCount) { val crtY = b.getEntryForIndex(i).y if (crtY > maxY) { maxY = crtY maxIdx = i } } chartProductiveHours.apply { moveViewToX(maxIdx.toFloat()) invalidate() notifyDataSetChanged() highlightValue(null) // clear any marker } } //TODO: make more efficient when setting spinners to not refresh all of it if not needed private fun refreshUi() { val label = labelsViewModel.crtExtendedLabel.value if (label != null) { sessionsToObserve?.removeObservers(this) val color = ThemeHelper.getColor(requireContext(), label.colorId) binding.overview.apply { todayValue.setTextColor(color) weekValue.setTextColor(color) monthValue.setTextColor(color) totalValue.setTextColor(color) } headerOverview.setTextColor(color) headerHistory.setTextColor(color) headerProductiveTime.setTextColor(color) when (label.title) { getString(R.string.label_all) -> { sessionsToObserve = sessionViewModel.allSessionsUnarchived showPieChart = true } "unlabeled" -> { sessionsToObserve = sessionViewModel.allSessionsUnlabeled showPieChart = false } else -> { sessionsToObserve = sessionViewModel.getSessions(label.title) showPieChart = false } } sessionsToObserve?.observe(viewLifecycleOwner, { sessions: List<Session> -> // Adjust the finished sessions according to the configured workday start sessions.forEach { it.timestamp -= preferenceHelper.getStartOfDayDeltaMillis() } refreshStats(sessions) refreshHistoryChart(sessions, color) refreshProductiveTimeChart(sessions, color) pieChartSection.visibility = if (showPieChart) View.VISIBLE else View.GONE if (showPieChart) { val labelsLd = labelsViewModel.labels labelsLd.observe(viewLifecycleOwner, { labels: List<Label> -> labelsLd.removeObservers(requireActivity()) refreshPieChart(sessions, labels) }) } lifecycleScope.launch { delay(100) progressBar.visibility = View.GONE parentView.visibility = View.VISIBLE } }) } } private fun setupPieChart() { val typedValue = TypedValue() val theme = requireContext().theme theme.resolveAttribute(R.attr.colorPrimaryDark, typedValue, true) @ColorInt val color = typedValue.data pieChart.apply { setHoleColor(color) legend.isEnabled = false setUsePercentValues(true) isDrawHoleEnabled = true holeRadius = 80f description.isEnabled = false setExtraOffsets(8f, 8f, 8f, 8f) highlightValues(null) setEntryLabelColor(resources.getColor(R.color.grey500)) setEntryLabelTextSize(11f) transparentCircleRadius = 0f dragDecelerationFrictionCoef = 0.95f isRotationEnabled = true isHighlightPerTapEnabled = false setNoDataText("") setTouchEnabled(true) onChartGestureListener = object : PieChartGestureListener() { override fun onChartSingleTapped(me: MotionEvent) { pieChartShowPercentages = !pieChartShowPercentages refreshUi() } } } } private fun refreshPieChart(sessions: List<Session>, labels: List<Label>) { // Nullable String key for the unlabeled sessions val totalTimePerLabel: MutableMap<String?, Int> = HashMap() val pieStatsType = PieStatsType.values()[pieChartType.selectedItemPosition] val today = LocalDate.now() val todayStart = today.atStartOfDay(ZoneId.systemDefault()).toLocalDate() val thisWeekStart: LocalDate = today.with(TemporalAdjusters.previousOrSame(firstDayOfWeek())) val thisMonthStart: LocalDate = today.with(TemporalAdjusters.firstDayOfMonth()) val filteredSessions: MutableList<Session> = ArrayList(sessions) when (pieStatsType) { PieStatsType.TODAY -> for (s in sessions) { if (s.timestamp.toLocalDate() < todayStart) { filteredSessions.remove(s) } } PieStatsType.THIS_WEEK -> for (s in sessions) { if (s.timestamp.toLocalDate() < thisWeekStart) { filteredSessions.remove(s) } } PieStatsType.THIS_MONTH -> for (s in sessions) { if (s.timestamp.toLocalDate() < thisMonthStart) { filteredSessions.remove(s) } } PieStatsType.TOTAL -> { } } if (filteredSessions.isEmpty()) { pieEmptyState.visibility = View.VISIBLE pieChart.visibility = View.GONE return } else { pieEmptyState.visibility = View.GONE pieChart.visibility = View.VISIBLE } for (s in filteredSessions) { if (!s.archived) { if (totalTimePerLabel.containsKey(s.label)) { totalTimePerLabel[s.label] = totalTimePerLabel[s.label]!! + s.duration } else { totalTimePerLabel[s.label] = s.duration } } } val entries = ArrayList<PieEntry>() for (label in totalTimePerLabel.keys) { entries.add(PieEntry(totalTimePerLabel[label]!!.toFloat(), label)) } entries.sortWith { o1: PieEntry, o2: PieEntry -> o2.value.compareTo(o1.value) } val colors = ArrayList<Int>() for (p in entries) { if (labels.isEmpty()) { p.label = getString(R.string.unlabeled) colors.add( ThemeHelper.getColor( requireContext(), ThemeHelper.COLOR_INDEX_ALL_LABELS ) ) break } for (l in labels) { if (p.label == null) { p.label = getString(R.string.unlabeled) colors.add( ThemeHelper.getColor( requireContext(), if (entries.size == 1) ThemeHelper.COLOR_INDEX_ALL_LABELS else ThemeHelper.COLOR_INDEX_UNLABELED ) ) break } else if (p.label == l.title) { colors.add(ThemeHelper.getColor(requireContext(), l.colorId)) break } } } val grey500 = resources.getColor(R.color.grey500) val dataSet = PieDataSet(entries, "") dataSet.colors = colors dataSet.yValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE dataSet.xValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE dataSet.valueLineColor = grey500 dataSet.valueLinePart1Length = 0.175f dataSet.isUsingSliceColorAsValueLineColor = true val data = PieData(dataSet) data.setValueTextSize(12f) data.setValueTextColor(grey500) if (pieChartShowPercentages) { pieChart.setUsePercentValues(true) data.setValueFormatter(PercentFormatter(pieChart)) } else { pieChart.setUsePercentValues(false) data.setValueFormatter(object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return formatMinutes(value.toLong()) } }) } pieChart.data = data pieChart.invalidate() } private fun refreshHistoryChart(sessions: List<Session>, color: Int) { val data = generateHistoryChartData(sessions, color) val isDurationType = statsType.selectedItemPosition == SpinnerStatsType.DURATION.ordinal chartHistory.apply { moveViewToX(data.xMax) this.data = data axisLeft.axisMinimum = 0f axisLeft.axisMaximum = if (isDurationType) 60f else 8f val visibleXCount = ThemeHelper.pxToDp(requireContext(), chartHistory.width) .toInt() / 36 setVisibleXRangeMaximum(visibleXCount.toFloat()) setVisibleXRangeMinimum(visibleXCount.toFloat()) xAxis.labelCount = visibleXCount axisLeft.setLabelCount(5, true) marker = ChartMarker(requireContext(), R.layout.view_chart_marker, if (isDurationType) ChartMarker.MarkerType.MINUTES else ChartMarker.MarkerType.INTEGER) highlightValue(null) // clear marker selection } val yMax = data.yMax if (sessions.isNotEmpty() && yMax >= (if (isDurationType) 60f else 8f)) { if (isDurationType) { chartHistory.axisLeft.axisMaximum = (ceil((yMax / 20).toDouble()) * 20).toFloat() } else { // round to the next multiple of 4 val axisMax = if (yMax % 4 != 0f) yMax + 4 - yMax % 4 else yMax chartHistory.axisLeft.axisMaximum = axisMax } } // this part is to align the history chart to the productive time chart by setting the same width val p = TextPaint() p.textSize = resources.getDimension(R.dimen.tinyTextSize) val widthOfOtherChart = ThemeHelper.pxToDp( requireContext(), p.measureText("100%") .toInt() ).toInt() chartHistory.apply { axisLeft.minWidth = widthOfOtherChart.toFloat() axisLeft.maxWidth = widthOfOtherChart.toFloat() notifyDataSetChanged() } } private fun setupHistoryChart() { chartHistory.setXAxisRenderer( CustomXAxisRenderer( chartHistory.viewPortHandler, chartHistory.xAxis, chartHistory.getTransformer(YAxis.AxisDependency.LEFT) ) ) val yAxis = chartHistory.axisLeft yAxis.valueFormatter = CustomYAxisFormatter() yAxis.textColor = resources.getColor(R.color.grey500) yAxis.textSize = resources.getDimension(R.dimen.tinyTextSize) / displayDensity yAxis.setDrawAxisLine(false) val xAxis = chartHistory.xAxis xAxis.textColor = resources.getColor(R.color.grey500) xAxis.position = XAxis.XAxisPosition.BOTTOM val rangeType = HistorySpinnerRangeType.values()[rangeType.selectedItemPosition] xAxisFormatter = DayWeekMonthXAxisFormatter(xValues, rangeType) xAxis.valueFormatter = xAxisFormatter xAxis.setAvoidFirstLastClipping(false) xAxis.textSize = resources.getDimension(R.dimen.tinyTextSize) / displayDensity xAxis.setDrawGridLines(false) xAxis.setDrawAxisLine(false) xAxis.yOffset = 10f chartHistory.apply { axisLeft.gridColor = resources.getColor(R.color.transparent_dark) axisLeft.gridLineWidth = 1f extraBottomOffset = 20f extraLeftOffset = 10f axisRight.isEnabled = false description.isEnabled = false setNoDataText("") setHardwareAccelerationEnabled(true) animateY(500, Easing.EaseOutCubic) legend.isEnabled = false isDoubleTapToZoomEnabled = false marker = ChartMarker(requireContext(), R.layout.view_chart_marker, ChartMarker.MarkerType.MINUTES) setScaleEnabled(false) invalidate() notifyDataSetChanged() } } private fun generateHistoryChartData(sessions: List<Session>, color: Int): LineData { val statsType = SpinnerStatsType.values()[statsType.selectedItemPosition] val rangeType = HistorySpinnerRangeType.values()[rangeType.selectedItemPosition] val dummyIntervalRange = ThemeHelper.pxToDp(requireContext(), chartHistory.width).toLong() / 24L val yValues: MutableList<Entry> = ArrayList() val tree = TreeMap<LocalDate, Int>() // generate dummy data val dummyEnd = LocalDate.now().plusDays(1) when (rangeType) { HistorySpinnerRangeType.DAYS -> { val dummyBegin = dummyEnd.minusDays(dummyIntervalRange) var i = dummyBegin while (i.isBefore(dummyEnd)) { tree[i] = 0 i = i.plusDays(1) } } HistorySpinnerRangeType.WEEKS -> { val dummyBegin = dummyEnd.minusWeeks(dummyIntervalRange).with( TemporalAdjusters.firstInMonth(firstDayOfWeek()) ) var i: LocalDate = dummyBegin while (i.isBefore(dummyEnd)) { tree[i] = 0 i = i.plusWeeks(1) } } HistorySpinnerRangeType.MONTHS -> { val dummyBegin = dummyEnd.minusMonths(dummyIntervalRange).withDayOfMonth(1) var i: LocalDate = dummyBegin while (i.isBefore(dummyEnd)) { tree[i] = 0 i = i.plusMonths(1).withDayOfMonth(1) } } } val isDurationType = statsType == SpinnerStatsType.DURATION // this is to sum up entries from the same day for visualization for (i in sessions.indices) { val millis = sessions[i].timestamp val localDate = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate() val localTime = when (rangeType) { HistorySpinnerRangeType.DAYS -> localDate HistorySpinnerRangeType.WEEKS -> localDate.with( TemporalAdjusters.previousOrSame(firstDayOfWeek()) ) HistorySpinnerRangeType.MONTHS -> localDate.with(TemporalAdjusters.firstDayOfMonth()) } if (!tree.containsKey(localTime)) { tree[localTime] = if (isDurationType) sessions[i].duration else 1 } else { tree[localTime] = (tree[localTime]!! + if (isDurationType) sessions[i].duration else 1) } } if (tree.size > 0) { xValues.clear() var i = 0 var previousTime = tree.firstKey() for (crt in tree.keys) { // visualize intermediate days/weeks/months in case of days without completed sessions val beforeWhat: LocalDate = when (rangeType) { HistorySpinnerRangeType.DAYS -> crt.minusDays(1) HistorySpinnerRangeType.WEEKS -> crt.minusWeeks(1) HistorySpinnerRangeType.MONTHS -> crt.minusMonths(1) } while (previousTime.isBefore(beforeWhat)) { yValues.add(Entry(i.toFloat(), 0f)) previousTime = when (rangeType) { HistorySpinnerRangeType.DAYS -> previousTime.plusDays(1) HistorySpinnerRangeType.WEEKS -> previousTime.plusWeeks(1) HistorySpinnerRangeType.MONTHS -> previousTime.plusMonths(1) } xValues.add(previousTime) ++i } yValues.add(Entry(i.toFloat(), tree[crt]!!.toFloat())) xValues.add(crt) ++i previousTime = crt } } return LineData(generateLineDataSet(yValues, color)) } private fun generateLineDataSet(entries: List<Entry>, color: Int): LineDataSet { val set = LineDataSet(entries, null) set.apply { this.color = color setCircleColor(color) setDrawFilled(true) fillColor = color lineWidth = 3f circleRadius = 3f setDrawCircleHole(false) disableDashedLine() setDrawValues(false) highlightLineWidth = 0.0000001f // for some reason 0f does not do the trick } return set } private fun setupProductiveTimeChart() { val yAxis = chartProductiveHours.axisLeft yAxis.valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return StringUtils.toPercentage(value) } } yAxis.textColor = resources.getColor(R.color.grey500) yAxis.granularity = 0.25f yAxis.textSize = resources.getDimension(R.dimen.tinyTextSize) / displayDensity yAxis.axisMaximum = 1f yAxis.setDrawGridLines(true) yAxis.setDrawAxisLine(false) val xAxis = chartProductiveHours.xAxis xAxis.textColor = resources.getColor(R.color.grey500) xAxis.position = XAxis.XAxisPosition.BOTTOM xAxis.setAvoidFirstLastClipping(false) xAxis.textSize = resources.getDimension(R.dimen.tinyTextSize) / displayDensity xAxis.setDrawGridLines(false) xAxis.setDrawAxisLine(false) chartProductiveHours.setXAxisRenderer( CustomXAxisRenderer( chartProductiveHours.viewPortHandler, xAxis, chartProductiveHours.getTransformer(YAxis.AxisDependency.LEFT) ) ) chartProductiveHours.apply { axisLeft.gridColor = resources.getColor(R.color.transparent_dark) axisLeft.gridLineWidth = 1f extraBottomOffset = 20f axisRight.isEnabled = false description.isEnabled = false setNoDataText("") setHardwareAccelerationEnabled(true) animateY(500, Easing.EaseOutCubic) legend.isEnabled = false isDoubleTapToZoomEnabled = false marker = ChartMarker( requireContext(), R.layout.view_chart_marker, ChartMarker.MarkerType.PERCENTAGE ) setScaleEnabled(false) //TODO: do we need these here? invalidate() notifyDataSetChanged() } } private fun generateProductiveTimeChart( sessions: List<Session>, type: ProductiveTimeType, color: Int ) { val values = ArrayList<BarEntry>() val productiveTimeType = SpinnerStatsType.values()[statsType.selectedItemPosition] val sessionsPerProductiveTimeType = MutableList(if (type == ProductiveTimeType.HOUR_OF_DAY) 24 else DayOfWeek.values().size) { 0L } for (i in sessionsPerProductiveTimeType.indices) { values.add(BarEntry(i.toFloat(), 0f)) } if (productiveTimeType == SpinnerStatsType.DURATION) { var totalTime = 0L for (s in sessions) { // When showing hours, re-adjust the displayed values to the real values if (type == ProductiveTimeType.HOUR_OF_DAY) { s.timestamp += preferenceHelper.getStartOfDayDeltaMillis() } totalTime += s.duration val crtIndex = if (type == ProductiveTimeType.HOUR_OF_DAY) s.timestamp.toLocalTime().hour else s.timestamp.toLocalDateTime().dayOfWeek.value - 1 sessionsPerProductiveTimeType[crtIndex] = sessionsPerProductiveTimeType[crtIndex] + s.duration } for (i in sessionsPerProductiveTimeType.indices) { values[i] = BarEntry(i.toFloat(), if (totalTime == 0L) 0f else sessionsPerProductiveTimeType[i].toFloat() / totalTime) } } else if (productiveTimeType == SpinnerStatsType.NR_OF_SESSIONS) { for (s in sessions) { // When showing hours, re-adjust the displayed values to the real values if (type == ProductiveTimeType.HOUR_OF_DAY) { s.timestamp -= preferenceHelper.getStartOfDayDeltaMillis() } val crtIndex = if (type == ProductiveTimeType.HOUR_OF_DAY) s.timestamp.toLocalTime().hour else s.timestamp.toLocalDateTime().dayOfWeek.value - 1 ++sessionsPerProductiveTimeType[crtIndex] } for (i in sessionsPerProductiveTimeType.indices) { values[i] = BarEntry( i.toFloat(), sessionsPerProductiveTimeType[i].toFloat() / sessions.size ) } } val set1 = BarDataSet(values, "") set1.color = color set1.highLightAlpha = 0 set1.setDrawIcons(false) val dataSets = ArrayList<IBarDataSet>() dataSets.add(set1) val data = BarData(dataSets) data.setValueTextSize(10f) data.barWidth = 0.4f chartProductiveHours.apply { this.data = data xAxis.valueFormatter = ProductiveTimeXAxisFormatter(type, DateFormat.is24HourFormat(requireContext())) invalidate() notifyDataSetChanged() } } companion object { private val TAG = StatisticsFragment::class.java.simpleName } }
apache-2.0
9fc55b02fe1c9b41a861b0ce40954563
40.112139
166
0.604482
5.481042
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/fields/ListDetailField.kt
1
8957
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.parameters.fields import javafx.scene.Node import javafx.scene.control.ListView import javafx.scene.control.SelectionMode import javafx.scene.layout.BorderPane import javafx.scene.layout.FlowPane import javafx.scene.layout.StackPane import javafx.scene.layout.VBox import uk.co.nickthecoder.paratask.gui.ApplicationActions import uk.co.nickthecoder.paratask.parameters.* class ListDetailField<T, P : ValueParameter<T>>( val multipleParameter: MultipleParameter<T, P>, val info: MultipleParameter.ListDetailsInfo<P>) : ParameterField(multipleParameter, isBoxed = info.isBoxed), FieldParent { val borderPane = BorderPane() val list = ListView<ListData>() val detailsContainer = StackPane() val listAndButtons = VBox() val buttons = FlowPane() val addButton = ApplicationActions.ITEM_ADD.createButton { onAdd() } val removeButton = ApplicationActions.ITEM_REMOVE.createButton { onRemove() } val upButton = ApplicationActions.ITEM_UP.createButton { onMoveUp() } val downButton = ApplicationActions.ITEM_DOWN.createButton { onMoveDown() } override fun createControl(): Node { with(buttons) { styleClass.addAll("small-buttons") children.addAll(addButton, removeButton) if (info.allowReordering) { children.addAll(upButton, downButton) } } with(detailsContainer) { styleClass.add("multiple-details") } buildList() with(listAndButtons) { prefWidth = info.width.toDouble() children.addAll(list, buttons) } with(list) { selectionModel.selectionMode = SelectionMode.MULTIPLE prefHeight = info.height.toDouble() selectionModel.selectedItemProperty().addListener { _, _, selectedData -> selectionChanged(selectedData) } } selectionChanged(list.selectionModel.selectedItem) with(borderPane) { left = listAndButtons center = detailsContainer } return borderPane } fun buildList() { list.items.clear() multipleParameter.innerParameters.forEach { innerP -> addItemToList(innerP) } list.items.firstOrNull()?.let { list.selectionModel.select(it) } } fun addItemToList(innerP: ValueParameter<T>): ListData { // TODO Consider caching fields, so that rebuilding the list doesn't create new fields. val field = innerP.createField() field.fieldParent = this val data = ListData(field) list.items.add(data) return data } fun selectionChanged(selectedItem: ListData?) { detailsContainer.children.clear() if (selectedItem != null) { detailsContainer.children.add(selectedItem.field.controlContainer) } removeButton.isDisable = selectedItem == null } override fun updateError(field: ParameterField) { // I don't THINK I need to do anything here. } override fun updateField(field: ParameterField) { // I don't THINK I need to do anything here. } override fun iterator(): Iterator<ParameterField> { return list.items.map { it.field }.iterator() } /** * Prevent us from rebuilding the list when a structural event is fired because of this. */ var ignoreStructuralChanges: Boolean = false fun onAdd() { ignoreStructuralChanges = true try { val innerP = multipleParameter.newValue() list.selectionModel.select(addItemToList(innerP)) } finally { ignoreStructuralChanges = false } } fun onRemove() { ignoreStructuralChanges = true try { var index = list.selectionModel.selectedIndex while (index >= 0) { list.selectionModel.clearSelection(index) multipleParameter.removeAt(index) list.items.removeAt(index) index = list.selectionModel.selectedIndex } } finally { ignoreStructuralChanges = false } } fun onMoveUp() { // We use this to prevent one item "overtaking" another when moving multiple items up. var previousPosition = -1 val newSelection = mutableListOf<Int>() // NOTE. we need to create a NEW list, because otherwise we get exceptions when removing items. val indicies = list.selectionModel.selectedIndices.toMutableList().sorted() ignoreStructuralChanges = true try { indicies.forEach { position -> if (position > previousPosition + 1) { val item = list.items[position] list.items.removeAt(position) list.items.add(position - 1, item) multipleParameter.moveInnerParameter(position, position - 1) previousPosition = position - 1 newSelection.add(position - 1) } else { previousPosition = position newSelection.add(position) } list.selectionModel.clearSelection() newSelection.forEach { list.selectionModel.select(it) } } } finally { ignoreStructuralChanges = false } } fun onMoveDown() { // We use this to prevent one item "overtaking" another when moving multiple items up. var previousPosition = list.items.size val newSelection = mutableListOf<Int>() // NOTE. we need to create a NEW list, because otherwise we get exceptions when removing items. val indicies = list.selectionModel.selectedIndices.toMutableList().sortedDescending() ignoreStructuralChanges = true try { indicies.forEach { position -> if (position < previousPosition - 1) { val item = list.items[position] list.items.removeAt(position) list.items.add(position + 1, item) multipleParameter.moveInnerParameter(position, position + 1) previousPosition = position + 1 newSelection.add(position + 1) } else { previousPosition = position newSelection.add(position) } list.selectionModel.clearSelection() newSelection.forEach { list.selectionModel.select(it) } } } finally { ignoreStructuralChanges = false } } override fun parameterChanged(event: ParameterEvent) { super.parameterChanged(event) if (!ignoreStructuralChanges && event.type == ParameterEventType.STRUCTURAL) { buildList() } } inner class ListData(val field: ParameterField) : ParameterListener { var label = label() init { field.parameter.parameterListeners.add(this) } fun label(): String { @Suppress("UNCHECKED_CAST") return info.labelFactory(field.parameter as P) } /** * Listen for changes, and if the text in the list needs updating, then * remove the item from the list and add it back again. * Make sure the item is selected if it was selected before this operation. */ override fun parameterChanged(event: ParameterEvent) { if (event.type == ParameterEventType.INNER || event.type == ParameterEventType.VALUE) { val newLabel = label() if (newLabel != label) { label = newLabel val index = list.items.indexOf(this) val wasSelected = list.selectionModel.isSelected(index) list.items.removeAt(index) list.items.add(index, this) if (wasSelected) { list.selectionModel.select(index) } } } } override fun toString() = label } }
gpl-3.0
06bfa224f5528ebf25cd91da425c894d
31.570909
103
0.606118
5.210588
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/BuildLinksGraphQLIT.kt
1
4279
package net.nemerosa.ontrack.graphql import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull /** * Management of build links using GraphQL. */ class BuildLinksGraphQLIT : AbstractQLKTITJUnit4Support() { @Test fun `Linking a build to another build using names`() { val build1 = doCreateBuild() val build2 = doCreateBuild() asAdmin { run( """ mutation { linkBuild(input: { fromProject: "${build1.project.name}", fromBuild: "${build1.name}", toProject: "${build2.project.name}", toBuild: "${build2.name}", }) { build { id } errors { message exception } } } """ ) { data -> checkGraphQLUserErrors(data, "linkBuild") { payload -> assertEquals(build1.id(), payload.path("build").path("id").asInt()) assertNotNull( structureService.getBuildsUsedBy(build1).pageItems.find { it.id == build2.id }, "Link has been created" ) } } } } @Test fun `Bulk addition of build links`() { val build0 = doCreateBuild() val builds = (0..2).map { doCreateBuild() } val links = builds.map { mapOf( "project" to it.project.name, "build" to it.name, ) } asAdmin { run( """ mutation BulkLinks(${'$'}links: [LinksBuildInputItem!]!) { linksBuild(input: { fromProject: "${build0.project.name}", fromBuild: "${build0.name}", links: ${'$'}links, }) { build { id } errors { message exception } } } """, mapOf("links" to links) ) { data -> checkGraphQLUserErrors(data, "linksBuild") { payload -> assertEquals(build0.id(), payload.path("build").path("id").asInt()) (0..2).forEach { no -> assertNotNull( structureService.getBuildsUsedBy(build0).pageItems.find { it.id == builds[no].id }, "Link has been created" ) } } } } } @Test fun `Linking a build to another build using IDs`() { val build1 = doCreateBuild() val build2 = doCreateBuild() asAdmin { run( """ mutation { linkBuildById(input: { fromBuild: ${build1.id}, toBuild: ${build2.id}, }) { build { id } errors { message exception } } } """ ) { data -> checkGraphQLUserErrors(data, "linkBuildById") { payload -> assertEquals(build1.id(), payload.path("build").path("id").asInt()) assertNotNull( structureService.getBuildsUsedBy(build1).pageItems.find { it.id == build2.id }, "Link has been created" ) } } } } }
mit
39e7be96669bb9ddf5a52f23570b8e1f
32.968254
111
0.349614
6.339259
false
false
false
false
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/DataFlowIR.kt
1
29779
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.descriptors.isAbstract import org.jetbrains.kotlin.backend.konan.descriptors.isBuiltInOperator import org.jetbrains.kotlin.backend.konan.ir.allParameters import org.jetbrains.kotlin.backend.konan.ir.isOverridableOrOverrides import org.jetbrains.kotlin.backend.konan.llvm.functionName import org.jetbrains.kotlin.backend.konan.llvm.isExported import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.backend.konan.llvm.symbolName import org.jetbrains.kotlin.backend.konan.lower.DECLARATION_ORIGIN_BRIDGE_METHOD import org.jetbrains.kotlin.backend.konan.lower.bridgeTarget import org.jetbrains.kotlin.backend.konan.optimizations.DataFlowIR.Function.Companion.appendCastTo import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.types.isNothing import org.jetbrains.kotlin.ir.types.isUnit import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name internal object DataFlowIR { abstract class Type(val isFinal: Boolean, val isAbstract: Boolean, val primitiveBinaryType: PrimitiveBinaryType?, val name: String?) { // Special marker type forbidding devirtualization on its instances. object Virtual : Declared(0, false, true, null, null, -1, null, "\$VIRTUAL") class External(val hash: Long, isFinal: Boolean, isAbstract: Boolean, primitiveBinaryType: PrimitiveBinaryType?, name: String? = null) : Type(isFinal, isAbstract, primitiveBinaryType, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is External) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "ExternalType(hash='$hash', name='$name')" } } abstract class Declared(val index: Int, isFinal: Boolean, isAbstract: Boolean, primitiveBinaryType: PrimitiveBinaryType?, val module: Module?, val symbolTableIndex: Int, val irClass: IrClass?, name: String?) : Type(isFinal, isAbstract, primitiveBinaryType, name) { val superTypes = mutableListOf<Type>() val vtable = mutableListOf<FunctionSymbol>() val itable = mutableMapOf<Long, FunctionSymbol>() } class Public(val hash: Long, index: Int, isFinal: Boolean, isAbstract: Boolean, primitiveBinaryType: PrimitiveBinaryType?, module: Module, symbolTableIndex: Int, irClass: IrClass?, name: String? = null) : Declared(index, isFinal, isAbstract, primitiveBinaryType, module, symbolTableIndex, irClass, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Public) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "PublicType(hash='$hash', symbolTableIndex='$symbolTableIndex', name='$name')" } } class Private(index: Int, isFinal: Boolean, isAbstract: Boolean, primitiveBinaryType: PrimitiveBinaryType?, module: Module, symbolTableIndex: Int, irClass: IrClass?, name: String? = null) : Declared(index, isFinal, isAbstract, primitiveBinaryType, module, symbolTableIndex, irClass, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Private) return false return index == other.index } override fun hashCode(): Int { return index } override fun toString(): String { return "PrivateType(index=$index, symbolTableIndex='$symbolTableIndex', name='$name')" } } } class Module(val descriptor: ModuleDescriptor) { var numberOfFunctions = 0 var numberOfClasses = 0 } object FunctionAttributes { val IS_GLOBAL_INITIALIZER = 1 val RETURNS_UNIT = 2 val RETURNS_NOTHING = 4 val EXPLICITLY_EXPORTED = 8 } class FunctionParameter(val type: Type, val boxFunction: FunctionSymbol?, val unboxFunction: FunctionSymbol?) abstract class FunctionSymbol(val attributes: Int, val irFunction: IrFunction?, val name: String?) { lateinit var parameters: Array<FunctionParameter> lateinit var returnParameter: FunctionParameter val isGlobalInitializer = attributes.and(FunctionAttributes.IS_GLOBAL_INITIALIZER) != 0 val returnsUnit = attributes.and(FunctionAttributes.RETURNS_UNIT) != 0 val returnsNothing = attributes.and(FunctionAttributes.RETURNS_NOTHING) != 0 val explicitlyExported = attributes.and(FunctionAttributes.EXPLICITLY_EXPORTED) != 0 var escapes: Int? = null var pointsTo: IntArray? = null class External(val hash: Long, attributes: Int, irFunction: IrFunction?, name: String? = null, val isExported: Boolean) : FunctionSymbol(attributes, irFunction, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is External) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "ExternalFunction(hash='$hash', name='$name', escapes='$escapes', pointsTo='${pointsTo?.contentToString()}')" } } abstract class Declared(val module: Module, val symbolTableIndex: Int, attributes: Int, irFunction: IrFunction?, var bridgeTarget: FunctionSymbol?, name: String?) : FunctionSymbol(attributes, irFunction, name) { } class Public(val hash: Long, module: Module, symbolTableIndex: Int, attributes: Int, irFunction: IrFunction?, bridgeTarget: FunctionSymbol?, name: String? = null) : Declared(module, symbolTableIndex, attributes, irFunction, bridgeTarget, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Public) return false return hash == other.hash } override fun hashCode(): Int { return hash.hashCode() } override fun toString(): String { return "PublicFunction(hash='$hash', name='$name', symbolTableIndex='$symbolTableIndex', escapes='$escapes', pointsTo='${pointsTo?.contentToString()})" } } class Private(val index: Int, module: Module, symbolTableIndex: Int, attributes: Int, irFunction: IrFunction?, bridgeTarget: FunctionSymbol?, name: String? = null) : Declared(module, symbolTableIndex, attributes, irFunction, bridgeTarget, name) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Private) return false return index == other.index } override fun hashCode(): Int { return index } override fun toString(): String { return "PrivateFunction(index=$index, symbolTableIndex='$symbolTableIndex', name='$name', escapes='$escapes', pointsTo='${pointsTo?.contentToString()})" } } } data class Field(val receiverType: Type?, val type: Type, val hash: Long, val name: String? = null) class Edge(val castToType: Type?) { lateinit var node: Node constructor(node: Node, castToType: Type?) : this(castToType) { this.node = node } } enum class VariableKind { Ordinary, Temporary, CatchParameter } sealed class Node { class Parameter(val index: Int) : Node() open class Const(val type: Type) : Node() class SimpleConst<T : Any>(type: Type, val value: T) : Const(type) object Null : Node() open class Call(val callee: FunctionSymbol, val arguments: List<Edge>, val returnType: Type, open val irCallSite: IrFunctionAccessExpression?) : Node() class StaticCall(callee: FunctionSymbol, arguments: List<Edge>, val receiverType: Type?, returnType: Type, irCallSite: IrFunctionAccessExpression?) : Call(callee, arguments, returnType, irCallSite) // TODO: It can be replaced with a pair(AllocInstance, constructor Call), remove. class NewObject(constructor: FunctionSymbol, arguments: List<Edge>, val constructedType: Type, override val irCallSite: IrConstructorCall?) : Call(constructor, arguments, constructedType, irCallSite) open class VirtualCall(callee: FunctionSymbol, arguments: List<Edge>, val receiverType: Type, returnType: Type, override val irCallSite: IrCall?) : Call(callee, arguments, returnType, irCallSite) class VtableCall(callee: FunctionSymbol, receiverType: Type, val calleeVtableIndex: Int, arguments: List<Edge>, returnType: Type, irCallSite: IrCall?) : VirtualCall(callee, arguments, receiverType, returnType, irCallSite) class ItableCall(callee: FunctionSymbol, receiverType: Type, val calleeHash: Long, arguments: List<Edge>, returnType: Type, irCallSite: IrCall?) : VirtualCall(callee, arguments, receiverType, returnType, irCallSite) class Singleton(val type: Type, val constructor: FunctionSymbol?) : Node() class AllocInstance(val type: Type, val irCallSite: IrCall?) : Node() class FunctionReference(val symbol: FunctionSymbol, val type: Type, val returnType: Type) : Node() class FieldRead(val receiver: Edge?, val field: Field, val type: Type, val ir: IrGetField?) : Node() class FieldWrite(val receiver: Edge?, val field: Field, val value: Edge, val type: Type) : Node() class ArrayRead(val callee: FunctionSymbol, val array: Edge, val index: Edge, val type: Type, val irCallSite: IrCall?) : Node() class ArrayWrite(val callee: FunctionSymbol, val array: Edge, val index: Edge, val value: Edge, val type: Type) : Node() class Variable(values: List<Edge>, val type: Type, val kind: VariableKind) : Node() { val values = mutableListOf<Edge>().also { it += values } } class Scope(val depth: Int, nodes: List<Node>) : Node() { val nodes = mutableSetOf<Node>().also { it += nodes } } } // Note: scopes form a tree. class FunctionBody(val rootScope: Node.Scope, val allScopes: List<Node.Scope>, val returns: Node.Variable, val throws: Node.Variable) { inline fun forEachNonScopeNode(block: (Node) -> Unit) { for (scope in allScopes) for (node in scope.nodes) if (node !is Node.Scope) block(node) } } class Function(val symbol: FunctionSymbol, val body: FunctionBody) { fun debugOutput() = println(debugString()) fun debugString() = buildString { appendLine("FUNCTION $symbol") appendLine("Params: ${symbol.parameters.contentToString()}") val nodes = listOf(body.rootScope) + body.allScopes.flatMap { it.nodes } val ids = nodes.withIndex().associateBy({ it.value }, { it.index }) nodes.forEach { appendLine(" NODE #${ids[it]!!}") appendLine(nodeToString(it, ids)) } appendLine(" RETURNS") append(nodeToString(body.returns, ids)) } companion object { fun printNode(node: Node, ids: Map<Node, Int>) = print(nodeToString(node, ids)) fun nodeToString(node: Node, ids: Map<Node, Int>) = when (node) { is Node.Const -> " CONST ${node.type}" Node.Null -> " NULL" is Node.Parameter -> " PARAM ${node.index}" is Node.Singleton -> " SINGLETON ${node.type}" is Node.AllocInstance -> " ALLOC INSTANCE ${node.type}" is Node.FunctionReference -> " FUNCTION REFERENCE ${node.symbol}" is Node.StaticCall -> buildString { append(" STATIC CALL ${node.callee}. Return type = ${node.returnType}") appendList(node.arguments) { append(" ARG #${ids[it.node]!!}") appendCastTo(it.castToType) } } is Node.VtableCall -> buildString { appendLine(" VIRTUAL CALL ${node.callee}. Return type = ${node.returnType}") appendLine(" RECEIVER: ${node.receiverType}") append(" VTABLE INDEX: ${node.calleeVtableIndex}") appendList(node.arguments) { append(" ARG #${ids[it.node]!!}") appendCastTo(it.castToType) } } is Node.ItableCall -> buildString { appendLine(" INTERFACE CALL ${node.callee}. Return type = ${node.returnType}") appendLine(" RECEIVER: ${node.receiverType}") append(" METHOD HASH: ${node.calleeHash}") appendList(node.arguments) { append(" ARG #${ids[it.node]!!}") appendCastTo(it.castToType) } } is Node.NewObject -> buildString { appendLine(" NEW OBJECT ${node.callee}") append(" CONSTRUCTED TYPE ${node.constructedType}") appendList(node.arguments) { append(" ARG #${ids[it.node]!!}") appendCastTo(it.castToType) } } is Node.FieldRead -> buildString { appendLine(" FIELD READ ${node.field}") append(" RECEIVER #${node.receiver?.node?.let { ids[it]!! } ?: "null"}") appendCastTo(node.receiver?.castToType) } is Node.FieldWrite -> buildString { appendLine(" FIELD WRITE ${node.field}") append(" RECEIVER #${node.receiver?.node?.let { ids[it]!! } ?: "null"}") appendCastTo(node.receiver?.castToType) appendLine() append(" VALUE #${ids[node.value.node]!!}") appendCastTo(node.value.castToType) } is Node.ArrayRead -> buildString { appendLine(" ARRAY READ") append(" ARRAY #${ids[node.array.node]}") appendCastTo(node.array.castToType) appendLine() append(" INDEX #${ids[node.index.node]!!}") appendCastTo(node.index.castToType) } is Node.ArrayWrite -> buildString { appendLine(" ARRAY WRITE") append(" ARRAY #${ids[node.array.node]}") appendCastTo(node.array.castToType) appendLine() append(" INDEX #${ids[node.index.node]!!}") appendCastTo(node.index.castToType) appendLine() append(" VALUE #${ids[node.value.node]!!}") appendCastTo(node.value.castToType) } is Node.Variable -> buildString { append(" ${node.kind}") appendList(node.values) { append(" VAL #${ids[it.node]!!}") appendCastTo(it.castToType) } } is Node.Scope -> buildString { append(" SCOPE ${node.depth}") appendList(node.nodes.toList()) { append(" SUBNODE #${ids[it]!!}") } } else -> " UNKNOWN: ${node::class.java}" } private fun <T> StringBuilder.appendList(list: List<T>, itemPrinter: StringBuilder.(T) -> Unit) { if (list.isEmpty()) return for (i in list.indices) { appendLine() itemPrinter(list[i]) } } private fun StringBuilder.appendCastTo(type: Type?) { if (type != null) append(" CASTED TO ${type}") } } } class SymbolTable(val context: Context, val irModule: IrModuleFragment, val module: Module) { private val TAKE_NAMES = true // Take fqNames for all functions and types (for debug purposes). private inline fun takeName(block: () -> String) = if (TAKE_NAMES) block() else null val classMap = mutableMapOf<IrClass, Type>() val primitiveMap = mutableMapOf<PrimitiveBinaryType, Type>() val functionMap = mutableMapOf<IrDeclaration, FunctionSymbol>() private val NAME_ESCAPES = Name.identifier("Escapes") private val NAME_POINTS_TO = Name.identifier("PointsTo") private val FQ_NAME_KONAN = FqName.fromSegments(listOf("kotlin", "native", "internal")) private val FQ_NAME_ESCAPES = FQ_NAME_KONAN.child(NAME_ESCAPES) private val FQ_NAME_POINTS_TO = FQ_NAME_KONAN.child(NAME_POINTS_TO) private val konanPackage = context.builtIns.builtInsModule.getPackage(FQ_NAME_KONAN).memberScope private val getContinuationSymbol = context.ir.symbols.getContinuation private val continuationType = getContinuationSymbol.owner.returnType var privateTypeIndex = 1 // 0 for [Virtual] var privateFunIndex = 0 init { irModule.accept(object : IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitFunction(declaration: IrFunction) { declaration.body?.let { mapFunction(declaration) } } override fun visitField(declaration: IrField) { if (declaration.parent is IrFile) declaration.initializer?.let { mapFunction(declaration) } } override fun visitClass(declaration: IrClass) { declaration.acceptChildrenVoid(this) mapClassReferenceType(declaration) } }, data = null) } private fun IrClass.isFinal() = modality == Modality.FINAL fun mapClassReferenceType(irClass: IrClass): Type { // Do not try to devirtualize ObjC classes. if (irClass.module.name == Name.special("<forward declarations>") || irClass.isObjCClass()) return Type.Virtual val isFinal = irClass.isFinal() val isAbstract = irClass.isAbstract() val name = irClass.fqNameForIrSerialization.asString() classMap[irClass]?.let { return it } val placeToClassTable = true val symbolTableIndex = if (placeToClassTable) module.numberOfClasses++ else -1 val type = if (irClass.isExported()) Type.Public(name.localHash.value, privateTypeIndex++, isFinal, isAbstract, null, module, symbolTableIndex, irClass, takeName { name }) else Type.Private(privateTypeIndex++, isFinal, isAbstract, null, module, symbolTableIndex, irClass, takeName { name }) classMap[irClass] = type type.superTypes += irClass.superTypes.map { mapClassReferenceType(it.getClass()!!) } if (!isAbstract) { val layoutBuilder = context.getLayoutBuilder(irClass) type.vtable += layoutBuilder.vtableEntries.map { mapFunction(it.getImplementation(context)!!) } layoutBuilder.methodTableEntries.forEach { type.itable[it.overriddenFunction.functionName.localHash.value] = mapFunction(it.getImplementation(context)!!) } } else if (irClass.isInterface) { // Warmup interface table so it is computed before DCE. context.getLayoutBuilder(irClass).interfaceTableEntries } return type } private fun choosePrimary(erasure: List<IrClass>): IrClass { if (erasure.size == 1) return erasure[0] // A parameter with constraints - choose class if exists. return erasure.singleOrNull { !it.isInterface } ?: context.ir.symbols.any.owner } private fun mapPrimitiveBinaryType(primitiveBinaryType: PrimitiveBinaryType): Type = primitiveMap.getOrPut(primitiveBinaryType) { Type.Public( primitiveBinaryType.ordinal.toLong(), privateTypeIndex++, true, false, primitiveBinaryType, module, -1, null, takeName { primitiveBinaryType.name } ) } fun mapType(type: IrType): Type { val binaryType = type.computeBinaryType() return when (binaryType) { is BinaryType.Primitive -> mapPrimitiveBinaryType(binaryType.type) is BinaryType.Reference -> mapClassReferenceType(choosePrimary(binaryType.types.toList())) } } private fun mapTypeToFunctionParameter(type: IrType) = type.getInlinedClassNative().let { inlinedClass -> FunctionParameter(mapType(type), inlinedClass?.let { mapFunction(context.getBoxFunction(it)) }, inlinedClass?.let { mapFunction(context.getUnboxFunction(it)) }) } fun mapFunction(declaration: IrDeclaration): FunctionSymbol = when (declaration) { is IrFunction -> mapFunction(declaration) is IrField -> mapPropertyInitializer(declaration) else -> error("Unknown declaration: $declaration") } private fun mapFunction(function: IrFunction): FunctionSymbol = function.target.let { functionMap[it]?.let { return it } val parent = it.parent val containingDeclarationPart = parent.fqNameForIrSerialization.let { if (it.isRoot) "" else "$it." } val name = "kfun:$containingDeclarationPart${it.functionName}" val returnsUnit = it is IrConstructor || (!it.isSuspend && it.returnType.isUnit()) val returnsNothing = !it.isSuspend && it.returnType.isNothing() var attributes = 0 if (returnsUnit) attributes = attributes or FunctionAttributes.RETURNS_UNIT if (returnsNothing) attributes = attributes or FunctionAttributes.RETURNS_NOTHING if (it.hasAnnotation(RuntimeNames.exportForCppRuntime) || it.getExternalObjCMethodInfo() != null // TODO-DCE-OBJC-INIT || it.hasAnnotation(RuntimeNames.objCMethodImp)) { attributes = attributes or FunctionAttributes.EXPLICITLY_EXPORTED } val symbol = when { it.isExternal || it.isBuiltInOperator -> { val escapesAnnotation = it.annotations.findAnnotation(FQ_NAME_ESCAPES) val pointsToAnnotation = it.annotations.findAnnotation(FQ_NAME_POINTS_TO) @Suppress("UNCHECKED_CAST") val escapesBitMask = (escapesAnnotation?.getValueArgument(0) as? IrConst<Int>)?.value @Suppress("UNCHECKED_CAST") val pointsToBitMask = (pointsToAnnotation?.getValueArgument(0) as? IrVararg)?.elements?.map { (it as IrConst<Int>).value } FunctionSymbol.External(name.localHash.value, attributes, it, takeName { name }, it.isExported()).apply { escapes = escapesBitMask pointsTo = pointsToBitMask?.toIntArray() } } else -> { val isAbstract = it is IrSimpleFunction && it.modality == Modality.ABSTRACT val irClass = it.parent as? IrClass val bridgeTarget = it.bridgeTarget val isSpecialBridge = bridgeTarget.let { it != null && BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(it.descriptor) != null } val bridgeTargetSymbol = if (isSpecialBridge || bridgeTarget == null) null else mapFunction(bridgeTarget) val placeToFunctionsTable = !isAbstract && it !is IrConstructor && irClass != null && !irClass.isNonGeneratedAnnotation() && (it.isOverridableOrOverrides || bridgeTarget != null || function.isSpecial || !irClass.isFinal()) val symbolTableIndex = if (placeToFunctionsTable) module.numberOfFunctions++ else -1 val frozen = it is IrConstructor && irClass!!.annotations.findAnnotation(KonanFqNames.frozen) != null val functionSymbol = if (it.isExported()) FunctionSymbol.Public(name.localHash.value, module, symbolTableIndex, attributes, it, bridgeTargetSymbol, takeName { name }) else FunctionSymbol.Private(privateFunIndex++, module, symbolTableIndex, attributes, it, bridgeTargetSymbol, takeName { name }) if (frozen) { functionSymbol.escapes = 0b1 // Assume instances of frozen classes escape. } functionSymbol } } functionMap[it] = symbol symbol.parameters = (function.allParameters.map { it.type } + (if (function.isSuspend) listOf(continuationType) else emptyList())) .map { mapTypeToFunctionParameter(it) } .toTypedArray() symbol.returnParameter = mapTypeToFunctionParameter(if (function.isSuspend) context.irBuiltIns.anyType else function.returnType) return symbol } private val IrFunction.isSpecial get() = origin == DECLARATION_ORIGIN_INLINE_CLASS_SPECIAL_FUNCTION || origin is DECLARATION_ORIGIN_BRIDGE_METHOD private fun mapPropertyInitializer(irField: IrField): FunctionSymbol { functionMap[irField]?.let { return it } assert(irField.parent !is IrClass) { "All local properties initializers should've been lowered" } val attributes = FunctionAttributes.IS_GLOBAL_INITIALIZER or FunctionAttributes.RETURNS_UNIT val symbol = FunctionSymbol.Private(privateFunIndex++, module, -1, attributes, null, null, takeName { "${irField.symbolName}_init" }) functionMap[irField] = symbol symbol.parameters = emptyArray() symbol.returnParameter = mapTypeToFunctionParameter(context.irBuiltIns.unitType) return symbol } } }
apache-2.0
71f87c351bab0e32d733791c4a40bb3d
44.745008
168
0.566607
5.455028
false
false
false
false
fabmax/binparse
src/test/kotlin/de/fabmax/binparse/examples/BuilderExample.kt
1
1501
package de.fabmax.binparse.examples import de.fabmax.binparse.BinWriter import de.fabmax.binparse.Parser import de.fabmax.binparse.struct import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream /** * Created by max on 24.11.2015. */ fun main(args: Array<String>) { val parser = Parser.fromFile("src/test/binparse/dns.bp") val msgDef = parser.structs["main"]!! // builders rock! val instance = struct { int("id") { set(12345) } struct("flags") { int("QR") { set(1) } int("OPCODE") { } int("AA") { set(23) } int("TC") { } int("RD") { } int("RA") { } int("Z") { } int("AD") { } int("CD") { } int("RCODE"){ set(1) } } // int("num_questions") { } // int("num_answers") { } // int("num_authorities") { } // int("num_additionals") { } array("questions") { } array("answers") { } array("authorities") { } array("additionals") { } } println("matches instance: " + msgDef.matchesInstance(instance)) val outStream = ByteArrayOutputStream() msgDef.write(outStream, instance) println() for (b in outStream.toByteArray()) { System.out.printf("%03d ", b.toInt() and 0xff); } println("\n") val inStream = ByteArrayInputStream(outStream.toByteArray()) val parsed = msgDef.parse(inStream) println(parsed.toString(0)) }
apache-2.0
4b08e63e6514c5d69abfa1fb6e12aeeb
25.333333
68
0.548301
3.743142
false
false
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/extractors/ImageUrlExtractor.kt
1
1985
@file:Suppress("DEPRECATION") package com.chimbori.crux.extractors import com.chimbori.crux.common.anyChildTagWithAttr import com.chimbori.crux.common.nullIfBlank import java.util.regex.Pattern import okhttp3.HttpUrl import org.jsoup.nodes.Element import org.jsoup.parser.Parser.unescapeEntities import org.jsoup.select.Elements /** * Given a single DOM Element root, this extractor inspects the sub-tree and returns the best possible image URL * candidate available within it. The use case for this application is to pick a single representative image from a DOM * sub-tree, in a way that works without explicit CSS selector foo. Check out the test cases for markup that is * supported. */ @Suppress("unused") public class ImageUrlExtractor(private val url: HttpUrl, private val root: Element) { public var imageUrl: HttpUrl? = null private set public fun findImage(): ImageUrlExtractor { ( root.attr("src").nullIfBlank() ?: root.attr("data-src").nullIfBlank() ?: root.select("img").anyChildTagWithAttr("src") ?: root.select("img").anyChildTagWithAttr("data-src") ?: root.select("*").anyChildTagWithAttr("src") ?: root.select("*").anyChildTagWithAttr("data-src") ?: parseImageUrlFromStyleAttr(root.select("[role=img]")) ?: parseImageUrlFromStyleAttr(root.select("*")) )?.let { imageUrl = url.resolve(it) } return this } private fun parseImageUrlFromStyleAttr(elements: Elements): String? { elements.forEach { element -> var styleAttr = element.attr("style") if (styleAttr.isNullOrEmpty()) { return@forEach } styleAttr = unescapeEntities(styleAttr, true) val cssUrlMatcher = CSS_URL.matcher(styleAttr) if (cssUrlMatcher.find()) { return cssUrlMatcher.group(1) } } return null } public companion object { private val CSS_URL = Pattern.compile("url\\([\\\"']{0,1}(.+?)[\\\"']{0,1}\\)") } }
apache-2.0
fb74bf1e960e2fe220cc2addb3a35573
34.446429
119
0.681612
4.214437
false
false
false
false
nickbutcher/plaid
app/src/main/java/io/plaidapp/ui/HomeActivity.kt
1
24633
/* * Copyright 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.ui import android.annotation.SuppressLint import android.app.Activity import android.app.ActivityManager import android.app.ActivityOptions import android.content.Context import android.content.Intent import android.graphics.drawable.AnimatedVectorDrawable import android.os.Bundle import android.text.Annotation import android.text.Spannable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.SpannedString import android.text.style.ForegroundColorSpan import android.text.style.ImageSpan import android.transition.TransitionManager import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.ViewStub import android.view.WindowInsets import android.widget.FrameLayout import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.AppCompatCheckBox import androidx.appcompat.widget.Toolbar import androidx.appcompat.widget.TooltipCompat import androidx.core.content.ContextCompat import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.Observer import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader import com.bumptech.glide.util.ViewPreloadSizeProvider import io.plaidapp.R import io.plaidapp.core.dagger.qualifier.IsPocketInstalled import io.plaidapp.core.data.prefs.SourcesRepository import io.plaidapp.core.dribbble.data.api.model.Shot import io.plaidapp.core.feed.FeedAdapter import io.plaidapp.core.feed.FeedProgressUiModel import io.plaidapp.core.feed.FeedUiModel import io.plaidapp.core.ui.ConnectivityChecker import io.plaidapp.core.ui.HomeGridItemAnimator import io.plaidapp.core.ui.filter.FilterAdapter import io.plaidapp.core.ui.filter.FilterAnimator import io.plaidapp.core.ui.filter.SourcesHighlightUiModel import io.plaidapp.core.ui.filter.SourcesUiModel import io.plaidapp.core.ui.recyclerview.InfiniteScrollListener import io.plaidapp.core.util.Activities import io.plaidapp.core.util.AnimUtils import io.plaidapp.core.util.ColorUtils import io.plaidapp.core.util.ViewUtils import io.plaidapp.core.util.drawableToBitmap import io.plaidapp.core.util.event.Event import io.plaidapp.core.util.intentTo import io.plaidapp.dagger.inject import io.plaidapp.ui.recyclerview.FilterTouchHelperCallback import io.plaidapp.ui.recyclerview.GridItemDividerDecoration import javax.inject.Inject /** * Main entry point to Plaid. * * Displays home feed. */ class HomeActivity : AppCompatActivity() { private var columns = 0 private var filtersAdapter = FilterAdapter() private lateinit var gridLayoutManager: GridLayoutManager private lateinit var drawer: DrawerLayout private lateinit var toolbar: Toolbar private lateinit var grid: RecyclerView private lateinit var loading: ProgressBar private lateinit var feedAdapter: FeedAdapter private lateinit var filtersList: RecyclerView // data @Inject lateinit var sourcesRepository: SourcesRepository @Inject @JvmField var connectivityChecker: ConnectivityChecker? = null @Inject lateinit var viewModel: HomeViewModel @IsPocketInstalled @JvmField var pocketInstalled = false private val noFiltersEmptyText by lazy { val view = findViewById<ViewStub>(R.id.stub_no_filters).inflate() as TextView // create the no filters empty text val emptyText = getText(R.string.no_filters_selected) as SpannedString val ssb = SpannableStringBuilder(emptyText) val annotations = emptyText.getSpans(0, emptyText.length, Annotation::class.java) annotations?.forEach { annotation -> if (annotation.key == "src") { // image span markup val id = annotation.getResId(this@HomeActivity) if (id != 0) { ssb.setSpan( ImageSpan(this, id, ImageSpan.ALIGN_BASELINE), emptyText.getSpanStart(annotation), emptyText.getSpanEnd(annotation), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } else if (annotation.key == "foregroundColor") { // foreground color span markup val id = annotation.getResId(this@HomeActivity) if (id != 0) { ssb.setSpan( ForegroundColorSpan(ContextCompat.getColor(this, id)), emptyText.getSpanStart(annotation), emptyText.getSpanEnd(annotation), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } } } with(view) { text = ssb setOnClickListener { drawer.openDrawer(GravityCompat.END) } view } } private val noConnection by lazy { findViewById<ViewStub>(R.id.stub_no_connection).inflate() as ImageView } private val toolbarElevation = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { // we want the grid to scroll over the top of the toolbar but for the toolbar items // to be clickable when visible. To achieve this we play games with elevation. The // toolbar is laid out in front of the grid but when we scroll, we lower it's elevation // to allow the content to pass in front (and reset when scrolled to top of the grid) if (newState == RecyclerView.SCROLL_STATE_IDLE && gridLayoutManager.findFirstVisibleItemPosition() == 0 && gridLayoutManager.findViewByPosition(0)!!.top == grid.paddingTop && toolbar.translationZ != 0f ) { // at top, reset elevation toolbar.translationZ = 0f } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING && toolbar.translationZ != -1f) { // grid scrolled, lower toolbar to allow content to pass in front toolbar.translationZ = -1f } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) bindResources() inject(this) feedAdapter = FeedAdapter(this, columns, pocketInstalled, ColorUtils.isDarkTheme(this)) connectivityChecker?.apply { lifecycle.addObserver(this) connectedStatus.observe(this@HomeActivity, Observer<Boolean> { if (it) { handleNetworkConnected() } else { handleNoNetworkConnection() } }) } ?: handleNoNetworkConnection() initViewModelObservers() drawer.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) setSupportActionBar(toolbar) if (savedInstanceState == null) { animateToolbar() } setExitSharedElementCallback(FeedAdapter.createSharedElementReenterCallback(this)) setupGrid() // drawer layout treats fitsSystemWindows specially so we have to handle insets ourselves drawer.setOnApplyWindowInsetsListener { _, insets -> handleDrawerInsets(insets) insets.consumeSystemWindowInsets() } setupTaskDescription() filtersList.apply { adapter = filtersAdapter itemAnimator = FilterAnimator() } val callback = FilterTouchHelperCallback(filtersAdapter, this) ItemTouchHelper(callback).also { it.attachToRecyclerView(filtersList) } checkEmptyState() } private fun initViewModelObservers() { viewModel.sources.observe(this@HomeActivity, Observer<SourcesUiModel> { filtersAdapter.submitList(it.sourceUiModels) if (it.highlightSources != null) { val highlightUiModel = (it.highlightSources as Event<SourcesHighlightUiModel>) .consume() if (highlightUiModel != null) { highlightPosition(highlightUiModel) } } }) viewModel.feedProgress.observe(this@HomeActivity, Observer<FeedProgressUiModel> { if (it.isLoading) { feedAdapter.dataStartedLoading() } else { feedAdapter.dataFinishedLoading() } }) viewModel.getFeed(columns).observe(this@HomeActivity, Observer<FeedUiModel> { feedAdapter.items = it.items checkEmptyState() }) } private fun bindResources() { drawer = findViewById(R.id.drawer) toolbar = findViewById(R.id.toolbar) grid = findViewById(R.id.grid) filtersList = findViewById(R.id.filters) loading = findViewById(android.R.id.empty) columns = resources.getInteger(R.integer.num_columns) } private fun setupGrid() { gridLayoutManager = GridLayoutManager(this@HomeActivity, columns).apply { spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return feedAdapter.getItemColumnSpan(position) } } } val infiniteScrollListener = object : InfiniteScrollListener(gridLayoutManager) { override fun onLoadMore() { viewModel.loadData() } override fun isDataLoading(): Boolean { val uiModel = viewModel.feedProgress.value return uiModel?.isLoading ?: false } } val shotPreloadSizeProvider = ViewPreloadSizeProvider<Shot>() val shotPreloader = RecyclerViewPreloader( this@HomeActivity, feedAdapter, shotPreloadSizeProvider, 4 ) with(grid) { layoutManager = gridLayoutManager adapter = feedAdapter addOnScrollListener(toolbarElevation) addOnScrollListener(infiniteScrollListener) setHasFixedSize(true) addItemDecoration( GridItemDividerDecoration( this@HomeActivity, R.dimen.divider_height, R.color.divider ) ) itemAnimator = HomeGridItemAnimator() addOnScrollListener(shotPreloader) } } private fun handleDrawerInsets(insets: WindowInsets) { // inset the toolbar down by the status bar height val lpToolbar = (toolbar.layoutParams as ViewGroup.MarginLayoutParams).apply { topMargin += insets.systemWindowInsetTop leftMargin += insets.systemWindowInsetLeft rightMargin += insets.systemWindowInsetRight } toolbar.layoutParams = lpToolbar // inset the grid top by statusbar+toolbar & the bottom by the navbar (don't clip) grid.setPadding( grid.paddingLeft + insets.systemWindowInsetLeft, // landscape insets.systemWindowInsetTop + ViewUtils.getActionBarSize(this@HomeActivity), grid.paddingRight + insets.systemWindowInsetRight, // landscape grid.paddingBottom + insets.systemWindowInsetBottom ) // we place a background behind the status bar to combine with it's semi-transparent // color to get the desired appearance. Set it's height to the status bar height val statusBarBackground = findViewById<View>(R.id.status_bar_background) val lpStatus = (statusBarBackground.layoutParams as FrameLayout.LayoutParams).apply { height = insets.systemWindowInsetTop } statusBarBackground.layoutParams = lpStatus // inset the filters list for the status bar / navbar // need to set the padding end for landscape case val ltr = filtersList.layoutDirection == View.LAYOUT_DIRECTION_LTR with(filtersList) { setPaddingRelative( paddingStart, paddingTop + insets.systemWindowInsetTop, paddingEnd + if (ltr) { insets.systemWindowInsetRight } else { 0 }, paddingBottom + insets.systemWindowInsetBottom ) } // clear this listener so insets aren't re-applied drawer.setOnApplyWindowInsetsListener(null) } override fun onActivityReenter(resultCode: Int, data: Intent?) { if (data == null || resultCode != Activity.RESULT_OK || !data.hasExtra(Activities.Dribbble.Shot.RESULT_EXTRA_SHOT_ID) ) { return } // When reentering, if the shared element is no longer on screen (e.g. after an // orientation change) then scroll it into view. val sharedShotId = data.getLongExtra( Activities.Dribbble.Shot.RESULT_EXTRA_SHOT_ID, -1L ) if (sharedShotId != -1L && // returning from a shot feedAdapter.items.isNotEmpty() && // grid populated grid.findViewHolderForItemId(sharedShotId) == null ) { // view not attached val position = feedAdapter.getItemPosition(sharedShotId) if (position == RecyclerView.NO_POSITION) return // delay the transition until our shared element is on-screen i.e. has been laid out postponeEnterTransition() grid.apply { addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange( v: View, l: Int, t: Int, r: Int, b: Int, oL: Int, oT: Int, oR: Int, oB: Int ) { removeOnLayoutChangeListener(this) startPostponedEnterTransition() } }) scrollToPosition(position) } toolbar.translationZ = -1f } } private fun setupToolbar() { toolbar.inflateMenu(R.menu.main) val toggleTheme = toolbar.menu.findItem(R.id.menu_theme) val actionView = toggleTheme.actionView (actionView as AppCompatCheckBox?)?.apply { setButtonDrawable(R.drawable.asl_theme) isChecked = ColorUtils.isDarkTheme(this@HomeActivity) jumpDrawablesToCurrentState() setOnCheckedChangeListener { _, isChecked -> // delay to allow the toggle anim to run postDelayed( { AppCompatDelegate.setDefaultNightMode( if (isChecked) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO ) delegate.applyDayNight() }, 800L ) } TooltipCompat.setTooltipText(this, getString(R.string.theme)) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { setupToolbar() return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { menu.findItem(R.id.menu_designer_news_login) .setTitle( if (viewModel.isDesignerNewsUserLoggedIn()) { R.string.designer_news_log_out } else { R.string.designer_news_login } ) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_filter -> { drawer.openDrawer(GravityCompat.END) true } R.id.menu_search -> { val searchMenuView = toolbar.findViewById<View>(R.id.menu_search) val options = ActivityOptions.makeSceneTransitionAnimation( this, searchMenuView, getString(R.string.transition_search_back) ).toBundle() startActivityForResult(intentTo(Activities.Search), RC_SEARCH, options) true } R.id.menu_designer_news_login -> { if (!viewModel.isDesignerNewsUserLoggedIn()) { startActivity(intentTo(Activities.DesignerNews.Login)) } else { viewModel.logoutFromDesignerNews() // TODO something better than a toast Toast.makeText( applicationContext, R.string.designer_news_logged_out, Toast.LENGTH_SHORT ).show() } true } R.id.menu_about -> { startActivity( intentTo(Activities.About), ActivityOptions.makeSceneTransitionAnimation(this).toBundle() ) true } else -> super.onOptionsItemSelected(item) } } override fun onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.END)) { drawer.closeDrawer(GravityCompat.END) } else { super.onBackPressed() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { RC_SEARCH -> { // reset the search icon which we hid toolbar.findViewById<View>(R.id.menu_search)?.alpha = 1f if (resultCode == Activities.Search.RESULT_CODE_SAVE && data != null) { with(data) { val query = getStringExtra(Activities.Search.EXTRA_QUERY) as String val isDribbble = getBooleanExtra(Activities.Search.EXTRA_SAVE_DRIBBBLE, false) val isDesignerNews = getBooleanExtra(Activities.Search.EXTRA_SAVE_DESIGNER_NEWS, false) viewModel.addSources(query, isDribbble, isDesignerNews) } } } } } private fun checkEmptyState() { if (feedAdapter.items.isEmpty()) { // if grid is empty check whether we're loading or if no filters are selected if (sourcesRepository.getActiveSourcesCount() > 0 && connectivityChecker != null) { connectivityChecker?.connectedStatus?.value?.let { loading.visibility = View.VISIBLE setNoFiltersEmptyTextVisibility(View.GONE) } } else { loading.visibility = View.GONE setNoFiltersEmptyTextVisibility(View.VISIBLE) } toolbar.translationZ = 0f } else { loading.visibility = View.GONE setNoFiltersEmptyTextVisibility(View.GONE) } } private fun setNoFiltersEmptyTextVisibility(visibility: Int) { noFiltersEmptyText.visibility = visibility } @Suppress("DEPRECATION") private fun setupTaskDescription() { val overviewIcon = drawableToBitmap(this, applicationInfo.icon) setTaskDescription( ActivityManager.TaskDescription( getString(R.string.app_name), overviewIcon, ContextCompat.getColor(this, R.color.primary) ) ) overviewIcon?.recycle() } private fun animateToolbar() { // this is gross but toolbar doesn't expose it's children to animate them :( val t = toolbar.getChildAt(0) if (t is TextView) { t.apply { /* Fade in and space out the title. Animating the letterSpacing performs horribly so fake it by setting the desired letterSpacing then animating the scaleX. ¯\_(ツ)_/¯ */ alpha = 0f scaleX = 0.8f animate() .alpha(1f) .scaleX(1f) .setStartDelay(300) .setDuration(900).interpolator = AnimUtils.getFastOutSlowInInterpolator(this@HomeActivity) } } } /** * Highlight the new source(s) by: * 1. opening the drawer * 2. scrolling new source(s) into view * 3. flashing new source(s) background * 4. closing the drawer (if user hasn't interacted with it) */ private fun highlightPosition(uiModel: SourcesHighlightUiModel) { val closeDrawerRunnable = { drawer.closeDrawer(GravityCompat.END) } drawer.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() { // if the user interacts with the filters while it's open then don't auto-close private val filtersTouch = View.OnTouchListener { _, _ -> drawer.removeCallbacks(closeDrawerRunnable) false } override fun onDrawerOpened(drawerView: View) { // scroll to the new item(s) filtersList.apply { smoothScrollToPosition(uiModel.scrollToPosition) setOnTouchListener(filtersTouch) } filtersAdapter.highlightPositions(uiModel.highlightPositions) } @SuppressLint("ClickableViewAccessibility") override fun onDrawerClosed(drawerView: View) { // reset filtersList.setOnTouchListener(null) drawer.removeDrawerListener(this) } override fun onDrawerStateChanged(newState: Int) { // if the user interacts with the drawer manually then don't auto-close if (newState == DrawerLayout.STATE_DRAGGING) { drawer.removeCallbacks(closeDrawerRunnable) } } }) drawer.openDrawer(GravityCompat.END) drawer.postDelayed(closeDrawerRunnable, 2000L) } private fun handleNoNetworkConnection() { loading.visibility = View.GONE (getDrawable(R.drawable.avd_no_connection) as AnimatedVectorDrawable).apply { noConnection.setImageDrawable(this) start() } } private fun handleNetworkConnected() { if (feedAdapter.items.isNotEmpty()) return TransitionManager.beginDelayedTransition(drawer) noConnection.visibility = View.GONE loading.visibility = View.VISIBLE viewModel.loadData() } companion object { private const val RC_SEARCH = 0 private const val RC_NEW_DESIGNER_NEWS_LOGIN = 5 } } /** * Get the resource identifier for an annotation. * @param context The context this should be executed in. */ fun Annotation.getResId(context: Context): Int { return context.resources.getIdentifier(value, null, context.packageName) }
apache-2.0
d52770bb234198b4cc7edf073370b905
36.260212
103
0.605506
5.432069
false
false
false
false
fabmax/binparse
src/main/kotlin/de/fabmax/binparse/StringDef.kt
1
3048
package de.fabmax.binparse import java.nio.charset.Charset import java.util.* /** * Created by max on 17.11.2015. */ class StringDef private constructor(fieldName: String, encoding: Charset, length: ArrayDef.Length) : FieldDef<StringField>(fieldName) { private val encoding = encoding private val length = length override fun toString(): String { return "$fieldName: StringParser: encoding: $encoding, length: $length" } override fun parse(reader: BinReader, parent: ContainerField<*>): StringField { val data = when (length.mode) { ArrayDef.LengthMode.FIXED -> reader.readBytes(length.intLength) ArrayDef.LengthMode.BY_FIELD -> reader.readBytes(parent.getInt(length.strLength).intValue) ArrayDef.LengthMode.BY_VALUE -> readNullTerminated(reader) } return StringField(fieldName, String(data, encoding)) } fun readNullTerminated(reader: BinReader): ByteArray { // fixme: this doesn't really work for UTF-16 val bytes = ArrayList<Byte>() while (length.termParser != null) { reader.mark() if (length.termParser.parseField(reader, ArrayDef.nullTermCtx).value == 0L) { break } reader.reset() bytes.add(reader.readU08().toByte()) } return bytes.toByteArray() } override fun prepareWrite(parent: ContainerField<*>) { super.prepareWrite(parent) val string = parent.getString(fieldName) if (length.mode == ArrayDef.LengthMode.BY_FIELD) { parent.getInt(length.strLength).intValue = string.value.toByteArray(encoding).size } } override fun write(writer: BinWriter, parent: ContainerField<*>) { val string = parent.getString(fieldName) writer.writeBytes(string.value.toByteArray(encoding)); if (length.mode == ArrayDef.LengthMode.BY_VALUE && length.termParser != null) { length.termParser.write(writer, ArrayDef.nullTermCtx) } } override fun matchesDef(parent: ContainerField<*>): Boolean { return parent[fieldName] is StringField } internal class Factory(encoding: Charset?) : FieldDefFactory() { val encoding = encoding override fun createParser(definition: Item): StringDef { val encoding = this.encoding ?: parseEncoding(definition) return StringDef(definition.identifier, encoding, ArrayDef.Factory.parseLength(definition)) } private fun parseEncoding(definition: Item): Charset { val encoding = getItem(definition.childrenMap, "encoding").value if (Charset.isSupported(encoding)) { return Charset.forName(encoding) } else { throw IllegalArgumentException("Unsupported encoding: $encoding") } } } } class StringField(name: String, value: String): Field<String>(name, value) { operator fun String.unaryPlus() { value = this } }
apache-2.0
f86d208621099f6847fecd667a253897
34.44186
103
0.640092
4.646341
false
false
false
false
REBOOTERS/AndroidAnimationExercise
game/src/main/java/com/bird/internal/Floor.kt
1
1364
package com.bird.internal import android.graphics.Bitmap import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Paint import android.graphics.Shader.TileMode class Floor(private val mGameWidth: Int, private val mGameHeight: Int, floorBg: Bitmap?) { /** * x坐标 */ var x = 0 /** * y坐标 */ val y: Int /** * 填充物 */ private val mFloorShader: BitmapShader fun draw(mCanvas: Canvas, mPaint: Paint) { if (-x > mGameWidth) { x %= mGameWidth } mCanvas.saveLayer(0f, 0f, mGameWidth.toFloat(), mGameHeight.toFloat(), null) //移动到指定的位置 mCanvas.translate(x.toFloat(), y.toFloat()) mPaint.shader = mFloorShader mCanvas.drawRect( x.toFloat(), 0f, (-x + mGameWidth).toFloat(), (mGameHeight - y).toFloat(), mPaint ) mCanvas.restore() mPaint.shader = null } companion object { /* * 地板位置游戏面板高度的4/5到底部 */ private const val FLOOR_Y_POS_RADIO = 4 / 5f } init { y = (mGameHeight * FLOOR_Y_POS_RADIO).toInt() mFloorShader = BitmapShader( floorBg!!, TileMode.REPEAT, TileMode.CLAMP ) } }
apache-2.0
bc39a15ba6ad6fb87fbc5d71974fc2e4
21.534483
90
0.556662
4.030864
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/implements/DuplicateInterfacePrefixInspection.kt
1
1519
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.implements import com.demonwav.mcdev.platform.mixin.inspection.MixinAnnotationAttributeInspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.IMPLEMENTS import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findAnnotations import com.demonwav.mcdev.util.ifEmpty import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue class DuplicateInterfacePrefixInspection : MixinAnnotationAttributeInspection(IMPLEMENTS, null) { override fun getStaticDescription() = "Reports duplicate @Interface prefixes in an @Implements annotation." override fun visitAnnotationAttribute( annotation: PsiAnnotation, value: PsiAnnotationMemberValue, holder: ProblemsHolder ) { val interfaces = value.findAnnotations().ifEmpty { return } val prefixes = ArrayList<String>() for (iface in interfaces) { val prefixValue = iface.findDeclaredAttributeValue("prefix") ?: continue val prefix = prefixValue.constantStringValue ?: continue if (prefix in prefixes) { holder.registerProblem(prefixValue, "Duplicate prefix '$prefix'") } else { prefixes.add(prefix) } } } }
mit
5da004bc2492b26f2bf8d6c52c3ec882
33.522727
111
0.724819
5.029801
false
false
false
false
mockk/mockk
modules/mockk-agent-api/src/jvmMain/kotlin/io/mockk/proxy/common/transformation/ClassTransformationSpec.kt
2
1384
package io.mockk.proxy.common.transformation data class ClassTransformationSpec( val cls: Class<*>, val simpleIntercept: Int = 0, val staticIntercept: Int = 0, val constructorIntercept: Int = 0 ) { val shouldDoSimpleIntercept: Boolean get() = simpleIntercept > 0 val shouldDoStaticIntercept: Boolean get() = staticIntercept > 0 val shouldDoConstructorIntercept: Boolean get() = constructorIntercept > 0 val shouldDoSomething get() = shouldDoSimpleIntercept || shouldDoStaticIntercept || shouldDoConstructorIntercept private data class Categories( val simple: Boolean, val static: Boolean, val constructor: Boolean ) private fun categories() = Categories( shouldDoSimpleIntercept, shouldDoStaticIntercept, shouldDoConstructorIntercept ) infix fun sameTransforms(other: ClassTransformationSpec) = categories() == other.categories() override fun toString(): String { val lst = mutableListOf<String>() if (shouldDoSimpleIntercept) { lst.add("mockk") } if (shouldDoStaticIntercept) { lst.add("mockkStatic") } if (shouldDoConstructorIntercept) { lst.add("mockkConstructor") } return lst.joinToString(", ") } }
apache-2.0
72a3e69b3633b87be193756c2b4dbb32
26.156863
97
0.632225
5.536
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/Mesh.kt
1
2201
package com.soywiz.korge.view import com.soywiz.kmem.* import com.soywiz.korge.internal.* import com.soywiz.korge.render.* import com.soywiz.korim.bitmap.* import com.soywiz.korma.geom.* open class Mesh( var texture: BmpSlice? = null, var vertices: Float32Buffer = Float32BufferAlloc(0), var uvs: Float32Buffer = Float32BufferAlloc(0), var indices: Uint16Buffer = Uint16BufferAlloc(0), var drawMode: DrawModes = DrawModes.Triangles ) : View() { enum class DrawModes { Triangles, TriangleStrip } val textureNN get() = texture ?: Bitmaps.white var dirty: Int = 0 var indexDirty: Int = 0 var pivotX: Double = 0.0 var pivotY: Double = 0.0 fun updatedVertices() { dirtyVertices = true } private var tva = TexturedVertexArray.EMPTY private val bb = BoundsBuilder() private val localBounds = Rectangle() private fun recomputeVerticesIfRequired() { if (!dirtyVertices) return dirtyVertices = false // @TODO: Render in one batch without matrix multiplication in CPU val m = globalMatrix val cmul = this.renderColorMul val cadd = this.renderColorAdd val vcount = vertices.size / 2 val isize = indices.size tva = if (vcount > tva.initialVcount || isize > tva.indices.size) TexturedVertexArray(vcount, ShortArray(isize)) else tva tva.vcount = vcount tva.isize = isize bb.reset() val pivotXf = pivotX.toFloat() val pivotYf = pivotY.toFloat() for (n in 0 until tva.isize) tva.indices[n] = indices[n].toShort() for (n in 0 until tva.vcount) { val x = vertices[n * 2 + 0] + pivotXf val y = vertices[n * 2 + 1] + pivotYf tva.quadV(n, m.transformXf(x, y), m.transformYf(x, y), uvs[n * 2 + 0], uvs[n * 2 + 1], cmul, cadd) bb.add(x, y) } bb.getBounds(localBounds) } override fun renderInternal(ctx: RenderContext) { recomputeVerticesIfRequired() ctx.useBatcher { batch -> batch.drawVertices(tva, ctx.getTex(textureNN).base, true, renderBlendMode.factors) } } override fun getLocalBoundsInternal(out: Rectangle) { recomputeVerticesIfRequired() out.copyFrom(localBounds) } } fun <T : Mesh> T.pivot(x: Double, y: Double): T { this.pivotX = x this.pivotY = y return this }
apache-2.0
e91167694e68994458ac320e522d929e
27.217949
123
0.692867
3.180636
false
false
false
false
cashapp/sqldelight
dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/MySqlDialect.kt
1
2123
package app.cash.sqldelight.dialects.mysql import app.cash.sqldelight.dialect.api.ConnectionManager import app.cash.sqldelight.dialect.api.MigrationSquasher import app.cash.sqldelight.dialect.api.RuntimeTypes import app.cash.sqldelight.dialect.api.SqlDelightDialect import app.cash.sqldelight.dialect.api.TypeResolver import app.cash.sqldelight.dialects.mysql.grammar.MySqlParserUtil import app.cash.sqldelight.dialects.mysql.grammar.mixins.ColumnDefMixin import app.cash.sqldelight.dialects.mysql.grammar.mixins.MySqlBinaryEqualityExpr import app.cash.sqldelight.dialects.mysql.ide.MySqlConnectionManager import com.alecstrong.sql.psi.core.SqlParserUtil import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.icons.AllIcons import com.squareup.kotlinpoet.ClassName /** * Base dialect for JDBC implementations. */ class MySqlDialect : SqlDelightDialect { override val runtimeTypes: RuntimeTypes = RuntimeTypes( ClassName("app.cash.sqldelight.driver.jdbc", "JdbcCursor"), ClassName("app.cash.sqldelight.driver.jdbc", "JdbcPreparedStatement"), ) override val asyncRuntimeTypes: RuntimeTypes = RuntimeTypes( ClassName("app.cash.sqldelight.driver.r2dbc", "R2dbcCursor"), ClassName("app.cash.sqldelight.driver.r2dbc", "R2dbcPreparedStatement"), ) override val icon = AllIcons.Providers.Mysql override val connectionManager: ConnectionManager by lazy { MySqlConnectionManager() } override fun setup() { SqlParserUtil.reset() MySqlParserUtil.reset() MySqlParserUtil.overrideSqlParser() val currentElementCreation = MySqlParserUtil.createElement MySqlParserUtil.createElement = { when (it.elementType) { SqlTypes.COLUMN_DEF -> ColumnDefMixin(it) SqlTypes.BINARY_EQUALITY_EXPR -> MySqlBinaryEqualityExpr(it) else -> currentElementCreation(it) } } } override fun typeResolver(parentResolver: TypeResolver): TypeResolver { return MySqlTypeResolver(parentResolver) } override fun migrationSquasher(parentSquasher: MigrationSquasher): MigrationSquasher { return MySqlMigrationSquasher(parentSquasher) } }
apache-2.0
c7a408b8d612837a44ddb02acee7eb43
36.910714
88
0.78992
4.35041
false
false
false
false
teamblueridge/PasteIt
app/src/main/kotlin/org/teamblueridge/pasteitapp/ApiHandler.kt
1
2913
package org.teamblueridge.pasteitapp import android.app.Activity import android.content.Context import android.support.v7.app.AlertDialog import android.util.JsonReader import android.util.Log import com.pawegio.kandroid.runAsync; import org.teamblueridge.utils.NetworkUtil import java.io.IOException import java.io.InputStreamReader import java.util.* import kotlin.collections.HashMap /** * Communicates with the Stikked API to get the data necessary * * @author Kyle Laker (kalaker) * @see UploadDownloadUrlPrep */ class ApiHandler { companion object { private val TAG = "TeamBlueRidge" } /** * Gets a list of the languages supported by the remote server * * @param context Used in order to be able to read the JSON file * @param listType Used in order to identify which Array<String> to use * @return a Array<String>, either pretty or ugly, depending on what is needed */ fun getLanguages(context: Context): Map<String, String> { val langMap = TreeMap<String, String>() try { val reader = JsonReader(InputStreamReader(context.openFileInput("languages"), "UTF-8")) reader.beginObject() while (reader.hasNext()) { langMap.put(reader.nextName(), reader.nextString()) } reader.endObject() reader.close() } catch (e: IOException) { Log.e(TAG, "Error reading languages file") Log.e(TAG, e.toString()) } langMap.remove("0") return langMap.toSortedMap() } /** * Downloads the list of languages from the Stikked API. * * @param activity The context of the calling activity * @param languageUrl The URL from which to fetch the languages * @param filename The file to which to write the languages. Defaults to "languages". */ fun getLanguages(activity: Activity, languageUrl: String, filename: String = "languages") { runAsync { val languageList = NetworkUtil.readFromUrl(activity, languageUrl) activity.openFileOutput(filename, Context.MODE_PRIVATE).use { if (languageList.isNotEmpty()) { it.write(languageList.toByteArray()) } else { it.write("{\"text\":\"Plain Text\"}".toByteArray()) activity.runOnUiThread { val alertBuilder = AlertDialog.Builder(activity) alertBuilder.setMessage(activity.resources.getString(R.string.error_api_key)) alertBuilder.setCancelable(true) alertBuilder.setNeutralButton(android.R.string.ok) { dialog, id -> dialog.cancel() } val alert = alertBuilder.create() alert.show() } } } } } }
gpl-3.0
6008373ddcf6992733149078b06c73a4
35.4125
108
0.610367
4.653355
false
false
false
false
mskn73/kache
kachelib/src/test/java/com/mskn73/kache/KacheTest.kt
1
3110
package com.fernandocejas.android.sample import com.mskn73.kache.AndroidTest import com.mskn73.kache.Kache import com.mskn73.kache.Kacheable import com.mskn73.kache.annotations.KacheLife import org.amshove.kluent.Verify import org.amshove.kluent.called import org.amshove.kluent.mock import org.amshove.kluent.on import org.amshove.kluent.shouldEqualTo import org.amshove.kluent.that import org.amshove.kluent.was import org.junit.After import org.junit.Before import org.junit.Test import java.io.File import kotlin.test.assertFails import kotlin.test.assertTrue /** * Created by francisco.hernandez on 22/5/17. */ class KacheTest : AndroidTest() { val kache = Kache(context(), cacheDir().path) @Before fun setUp() { } @After fun tearDown() { val dir = cacheDir() if (dir.isDirectory()) { val children = dir.list() for (i in children.indices) { File(dir, children[i]).delete() } } } @Test fun shouldBeCached() { val key = "key1" val dummy = DummyObject(key, "content") kache.put(dummy) val expectedContent = kache.isCached(key) expectedContent shouldEqualTo true } @Test fun shouldNotBeCached() { val key1 = "key1" val key2 = "key2" val dummy = DummyObject(key1, "content") kache.put(dummy) val expectedContent = kache.isCached(key2) expectedContent shouldEqualTo false } @Test fun shouldGetData() { val key = "key1" val data = "content" val dummy = DummyObject(key, data) kache.put(dummy) val expectContent = kache.get(DummyObject::class.java, key) if (expectContent is DummyObject) { expectContent.data shouldEqualTo data } else { assertTrue(expectContent is DummyObject) } } @Test fun shouldNotBeExpired() { val key = "key1" val dummy = DummyObject(key, "content") kache.put(dummy) Thread.sleep(1000) val expectedContent = kache.isExpired(key, dummy.javaClass) expectedContent shouldEqualTo false } @Test fun shouldBeExpired() { val key = "key1" val dummy = DummyObject(key, "content") kache.put(dummy) Thread.sleep(1000) val expectedContent = kache.isExpired(key, dummy.javaClass) assertFails({ Verify on kache that kache.evict(key) was called }) expectedContent shouldEqualTo false } @Test fun shouldBeEvicted() { val key = "key1" val dummy = DummyObject(key, "content") kache.put(dummy) kache.evict(key) val expectedContent = kache.isCached(key) expectedContent shouldEqualTo false } @Test fun shouldBeEvictAll() { val key1 = "key1" val dummy1 = DummyObject(key1, "content") val key2 = "key2" val dummy2 = DummyObject(key2, "content") kache.put(dummy1) kache.put(dummy2) kache.evictAll() val expectedContent = kache.isCached(key1) || kache.isCached(key2) expectedContent shouldEqualTo false } class DummyObject(override val key: String, val data: String) : Kacheable @KacheLife(expiresTime = 1) class DummyObject1(override val key: String, val data: String) : Kacheable }
gpl-3.0
5dcfffaa6b3205f24b9b1d9e76de64ac
21.221429
76
0.687781
3.697979
false
true
false
false
vimeo/vimeo-networking-java
model-generator/plugin/src/main/java/com/vimeo/modelgenerator/ModelFactory.kt
1
16487
package com.vimeo.modelgenerator import com.squareup.kotlinpoet.* import com.vimeo.modelgenerator.extensions.* import com.vimeo.modelgenerator.visitor.* import org.gradle.api.GradleException import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.util.isOrdinaryClass import java.io.File /** * A factory that will generates new models from the given [KtFiles][KtFile]. * * @param path the file path that points to where the generated files should be put. * @param classVisitor a [ModifyVisitor] that is used to make changes to classes. * @param interfaceVisitor a [ModifyVisitor] that is used to make changes to interfaces. */ internal class ModelFactory( private val path: String, private val classVisitor: ModifyVisitor, private val interfaceVisitor: ModifyVisitor ) { /** * Takes the given [KtFile] and uses it to generate a new model. * * @param ktFile the [KtFile] of the file that will be parsed and used to generate a new model. */ fun buildModel(ktFile: KtFile) { val elements = ktFile.children.filter { it is KtClass || it is KtNamedFunction || it is KtProperty } val imports = ktFile.importDirectives.map { it.importPath.toString() } // Class name is key full package is entry, ie: <Date, java.util>, <Serializable, java.io> .map { Pair(it.substringAfterLast("."), it.substringBeforeLast(".")) } val name = ktFile.name.substringAfterLast("/").substringBefore(".kt") val fileAnnotations = ktFile.annotationEntries.map { AnnotationSpec.builder( ClassName( "", it.shortName?.asString().orEmpty() ) ) .addMembers(it.valueArguments) .build() } val packageName = ktFile.packageFqName.asString() FileSpec.builder( packageName = packageName, fileName = name ) .addImports(imports) .addTypes( elements.filterIsInstance<KtClass>().map { buildType(it, packageName) }) .addFunctions( elements.filterIsInstance<KtNamedFunction>().map { buildFunction(it, packageName) } ) .addProperties( elements.filterIsInstance<KtProperty>().map { buildProperty(it, packageName) } ) .addIfConditionMet(fileAnnotations.isNotEmpty()) { addAnnotations(fileAnnotations) } .build() .writeTo(File(path)) } private fun buildType( clazz: KtClass, packageName: String ): TypeSpec = when { clazz.isInterface() -> buildInterface(clazz, packageName) clazz.isEnum() -> buildEnum(clazz, packageName) clazz.isAnnotation() -> buildAnnotation(clazz, packageName) clazz.isData() || clazz.isOrdinaryClass -> buildClass(clazz, packageName) else -> throw GradleException("$clazz: This class is not supported.") } private fun buildFunction( function: KtNamedFunction, packageName: String ): FunSpec = FunSpec.builder(function.validateName) .addIfConditionMet(function.modifierList?.isInline == true) { addModifiers(KModifier.INLINE) } .addIfConditionMet(function.isExtensionDeclaration()) { receiver( createTypeName( function.receiverTypeReference, packageName ) ) returns( createTypeName( function.typeReference, packageName ) ) } .addIfConditionMet(function.typeParameters.isNotEmpty()) { addTypeVariables( createTypeVariables( function.typeParameters, packageName, function.typeConstraints, isInline = function.modifierList?.isInline == true ) ) } .addIfConditionMet(function.typeReference != null) { addStatement("return ${function.bodyExpression?.text.orEmpty()}") } .addIfConditionMet(function.typeReference == null) { val content = function.bodyBlockExpression?.statements if (!content.isNullOrEmpty()) { val statements = content.map { it.text } statements.forEach { addStatement(it) } } else { // Function has no content and is declared in an interface addModifiers(KModifier.ABSTRACT) } } .addParameters(function.valueParameters.map { param -> ParameterSpec.builder( param.validateName, createTypeName( param.typeReference, packageName ) ) .build() }) .addKdoc(function.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(function.docComment?.blockTags.orEmpty()) .addAnnotations( createAnnotations( function.annotationEntries, packageName ) ) .addIfConditionMet(function.visibilityModifier != null) { addModifiers(function.visibilityModifier!!) } .build() private fun buildProperty( property: KtProperty, packageName: String ): PropertySpec = PropertySpec.builder( property.validateName, createTypeName( property.typeReference, packageName ) ) .addIfConditionMet(property.modifierList?.isOverridden == true) { addModifiers(KModifier.OVERRIDE) } .addIfConditionMet(property.initializer?.text != null) { initializer(property.initializer?.text!!) } .addIfConditionMet(property.isExtensionDeclaration()) { receiver( createTypeName( property.receiverTypeReference, packageName ) ) } .addAnnotations( createAnnotations( property.annotationEntries, packageName ) ) .addIfConditionMet(property.getter != null) { getter( FunSpec.getterBuilder() .addIfConditionMet ( property.getter?.modifierList?.isInline == true || property.modifierList?.isInline == true ) { addModifiers(KModifier.INLINE) } .addStatement("return ${property.getter?.bodyExpression?.text.orEmpty()}") .build() ) } .addKdoc(property.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(property.docComment?.blockTags.orEmpty()) .addIfConditionMet(property.visibilityModifier != null) { addModifiers(property.visibilityModifier!!) } .build() private fun buildAnnotation( clazz: KtClass, packageName: String ): TypeSpec { val properties = clazz.primaryConstructorParameters .map { PropertySpec.builder( it.validateName, createTypeName( it.typeReference, packageName ) ) .initializer(it.validateName) .addKdoc(it.docComment?.getDefaultSection()?.getContent().orEmpty()) .addIfConditionMet(it.modifierList?.isOverridden == true) { addModifiers(KModifier.OVERRIDE) } .build() } return TypeSpec.annotationBuilder(clazz.validateName) .addKdoc(clazz.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(clazz.docComment?.blockTags.orEmpty()) .addAnnotations( createAnnotations( clazz.annotationEntries, packageName ) ) .primaryConstructor( FunSpec.constructorBuilder().addParameters( createConstructorParams( clazz.primaryConstructorParameters, packageName ) ).build() ) .addProperties(properties) .addIfConditionMet(clazz.visibilityModifier != null) { addModifiers(clazz.visibilityModifier!!) } .build() } private fun buildEnum( clazz: KtClass, packageName: String ): TypeSpec { val properties = clazz.primaryConstructorParameters .map { PropertySpec.builder( it.validateName, createTypeName( it.typeReference, packageName ) ) .initializer(it.validateName) .addKdoc(it.docComment?.getDefaultSection()?.getContent().orEmpty()) .addIfConditionMet(it.modifierList?.isOverridden == true) { addModifiers(KModifier.OVERRIDE) } .build() } val enums = clazz.body?.enumEntries?.map { entry -> val superTypeCall = entry.initializerList?.children?.find { it is KtSuperTypeCallEntry } as KtSuperTypeCallEntry? val args = superTypeCall?.valueArguments?.toParams?.map { Pair("%L", it) }.orEmpty() Pair( entry.validateName, TypeSpec.anonymousClassBuilder() .addSuperclassConstructorParameters(args) .addKdoc(entry.docComment?.getDefaultSection()?.getContent().orEmpty()) .addAnnotations( createAnnotations( entry.annotationEntries, packageName ) ) .build() ) }.orEmpty() return TypeSpec.enumBuilder(clazz.validateName) .addAnnotations( createAnnotations( clazz.annotationEntries, packageName ) ) .primaryConstructor( FunSpec.constructorBuilder().addParameters( createConstructorParams( clazz.primaryConstructorParameters, packageName ) ).build() ) .addEnumConstants(enums) .addProperties(properties) .addKdoc(clazz.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(clazz.docComment?.blockTags.orEmpty()) .addIfConditionMet(clazz.visibilityModifier != null) { addModifiers(clazz.visibilityModifier!!) } .addSuperinterfaces( createSuperTypes( clazz.superTypeListEntries, packageName ) ) .addIfConditionMet(classVisitor is ParcelableClassVisitor) { classVisitor.modify(this, clazz, packageName) } .build() } private fun buildInterface( clazz: KtClass, packageName: String ): TypeSpec = TypeSpec.interfaceBuilder(clazz.validateName) .addIfConditionMet(clazz.typeParameters.isNotEmpty()) { addTypeVariables( createTypeVariables( clazz.typeParameters, packageName = packageName ) ) } .addKdoc(clazz.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(clazz.docComment?.blockTags.orEmpty()) .addIfConditionMet(clazz.superTypeListEntries.isNotEmpty()) { addSuperinterfaces( createSuperTypes( clazz.superTypeListEntries, packageName ) ) } .addIfConditionMet(clazz.visibilityModifier != null) { addModifiers(clazz.visibilityModifier!!) } .addProperties(clazz.getProperties().map { buildProperty(it, packageName) }) .addAnnotations( createAnnotations( clazz.annotationEntries, packageName ) ) .addIfConditionMet(clazz.body?.functions?.isNotEmpty() == true) { addFunctions(clazz.body?.functions!!.map { buildFunction(it, packageName) }) } .run { interfaceVisitor.modify(this, clazz, packageName) } .build() private fun buildClass( clazz: KtClass, packageName: String ): TypeSpec { val secondaryConstructors = clazz.secondaryConstructors.map { constructor -> FunSpec.constructorBuilder() .addKdoc(constructor.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(constructor.docComment?.blockTags.orEmpty()) .callThisConstructor(constructor.getDelegationCall().valueArguments.toParams.map { CodeBlock.Builder().add(it).build() }) .addParameters(constructor.valueParameters.map { param -> ParameterSpec.builder( param.validateName, createTypeName( param.typeReference, packageName ) ) .build() }) .build() } val properties = clazz.primaryConstructorParameters .map { PropertySpec.builder( it.validateName, createTypeName( it.typeReference, packageName ) ) .initializer(it.validateName) .addKdoc(it.docComment?.getDefaultSection()?.getContent().orEmpty()) .addIfConditionMet(it.modifierList?.isOverridden == true) { addModifiers(KModifier.OVERRIDE) } .build() } val builder = TypeSpec.classBuilder(clazz.validateName) .addIfConditionMet(clazz.isData()) { addModifiers(KModifier.DATA) } .addAnnotations( createAnnotations( clazz.annotationEntries, packageName ) ) .addKdoc(clazz.docComment?.getDefaultSection()?.getContent().orEmpty()) .addKdocs(clazz.docComment?.blockTags.orEmpty()) .primaryConstructor( FunSpec.constructorBuilder().addParameters( createConstructorParams( clazz.primaryConstructorParameters, packageName ) ).build() ) .addFunctions(secondaryConstructors) .addIfConditionMet(clazz.superTypeListEntries.isNotEmpty()) { addSuperinterfaces( createSuperTypes( clazz.superTypeListEntries, packageName ) ) } .addIfConditionMet(clazz.visibilityModifier != null) { addModifiers(clazz.visibilityModifier!!) } .addProperties(properties) .addIfConditionMet(clazz.body?.functions?.isNotEmpty() == true) { addFunctions(clazz.body?.functions!!.map { buildFunction(it, packageName) }) } .addProperties(clazz.getProperties().map { buildProperty(it, packageName) }) return classVisitor.modify(builder, clazz, packageName).build() } }
mit
45d562a0fefe890967939b7b04732c10
35.966368
109
0.528902
6.44527
false
false
false
false
AndroidX/androidx
testutils/testutils-runtime/src/androidTest/java/androidx/testutils/LocaleTestUtilsTest.kt
3
4702
/* * 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.os.Build import androidx.core.os.ConfigurationCompat import androidx.core.view.ViewCompat.LAYOUT_DIRECTION_LTR import androidx.core.view.ViewCompat.LAYOUT_DIRECTION_RTL import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.hamcrest.CoreMatchers import org.hamcrest.MatcherAssert.assertThat import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.Locale // Fetch default locale as early as possible (e.g., before initializing LocaleTestUtilsTest class) private val DEFAULT_LANGUAGE = Locale.getDefault().toString() @RunWith(AndroidJUnit4::class) @LargeTest class LocaleTestUtilsTest { private val configuration: Configuration get() = (ApplicationProvider.getApplicationContext() as Context).resources.configuration private val Configuration.language: String get() = ConfigurationCompat.getLocales(this).get(0).toString() private lateinit var localeUtil: LocaleTestUtils private var expectRtlInDefaultLanguage: Boolean = false @Before fun setUp() { localeUtil = LocaleTestUtils( ApplicationProvider.getApplicationContext() as Context ) determineDefaultLayoutDirection() } @After fun tearDown() { localeUtil.resetLocale() } @Test fun test_defaultValues() { assertDefaultValues() } @Test fun test_setAndResetLocale() { assertDefaultValues() localeUtil.setLocale(LocaleTestUtils.LTR_LANGUAGE) assertLocaleIs(LocaleTestUtils.LTR_LANGUAGE, false) localeUtil.resetLocale() assertDefaultValues() localeUtil.setLocale(LocaleTestUtils.RTL_LANGUAGE) assertLocaleIs(LocaleTestUtils.RTL_LANGUAGE, true) localeUtil.resetLocale() assertDefaultValues() } @Test fun test_ltrRtlLanguagesExist() { val availableLanguages = Locale.getAvailableLocales().map { it.toString() } val getReason: (String, String) -> String = { name, code -> "$name test language '$code' does not exist on test device" } assertThat( getReason( "Default", LocaleTestUtils.DEFAULT_TEST_LANGUAGE ), availableLanguages, CoreMatchers.hasItem(LocaleTestUtils.DEFAULT_TEST_LANGUAGE) ) assertThat( getReason("LTR", LocaleTestUtils.LTR_LANGUAGE), availableLanguages, CoreMatchers.hasItem(LocaleTestUtils.LTR_LANGUAGE) ) assertThat( getReason("RTL", LocaleTestUtils.RTL_LANGUAGE), availableLanguages, CoreMatchers.hasItem(LocaleTestUtils.RTL_LANGUAGE) ) } private fun assertDefaultValues() { assertLocaleIs(DEFAULT_LANGUAGE, expectRtlInDefaultLanguage) } private fun assertLocaleIs(lang: String, expectRtl: Boolean) { assertThat( "Locale should be $lang", configuration.language, CoreMatchers.equalTo(lang) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { assertThat( "Layout direction should be ${if (expectRtl) "RTL" else "LTR"}", configuration.layoutDirection, CoreMatchers.equalTo(if (expectRtl) LAYOUT_DIRECTION_RTL else LAYOUT_DIRECTION_LTR) ) } } private fun determineDefaultLayoutDirection() { assertThat( "Locale must still be the default when determining the default layout direction", configuration.language, CoreMatchers.equalTo(DEFAULT_LANGUAGE) ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { expectRtlInDefaultLanguage = configuration.layoutDirection == LAYOUT_DIRECTION_RTL } } }
apache-2.0
d85c5452292e119ffe8783bf7370ff49
33.321168
99
0.680987
4.939076
false
true
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solution/HiddenSetDerivation.kt
1
1537
package de.sudoq.model.solverGenerator.solution import de.sudoq.model.actionTree.Action import de.sudoq.model.actionTree.NoteActionFactory import de.sudoq.model.solvingAssistant.HintTypes import de.sudoq.model.sudoku.CandidateSet import de.sudoq.model.sudoku.CandidateSet.Companion.fromBitSet import de.sudoq.model.sudoku.Constraint import de.sudoq.model.sudoku.Sudoku import java.util.* class HiddenSetDerivation(technique: HintTypes) : SolveDerivation(technique) { var constraint: Constraint? = null //todo is it ever set? private val subsetMembers: MutableList<DerivationCell> = Stack() fun getSubsetMembers(): List<DerivationCell> { return subsetMembers } var subsetCandidates: CandidateSet? = null private set fun setSubsetCandidates(bs: BitSet) { subsetCandidates = bs.clone() as CandidateSet } init { hasActionListCapability = true } fun addSubsetCell(f: DerivationCell) { subsetMembers.add(f) } /* creates a list of actions in case the user want the app to execute the hints */ override fun getActionList(sudoku: Sudoku): List<Action> { val actionlist: MutableList<Action> = ArrayList() val af = NoteActionFactory() val it = cellIterator while (it.hasNext()) { val df = it.next() for (note in fromBitSet(df.irrelevantCandidates).setBits) actionlist.add(af.createAction(note, sudoku.getCell(df.position)!!)) } return actionlist } }
gpl-3.0
aabbcc7e018a13b533dbc41d294f5af0
27.481481
86
0.695511
4.293296
false
false
false
false
ice1000/PlasticApp
app/src/main/kotlin/core/Parser.kt
1
1599
package core import android.util.Log import data.BaseData import java.util.* /** * @author ice1000 * @version 0.3.2 * Created by ice1000 on 2016/7/12. */ object Parser { var source: List<String> = listOf() /** * @param source DSL source */ fun parse(source: List<String>, dataType: Int): ArrayList<BaseData> { this.source = source val index = ArrayList<BaseData>() var i = 0 while (i < this.source.size) { if (this.source[i].startsWith("def ")) { val definition = this.source[i].split(" ").toList().filter { it.length > 0 } this.source = this.source.map { it.replace( oldValue = "%" + definition[1] + "%", newValue = definition[2] ) } } if (this.source[i].startsWith("====")) { try { i++ index.add(BaseData( title = this.source[i], url = this.source[i + 1], type = dataType, description = this.source[i + 2] )) i += 3 continue } catch (e: IndexOutOfBoundsException) { Log.i("important", "parsing indexOutOfBound!!!") } Log.i("important", "parse finished") } // !!!VERY IMPORTANT!!! i++ } return index } }
apache-2.0
0bd12718d7c28f9bcc4d18c8f0fc593b
28.611111
92
0.417761
4.801802
false
false
false
false
Soya93/Extract-Refactoring
platform/script-debugger/protocol/protocol-reader/src/Util.kt
6
1205
package org.jetbrains.protocolReader import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.WildcardType val TYPE_FACTORY_NAME_PREFIX = 'F' val READER_NAME = "reader" val PENDING_INPUT_READER_NAME = "inputReader" val JSON_READER_CLASS_NAME = "JsonReaderEx" val JSON_READER_PARAMETER_DEF = "$READER_NAME: $JSON_READER_CLASS_NAME" /** * Generate Java type name of the passed type. Type may be parameterized. */ internal fun writeJavaTypeName(arg: Type, out: TextOutput) { if (arg is Class<*>) { val name = arg.canonicalName out.append(if (name == "java.util.List") "List" else name) } else if (arg is ParameterizedType) { writeJavaTypeName(arg.rawType, out) out.append('<') val params = arg.actualTypeArguments for (i in params.indices) { if (i != 0) { out.comma() } writeJavaTypeName(params[i], out) } out.append('>') } else if (arg is WildcardType) { val upperBounds = arg.upperBounds!! if (upperBounds.size != 1) { throw RuntimeException() } out.append("? extends ") writeJavaTypeName(upperBounds.first(), out) } else { out.append(arg.toString()) } }
apache-2.0
ad900081a5ebdd0e23a9ee659bf39d64
25.217391
73
0.66971
3.73065
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/ConfirmationDialog.kt
1
2135
package nerd.tuxmobil.fahrplan.congress.utils import android.content.Context import android.os.Bundle import androidx.annotation.CallSuper import androidx.annotation.MainThread import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.extensions.withArguments class ConfirmationDialog : DialogFragment() { interface OnConfirmationDialogClicked { fun onAccepted(requestCode: Int) } companion object { const val FRAGMENT_TAG = "ConfirmationDialog.FRAGMENT_TAG" private const val BUNDLE_DLG_TITLE = "ConfirmationDialog.DLG_TITLE" private const val BUNDLE_DLG_REQUEST_CODE = "ConfirmationDialog.DLG_REQUEST_CODE" fun newInstance(@StringRes title: Int, requestCode: Int) = ConfirmationDialog().withArguments( BUNDLE_DLG_TITLE to title, BUNDLE_DLG_REQUEST_CODE to requestCode ).apply { listener = null isCancelable = false } } private var title = 0 private var requestCode = 0 private var listener: OnConfirmationDialogClicked? = null @MainThread @CallSuper override fun onAttach(context: Context) { super.onAttach(context) if (context is OnConfirmationDialogClicked) { listener = context } } @MainThread override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val args = requireArguments() title = args.getInt(BUNDLE_DLG_TITLE) requestCode = args.getInt(BUNDLE_DLG_REQUEST_CODE) } @MainThread override fun onCreateDialog(savedInstanceState: Bundle?) = AlertDialog .Builder(requireContext()) .setTitle(title) .setPositiveButton(R.string.dlg_delete_all_favorites_delete_all) { _, _ -> listener?.onAccepted(requestCode) } .setNegativeButton(android.R.string.cancel) { _, _ -> // Do nothing. } .create() }
apache-2.0
b0361444729539932c96a9ab1e2b067e
31.348485
89
0.671194
4.97669
false
false
false
false
wordpress-mobile/AztecEditor-Android
aztec/src/main/kotlin/org/wordpress/aztec/toolbar/AztecToolbar.kt
1
54176
package org.wordpress.aztec.toolbar import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.os.Parcelable import android.util.AttributeSet import android.view.KeyEvent import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.accessibility.AccessibilityEvent import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.FrameLayout import android.widget.HorizontalScrollView import android.widget.LinearLayout import android.widget.PopupMenu import android.widget.PopupMenu.OnMenuItemClickListener import android.widget.Toast import android.widget.ToggleButton import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.core.text.TextUtilsCompat import androidx.core.view.ViewCompat import org.wordpress.android.util.AppLog import org.wordpress.aztec.AztecText import org.wordpress.aztec.AztecText.EditorHasChanges.NO_CHANGES import org.wordpress.aztec.AztecTextFormat import org.wordpress.aztec.ITextFormat import org.wordpress.aztec.R import org.wordpress.aztec.plugins.IMediaToolbarButton import org.wordpress.aztec.plugins.IToolbarButton import org.wordpress.aztec.source.SourceViewEditText import org.wordpress.aztec.util.convertToButtonAccessibilityProperties import org.wordpress.aztec.util.setBackgroundDrawableRes import java.util.ArrayList import java.util.Arrays import java.util.Locale /** * Aztec toolbar container. * Contains both Styling and Media toolbars. * Supports RTL layout direction on API 19+ */ class AztecToolbar : FrameLayout, IAztecToolbar, OnMenuItemClickListener { val RETAINED_EDITOR_HTML_PARSED_SHA256_KEY = "RETAINED_EDITOR_HTML_PARSED_SHA256_KEY" val RETAINED_SOURCE_HTML_PARSED_SHA256_KEY = "RETAINED_SOURCE_HTML_PARSED_SHA256_KEY" private var aztecToolbarListener: IAztecToolbarClickListener? = null private var editor: AztecText? = null private var headingMenu: PopupMenu? = null private var listMenu: PopupMenu? = null private var sourceEditor: SourceViewEditText? = null private var dialogShortcuts: AlertDialog? = null private var isAdvanced: Boolean = false private var hasCustomLayout: Boolean = false private var isMediaToolbarAvailable: Boolean = false private var isExpanded: Boolean = false private var isMediaToolbarVisible: Boolean = false private var isMediaModeEnabled: Boolean = false var editorContentParsedSHA256LastSwitch: ByteArray = ByteArray(0) var sourceContentParsedSHA256LastSwitch: ByteArray = ByteArray(0) private lateinit var toolbarScrolView: HorizontalScrollView private lateinit var buttonEllipsisCollapsed: RippleToggleButton private lateinit var buttonEllipsisExpanded: RippleToggleButton private lateinit var layoutExpandedTranslateInEnd: Animation private lateinit var layoutExpandedTranslateOutStart: Animation private val htmlButton: RippleToggleButton? by lazy { findViewById(R.id.format_bar_button_html) } private lateinit var buttonMediaCollapsed: RippleToggleButton private lateinit var buttonMediaExpanded: RippleToggleButton private lateinit var layoutMediaTranslateInEnd: Animation private lateinit var layoutMediaTranslateOutStart: Animation private lateinit var layoutMediaTranslateOutEnd: Animation private lateinit var layoutMediaTranslateInStart: Animation private lateinit var ellipsisSpinLeft: Animation private lateinit var ellipsisSpinRight: Animation private lateinit var mediaButtonSpinLeft: Animation private lateinit var mediaButtonSpinRight: Animation private lateinit var layoutExpanded: LinearLayout private lateinit var mediaToolbar: View private lateinit var stylingToolbar: View private var toolbarButtonPlugins: ArrayList<IToolbarButton> = ArrayList() private var toolbarItems: ToolbarItems? = null private var tasklistEnabled: Boolean = false constructor(context: Context) : super(context) { initView(null) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { initView(attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initView(attrs) } override fun setToolbarListener(listener: IAztecToolbarClickListener) { aztecToolbarListener = listener } override fun onKeyUp(keyCode: Int, keyEvent: KeyEvent): Boolean { when (keyCode) { KeyEvent.KEYCODE_1 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 1 = Alt + Ctrl + 1 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_1, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_1) return true } } KeyEvent.KEYCODE_2 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 2 = Alt + Ctrl + 2 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_2, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_2) return true } } KeyEvent.KEYCODE_3 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 3 = Alt + Ctrl + 3 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_3, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_3) return true } } KeyEvent.KEYCODE_4 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 4 = Alt + Ctrl + 4 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_4, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_4) return true } } KeyEvent.KEYCODE_5 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 5 = Alt + Ctrl + 5 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_5, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_5) return true } } KeyEvent.KEYCODE_6 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 6 = Alt + Ctrl + 6 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_6, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_6) return true } } KeyEvent.KEYCODE_7 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Heading 6 = Alt + Ctrl + 7 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_PARAGRAPH, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_PARAGRAPH) return true } } KeyEvent.KEYCODE_8 -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Preformat = Alt + Ctrl + 8 aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_PREFORMAT, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_PREFORMAT) return true } } KeyEvent.KEYCODE_B -> { if (keyEvent.isCtrlPressed) { // Bold = Ctrl + B aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_STRONG, true) findViewById<ToggleButton>(ToolbarAction.BOLD.buttonId).performClick() return true } } KeyEvent.KEYCODE_D -> { if (keyEvent.isCtrlPressed) { // Strikethrough = Ctrl + D aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_STRIKETHROUGH, true) findViewById<ToggleButton>(ToolbarAction.STRIKETHROUGH.buttonId).performClick() return true } } KeyEvent.KEYCODE_H -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Shortcuts = Alt + Ctrl + H showDialogShortcuts() return true } } KeyEvent.KEYCODE_I -> { if (keyEvent.isCtrlPressed) { // Italic = Ctrl + I aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_EMPHASIS, true) findViewById<ToggleButton>(ToolbarAction.ITALIC.buttonId).performClick() return true } } KeyEvent.KEYCODE_K -> { if (keyEvent.isCtrlPressed) { // Link = Ctrl + K aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_LINK, true) findViewById<ToggleButton>(ToolbarAction.LINK.buttonId).performClick() return true } } KeyEvent.KEYCODE_M -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Media = Alt + Ctrl + M if (aztecToolbarListener != null && aztecToolbarListener!!.onToolbarMediaButtonClicked()) { //event is consumed by listener } else { val mediaAction = if (isMediaToolbarVisible) ToolbarAction.ADD_MEDIA_EXPAND else ToolbarAction.ADD_MEDIA_COLLAPSE findViewById<ToggleButton>(mediaAction.buttonId).performClick() } return true } } KeyEvent.KEYCODE_O -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Ordered List = Alt + Ctrl + O aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_ORDERED_LIST, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_ORDERED_LIST) return true } } KeyEvent.KEYCODE_Q -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Quote = Alt + Ctrl + Q aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_QUOTE, true) findViewById<ToggleButton>(ToolbarAction.QUOTE.buttonId).performClick() return true } } KeyEvent.KEYCODE_U -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Unordered List = Alt + Ctrl + U aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_UNORDERED_LIST, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_UNORDERED_LIST) return true } else if (keyEvent.isCtrlPressed) { // Underline = Ctrl + U aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_UNDERLINE, true) findViewById<ToggleButton>(ToolbarAction.UNDERLINE.buttonId).performClick() return true } } KeyEvent.KEYCODE_T -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Task List = Alt + Ctrl + T aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_TASK_LIST, true) editor?.toggleFormatting(AztecTextFormat.FORMAT_TASK_LIST) return true } } KeyEvent.KEYCODE_X -> { if (keyEvent.isAltPressed && keyEvent.isCtrlPressed) { // Code = Alt + Ctrl + X // TODO: Add Code action. // findViewById<ToggleButton>(ToolbarAction.CODE.buttonId).performClick() return true } } KeyEvent.KEYCODE_Y -> { if (keyEvent.isCtrlPressed) { // Redo = Ctrl + Y editor?.redo() return true } } KeyEvent.KEYCODE_Z -> { if (keyEvent.isCtrlPressed) { // Undo = Ctrl + Z editor?.undo() return true } } else -> { toolbarButtonPlugins.forEach { if (it.matchesKeyShortcut(keyCode, keyEvent)) { aztecToolbarListener?.onToolbarFormatButtonClicked(it.action.textFormats.first(), true) it.toggle() return true } } } } return false } override fun onMenuItemClick(item: MenuItem?): Boolean { val checked = (item?.isChecked == false) item?.isChecked = checked val headingButton = findViewById<ToggleButton>(ToolbarAction.HEADING.buttonId) when (item?.itemId) { // Heading Menu R.id.paragraph -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_PARAGRAPH, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_PARAGRAPH) updateHeadingMenuItem(AztecTextFormat.FORMAT_PARAGRAPH, headingButton) return true } R.id.heading_1 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_1, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_1) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_1, headingButton) return true } R.id.heading_2 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_2, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_2) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_2, headingButton) return true } R.id.heading_3 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_3, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_3) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_3, headingButton) return true } R.id.heading_4 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_4, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_4) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_4, headingButton) return true } R.id.heading_5 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_5, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_5) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_5, headingButton) return true } R.id.heading_6 -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_HEADING_6, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_HEADING_6) updateHeadingMenuItem(AztecTextFormat.FORMAT_HEADING_6, headingButton) return true } // TODO: Uncomment when Preformat is to be added back as a feature // R.id.preformat -> { // aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_PREFORMAT, false) // editor?.toggleFormatting(AztecTextFormat.FORMAT_PREFORMAT) // return true // } // List Menu R.id.list_ordered -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_ORDERED_LIST, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_ORDERED_LIST) toggleListMenuSelection(item.itemId, checked) editor?.let { highlightAppliedStyles(editor!!.selectionStart, editor!!.selectionEnd) } return true } R.id.list_unordered -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_UNORDERED_LIST, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_UNORDERED_LIST) toggleListMenuSelection(item.itemId, checked) editor?.let { highlightAppliedStyles(editor!!.selectionStart, editor!!.selectionEnd) } return true } R.id.task_list -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_TASK_LIST, false) editor?.toggleFormatting(AztecTextFormat.FORMAT_TASK_LIST) toggleListMenuSelection(item.itemId, checked) editor?.let { highlightAppliedStyles(editor!!.selectionStart, editor!!.selectionEnd) } return true } else -> return false } } override fun onRestoreInstanceState(state: Parcelable?) { val savedState = state as SourceViewEditText.SavedState super.onRestoreInstanceState(savedState.superState) val restoredState = savedState.state toggleHtmlMode(restoredState.getBoolean("isSourceVisible")) enableMediaMode(restoredState.getBoolean("isMediaMode")) isExpanded = restoredState.getBoolean("isExpanded") isMediaToolbarVisible = restoredState.getBoolean("isMediaToolbarVisible") setAdvancedState() setupMediaToolbar() restoredState.getByteArray(RETAINED_EDITOR_HTML_PARSED_SHA256_KEY)?.let { editorContentParsedSHA256LastSwitch = it } restoredState.getByteArray(RETAINED_SOURCE_HTML_PARSED_SHA256_KEY)?.let { sourceContentParsedSHA256LastSwitch = it } } override fun onSaveInstanceState(): Parcelable? { val superState = super.onSaveInstanceState() val savedState = superState?.let { SourceViewEditText.SavedState(it) } val bundle = Bundle() bundle.putBoolean("isSourceVisible", sourceEditor?.visibility == View.VISIBLE) bundle.putBoolean("isMediaMode", isMediaModeEnabled) bundle.putBoolean("isExpanded", isExpanded) bundle.putBoolean("isMediaToolbarVisible", isMediaToolbarVisible) bundle.putByteArray(RETAINED_EDITOR_HTML_PARSED_SHA256_KEY, editorContentParsedSHA256LastSwitch) bundle.putByteArray(RETAINED_SOURCE_HTML_PARSED_SHA256_KEY, sourceContentParsedSHA256LastSwitch) savedState?.state = bundle return savedState } private fun isEditorAttached(): Boolean { return editor != null && editor is AztecText } override fun setEditor(editor: AztecText, sourceEditor: SourceViewEditText?) { this.sourceEditor = sourceEditor this.editor = editor // highlight toolbar buttons based on what styles are applied to the text beneath cursor this.editor!!.setOnSelectionChangedListener(object : AztecText.OnSelectionChangedListener { override fun onSelectionChanged(selStart: Int, selEnd: Int) { highlightAppliedStyles(selStart, selEnd) } }) setupToolbarItems() if (sourceEditor == null) { htmlButton?.visibility = View.GONE } else { htmlButton?.visibility = View.VISIBLE } } private fun initView(attrs: AttributeSet?) { val styles = context.obtainStyledAttributes(attrs, R.styleable.AztecToolbar, 0, R.style.AztecToolbarStyle) isAdvanced = styles.getBoolean(R.styleable.AztecToolbar_advanced, false) isMediaToolbarAvailable = styles.getBoolean(R.styleable.AztecToolbar_mediaToolbarAvailable, true) val toolbarBackgroundColor = styles.getColor( R.styleable.AztecToolbar_toolbarBackgroundColor, ContextCompat.getColor(context, R.color.format_bar_background) ) val toolbarBorderColor = styles.getColor(R.styleable.AztecToolbar_toolbarBorderColor, ContextCompat.getColor(context, R.color.format_bar_divider_horizontal)) val layout = when { styles.hasValue(R.styleable.AztecToolbar_customLayout) -> { hasCustomLayout = true styles.getResourceId(R.styleable.AztecToolbar_customLayout, 0) } isAdvanced -> R.layout.aztec_format_bar_advanced else -> R.layout.aztec_format_bar_basic } styles.recycle() View.inflate(context, layout, this) toolbarScrolView = findViewById(R.id.format_bar_button_scroll) setBackgroundColor(toolbarBackgroundColor) findViewById<View>(R.id.format_bar_horizontal_divider)?.setBackgroundColor(toolbarBorderColor) setAdvancedState() setupMediaToolbar() setupToolbarButtonsForAccessibility() } override fun addButton(buttonPlugin: IToolbarButton) { val pluginContainer = if (buttonPlugin is IMediaToolbarButton) { findViewById(R.id.media_toolbar) } else { findViewById<LinearLayout>(R.id.plugin_buttons) } buttonPlugin.inflateButton(pluginContainer) toolbarButtonPlugins.add(buttonPlugin) val button = findViewById<ToggleButton>(buttonPlugin.action.buttonId) button.setOnClickListener { buttonPlugin.toggle() } button.setBackgroundDrawableRes(buttonPlugin.action.buttonDrawableRes) setupMediaButtonForAccessibility(buttonPlugin) } private fun setupMediaButtonForAccessibility(buttonPlugin: IToolbarButton) { val button = findViewById<ToggleButton>(buttonPlugin.action.buttonId) if (buttonPlugin is IMediaToolbarButton) { button.convertToButtonAccessibilityProperties() } } private fun setupToolbarButtonsForAccessibility() { val targetActions = listOf(ToolbarAction.ADD_MEDIA_EXPAND, ToolbarAction.ADD_MEDIA_COLLAPSE, ToolbarAction.HORIZONTAL_RULE, ToolbarAction.HEADING, ToolbarAction.LIST, ToolbarAction.LINK ) ToolbarAction.values().forEach { action -> if (targetActions.contains(action)) { findViewById<ToggleButton>(action.buttonId)?.convertToButtonAccessibilityProperties() } } } fun highlightActionButtons(toolbarActions: List<IToolbarAction>) { ToolbarAction.values().forEach { action -> if (toolbarActions.contains(action)) { toggleButton(findViewById<ToggleButton>(action.buttonId), true) } else { toggleButton(findViewById<ToggleButton>(action.buttonId), false) } } } private fun getSelectedActions(): ArrayList<IToolbarAction> { val actions = ArrayList<IToolbarAction>() for (action in ToolbarAction.values()) { if (action != ToolbarAction.ELLIPSIS_COLLAPSE && action != ToolbarAction.ELLIPSIS_EXPAND) { val view = findViewById<ToggleButton>(action.buttonId) if (view?.isChecked == true) actions.add(action) } } return actions } private fun toggleButton(button: View?, checked: Boolean) { if (button != null && button is ToggleButton) { button.isChecked = checked } } private fun toggleButtonState(button: View?, enabled: Boolean) { if (button != null) { button.isEnabled = enabled } } private fun highlightAppliedStyles(selStart: Int, selEnd: Int) { if (!isEditorAttached()) return val appliedStyles = editor!!.getAppliedStyles(selStart, selEnd) highlightActionButtons(ToolbarAction.getToolbarActionsForStyles(appliedStyles)) selectHeadingMenuItem(appliedStyles) selectListMenuItem(appliedStyles) highlightAlignButtons(appliedStyles) setIndentState() } private fun setIndentState() { findViewById<View>(ToolbarAction.INDENT.buttonId)?.let { toggleButtonState(it, editor?.isIndentAvailable() == true) } findViewById<View>(ToolbarAction.OUTDENT.buttonId)?.let { toggleButtonState(it, editor?.isOutdentAvailable() == true) } } private fun highlightAlignButtons(appliedStyles: ArrayList<ITextFormat>) { if (!appliedStyles.contains(AztecTextFormat.FORMAT_ALIGN_LEFT)) { toggleButton(findViewById(ToolbarAction.ALIGN_LEFT.buttonId), false) } if (!appliedStyles.contains(AztecTextFormat.FORMAT_ALIGN_CENTER)) { toggleButton(findViewById(ToolbarAction.ALIGN_CENTER.buttonId), false) } if (!appliedStyles.contains(AztecTextFormat.FORMAT_ALIGN_RIGHT)) { toggleButton(findViewById(ToolbarAction.ALIGN_RIGHT.buttonId), false) } } private fun onToolbarAction(action: IToolbarAction) { if (!isEditorAttached()) return // if nothing is selected just mark the style as active if (!editor!!.isTextSelected() && action.isInlineAction()) { val toggledActionIsExclusive = action.actionType == ToolbarActionType.EXCLUSIVE_INLINE_STYLE val selectedActions = getSelectedActions() val actions = selectedActions.filter { val isExclusive = it.actionType == ToolbarActionType.EXCLUSIVE_INLINE_STYLE (it == action || !it.isInlineAction() || !toggledActionIsExclusive && !isExclusive) } if (selectedActions.size != actions.size) { highlightActionButtons(actions) } val textFormats = ArrayList<ITextFormat>() actions.filter { it.isStylingAction() } .forEach { textFormats.add(it.textFormats.first()) } if (getSelectedHeadingMenuItem() != null) { textFormats.add(getSelectedHeadingMenuItem()!!) } if (getSelectedListMenuItem() != null) { textFormats.add(getSelectedListMenuItem()!!) } aztecToolbarListener?.onToolbarFormatButtonClicked(action.textFormats.first(), false) return editor!!.setSelectedStyles(textFormats) } // if text is selected and action is styling - toggle the style if (action.isStylingAction() && action != ToolbarAction.HEADING && action != ToolbarAction.LIST) { aztecToolbarListener?.onToolbarFormatButtonClicked(action.textFormats.first(), false) val returnValue = editor!!.toggleFormatting(action.textFormats.first()) highlightAppliedStyles() return returnValue } // other toolbar action when (action) { ToolbarAction.ADD_MEDIA_COLLAPSE, ToolbarAction.ADD_MEDIA_EXPAND -> { if (aztecToolbarListener != null && aztecToolbarListener!!.onToolbarMediaButtonClicked()) { //event is consumed by listener } else { toggleMediaToolbar() } } ToolbarAction.HEADING -> { aztecToolbarListener?.onToolbarHeadingButtonClicked() headingMenu?.show() } ToolbarAction.LIST -> { aztecToolbarListener?.onToolbarListButtonClicked() listMenu?.show() } ToolbarAction.LINK -> { aztecToolbarListener?.onToolbarFormatButtonClicked(AztecTextFormat.FORMAT_LINK, false) editor!!.showLinkDialog() } ToolbarAction.HTML -> { aztecToolbarListener?.onToolbarHtmlButtonClicked() } ToolbarAction.ELLIPSIS_COLLAPSE -> { aztecToolbarListener?.onToolbarCollapseButtonClicked() animateToolbarCollapse() } ToolbarAction.ELLIPSIS_EXPAND -> { aztecToolbarListener?.onToolbarExpandButtonClicked() animateToolbarExpand() } ToolbarAction.INDENT -> { editor?.indent() setIndentState() } ToolbarAction.OUTDENT -> { editor?.outdent() setIndentState() } else -> { Toast.makeText(context, "Unsupported action", Toast.LENGTH_SHORT).show() } } } private fun highlightAppliedStyles() { editor?.let { highlightAppliedStyles(editor!!.selectionStart, editor!!.selectionEnd) } } private fun syncSourceFromEditor() { val editorHtml = editor!!.toPlainHtml(true) val sha256 = AztecText.calculateSHA256(editorHtml) if (editorContentParsedSHA256LastSwitch.isEmpty()) { // initialize the var if it's the first time we're about to use it editorContentParsedSHA256LastSwitch = sha256 } if (editor!!.hasChanges() != NO_CHANGES || !Arrays.equals(editorContentParsedSHA256LastSwitch, sha256)) { sourceEditor!!.displayStyledAndFormattedHtml(editorHtml) } editorContentParsedSHA256LastSwitch = sha256 } private fun syncEditorFromSource() { // temp var of the source html to load it to the editor if needed val sourceHtml = sourceEditor!!.getPureHtml(true) val sha256 = AztecText.calculateSHA256(sourceHtml) if (sourceContentParsedSHA256LastSwitch.isEmpty()) { // initialize the var if it's the first time we're about to use it sourceContentParsedSHA256LastSwitch = sha256 } if (sourceEditor!!.hasChanges() != NO_CHANGES || !Arrays.equals(sourceContentParsedSHA256LastSwitch, sha256)) { editor!!.fromHtml(sourceHtml) } sourceContentParsedSHA256LastSwitch = sha256 } override fun toggleEditorMode() { // only allow toggling if sourceEditor is present if (sourceEditor == null) return if (editor!!.visibility == View.VISIBLE) { syncSourceFromEditor() editor!!.visibility = View.GONE sourceEditor!!.visibility = View.VISIBLE toggleHtmlMode(true) } else { syncEditorFromSource() editor!!.visibility = View.VISIBLE sourceEditor!!.visibility = View.GONE toggleHtmlMode(false) } } fun getHeadingMenu(): PopupMenu? { return headingMenu } fun getListMenu(): PopupMenu? { return listMenu } fun getSelectedHeadingMenuItem(): ITextFormat? = when { headingMenu?.menu?.findItem(R.id.paragraph)?.isChecked == true -> AztecTextFormat.FORMAT_PARAGRAPH headingMenu?.menu?.findItem(R.id.heading_1)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_1 headingMenu?.menu?.findItem(R.id.heading_2)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_2 headingMenu?.menu?.findItem(R.id.heading_3)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_3 headingMenu?.menu?.findItem(R.id.heading_4)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_4 headingMenu?.menu?.findItem(R.id.heading_5)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_5 headingMenu?.menu?.findItem(R.id.heading_6)?.isChecked == true -> AztecTextFormat.FORMAT_HEADING_6 else -> null } fun getSelectedListMenuItem(): ITextFormat? { if (listMenu?.menu?.findItem(R.id.list_unordered)?.isChecked == true) return AztecTextFormat.FORMAT_UNORDERED_LIST else if (listMenu?.menu?.findItem(R.id.list_ordered)?.isChecked == true) return AztecTextFormat.FORMAT_ORDERED_LIST else if (listMenu?.menu?.findItem(R.id.task_list)?.isChecked == true) return AztecTextFormat.FORMAT_TASK_LIST return null } fun setExpanded(expanded: Boolean) { isExpanded = expanded setAdvancedState() } private fun animateToolbarCollapse() { buttonEllipsisCollapsed.startAnimation(ellipsisSpinLeft) isExpanded = false } private fun animateToolbarExpand() { buttonEllipsisExpanded.startAnimation(ellipsisSpinRight) isExpanded = true } /** * Call this method before Aztec is initialized to change the items visible in the Aztec toolbar */ fun setToolbarItems(toolbarItems: ToolbarItems) { this.toolbarItems = toolbarItems } /** * Call this method to enable a task list with checkboxes */ fun enableTaskList() { this.tasklistEnabled = true } private fun setupToolbarItems() { layoutExpanded = findViewById(R.id.format_bar_button_layout_expanded) val inflater = LayoutInflater.from(context) val order = toolbarItems ?: if (isAdvanced) { ToolbarItems.defaultAdvancedLayout } else { ToolbarItems.defaultBasicLayout } when (order) { is ToolbarItems.BasicLayout -> { order.addInto(layoutExpanded, inflater) } is ToolbarItems.AdvancedLayout -> { val layoutCollapsed = findViewById<LinearLayout>(R.id.format_bar_button_layout_collapsed) order.addInto(layoutExpanded, layoutCollapsed, inflater) } } for (toolbarAction in ToolbarAction.values()) { findViewById<ToggleButton>(toolbarAction.buttonId)?.let { it.setOnClickListener { onToolbarAction(toolbarAction) } when (toolbarAction) { ToolbarAction.HEADING -> setHeadingMenu(it) ToolbarAction.LIST -> setListMenu(it) else -> Unit // Do nothing } if (!hasCustomLayout) { it.setBackgroundDrawableRes(toolbarAction.buttonDrawableRes) } } } } private fun setAdvancedState() { if (isAdvanced) { setButtonViews() setAnimations() if (isExpanded) { showExpandedToolbar() } else { showCollapsedToolbar() } } } private fun selectHeadingMenuItem(textFormats: ArrayList<ITextFormat>) { val headingButton = findViewById<ToggleButton>(ToolbarAction.HEADING.buttonId) ?: return // Use unnumbered heading selector by default. updateHeadingMenuItem(AztecTextFormat.FORMAT_PARAGRAPH, headingButton) headingMenu?.menu?.findItem(R.id.paragraph)?.isChecked = true foreach@ for (it in textFormats) { when (it) { AztecTextFormat.FORMAT_HEADING_1 -> headingMenu?.menu?.findItem(R.id.heading_1)?.isChecked = true AztecTextFormat.FORMAT_HEADING_2 -> headingMenu?.menu?.findItem(R.id.heading_2)?.isChecked = true AztecTextFormat.FORMAT_HEADING_3 -> headingMenu?.menu?.findItem(R.id.heading_3)?.isChecked = true AztecTextFormat.FORMAT_HEADING_4 -> headingMenu?.menu?.findItem(R.id.heading_4)?.isChecked = true AztecTextFormat.FORMAT_HEADING_5 -> headingMenu?.menu?.findItem(R.id.heading_5)?.isChecked = true AztecTextFormat.FORMAT_HEADING_6 -> headingMenu?.menu?.findItem(R.id.heading_6)?.isChecked = true // TODO: Uncomment when Preformat is to be added back as a feature // AztecTextFormat.FORMAT_PREFORMAT -> headingMenu?.menu?.findItem(R.id.preformat)?.isChecked = true else -> continue@foreach } updateHeadingMenuItem(it, headingButton) } } private fun selectListMenuItem(textFormats: ArrayList<ITextFormat>) { val listButton = findViewById<ToggleButton>(ToolbarAction.LIST.buttonId) ?: return updateListMenuItem(AztecTextFormat.FORMAT_NONE, listButton) listMenu?.menu?.findItem(R.id.list_none)?.isChecked = true foreach@ for (it in textFormats) { when (it) { AztecTextFormat.FORMAT_UNORDERED_LIST -> listMenu?.menu?.findItem(R.id.list_unordered)?.isChecked = true AztecTextFormat.FORMAT_ORDERED_LIST -> listMenu?.menu?.findItem(R.id.list_ordered)?.isChecked = true AztecTextFormat.FORMAT_TASK_LIST -> listMenu?.menu?.findItem(R.id.task_list)?.isChecked = true else -> continue@foreach } updateListMenuItem(it, listButton) } } private fun setAnimations() { layoutExpandedTranslateInEnd = AnimationUtils.loadAnimation(context, R.anim.translate_in_end) layoutExpandedTranslateOutStart = AnimationUtils.loadAnimation(context, R.anim.translate_out_start) layoutExpandedTranslateOutStart.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { layoutExpanded.visibility = View.GONE } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { } } ) ellipsisSpinLeft = AnimationUtils.loadAnimation(context, R.anim.spin_left_90) ellipsisSpinLeft.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { buttonEllipsisCollapsed.visibility = View.GONE buttonEllipsisExpanded.visibility = View.VISIBLE } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { scrollToBeginingOfToolbar() layoutExpanded.startAnimation(layoutExpandedTranslateOutStart) } } ) ellipsisSpinRight = AnimationUtils.loadAnimation(context, R.anim.spin_right_90) ellipsisSpinRight.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { buttonEllipsisCollapsed.visibility = View.VISIBLE buttonEllipsisExpanded.visibility = View.GONE } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { layoutExpanded.visibility = View.VISIBLE //in rtl mode the scrollview will scroll to "end" when layoutExpanded becomes visible //keep hard focus on media button to avoid it toolbarScrolView.requestChildFocus(buttonMediaCollapsed, buttonMediaCollapsed) layoutExpanded.startAnimation(layoutExpandedTranslateInEnd) } } ) } //HorizontalScrollView does not support RTL layout direction on API <= 18, so we will always scroll to the left fun scrollToBeginingOfToolbar() { if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_LTR) { toolbarScrolView.fullScroll(View.FOCUS_LEFT) } else { toolbarScrolView.fullScroll(View.FOCUS_RIGHT) } } private fun setButtonViews() { layoutExpanded = findViewById(R.id.format_bar_button_layout_expanded) buttonEllipsisCollapsed = findViewById(R.id.format_bar_button_ellipsis_collapsed) buttonEllipsisExpanded = findViewById(R.id.format_bar_button_ellipsis_expanded) } private fun setupMediaToolbar() { if (!isMediaToolbarAvailable) return val mediaToolbarContainer: LinearLayout = findViewById(R.id.media_button_container) mediaToolbarContainer.visibility = if (isMediaToolbarAvailable) View.VISIBLE else View.GONE buttonMediaCollapsed = findViewById(R.id.format_bar_button_media_collapsed) mediaToolbar = findViewById(R.id.media_toolbar) stylingToolbar = findViewById(R.id.styling_toolbar) buttonMediaExpanded = findViewById(R.id.format_bar_button_media_expanded) if (isMediaToolbarVisible) { buttonMediaExpanded.visibility = View.VISIBLE buttonMediaCollapsed.visibility = View.GONE stylingToolbar.visibility = View.GONE mediaToolbar.visibility = View.VISIBLE } else { buttonMediaExpanded.visibility = View.GONE buttonMediaCollapsed.visibility = View.VISIBLE stylingToolbar.visibility = View.VISIBLE mediaToolbar.visibility = View.GONE } setupMediaToolbarAnimations() } private fun setupMediaToolbarAnimations() { if (!isMediaToolbarAvailable) return layoutMediaTranslateInEnd = AnimationUtils.loadAnimation(context, R.anim.translate_in_end) layoutMediaTranslateOutEnd = AnimationUtils.loadAnimation(context, R.anim.translate_out_end) layoutMediaTranslateOutEnd.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { stylingToolbar.visibility = View.GONE } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { } } ) layoutMediaTranslateInStart = AnimationUtils.loadAnimation(context, R.anim.translate_in_start) layoutMediaTranslateInStart.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { stylingToolbar.visibility = View.VISIBLE //in rtl mode the scrollview will scroll to "end" when stylingToolbar becomes visible //keep hard focus on media button to avoid it toolbarScrolView.requestChildFocus(buttonMediaCollapsed, buttonMediaCollapsed) } } ) layoutMediaTranslateOutStart = AnimationUtils.loadAnimation(context, R.anim.translate_out_start) layoutMediaTranslateOutStart.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { mediaToolbar.visibility = View.GONE } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { } } ) mediaButtonSpinRight = AnimationUtils.loadAnimation(context, R.anim.spin_right_45) mediaButtonSpinRight.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { buttonMediaCollapsed.visibility = View.GONE buttonMediaExpanded.visibility = View.VISIBLE buttonMediaExpanded.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED) buttonMediaExpanded.isChecked = true } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { scrollToBeginingOfToolbar() } } ) mediaButtonSpinLeft = AnimationUtils.loadAnimation(context, R.anim.spin_left_45) mediaButtonSpinLeft.setAnimationListener( object : Animation.AnimationListener { override fun onAnimationEnd(animation: Animation) { buttonMediaCollapsed.visibility = View.VISIBLE buttonMediaExpanded.visibility = View.GONE buttonMediaCollapsed.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED) buttonMediaCollapsed.isChecked = false } override fun onAnimationRepeat(animation: Animation) { } override fun onAnimationStart(animation: Animation) { } } ) } private fun setHeadingMenu(view: View?) { view ?: return headingMenu = PopupMenu(context, view) headingMenu?.setOnMenuItemClickListener(this) headingMenu?.inflate(R.menu.heading) headingMenu?.setOnDismissListener({ if (getSelectedHeadingMenuItem() == null || getSelectedHeadingMenuItem() == AztecTextFormat.FORMAT_PARAGRAPH) { findViewById<ToggleButton>(ToolbarAction.HEADING.buttonId).isChecked = false } else { findViewById<ToggleButton>(ToolbarAction.HEADING.buttonId).isChecked = true } }) } private fun setListMenu(view: View?) { view ?: return listMenu = PopupMenu(context, view) listMenu?.setOnMenuItemClickListener(this) listMenu?.inflate(R.menu.list) if (!tasklistEnabled) { listMenu?.menu?.findItem(R.id.task_list)?.setVisible(false) } listMenu?.setOnDismissListener { (getSelectedListMenuItem() != null).also { findViewById<ToggleButton>(ToolbarAction.LIST.buttonId).isChecked = it } } } private fun updateListMenuItem(textFormat: ITextFormat, listButton: ToggleButton?) { listButton ?: return var backgroundRes = R.drawable.format_bar_button_ul_selector var contentDescriptionRes = R.string.format_bar_description_list var check = true when (textFormat) { AztecTextFormat.FORMAT_ORDERED_LIST -> { backgroundRes = R.drawable.format_bar_button_ol_selector contentDescriptionRes = R.string.item_format_list_ordered } AztecTextFormat.FORMAT_UNORDERED_LIST -> { contentDescriptionRes = R.string.item_format_list_unordered // keep default background } AztecTextFormat.FORMAT_TASK_LIST -> { backgroundRes = R.drawable.format_bar_button_tasklist_selector contentDescriptionRes = R.string.item_format_task_list // keep default background } AztecTextFormat.FORMAT_NONE -> { check = false // keep default background and content description } else -> { AppLog.w(AppLog.T.EDITOR, "Unknown list menu item - text format") return } } listButton.setBackgroundDrawableRes(backgroundRes) listButton.contentDescription = context.getString(contentDescriptionRes) listButton.isChecked = check } private fun updateHeadingMenuItem(textFormat: ITextFormat, headingButton: ToggleButton?) { headingButton ?: return var backgroundRes = R.drawable.format_bar_button_heading_selector var contentDescriptionRes = R.string.format_bar_description_heading var check = true when (textFormat) { AztecTextFormat.FORMAT_HEADING_1 -> { backgroundRes = R.drawable.format_bar_button_heading_1_selector contentDescriptionRes = R.string.heading_1 } AztecTextFormat.FORMAT_HEADING_2 -> { backgroundRes = R.drawable.format_bar_button_heading_2_selector contentDescriptionRes = R.string.heading_2 } AztecTextFormat.FORMAT_HEADING_3 -> { backgroundRes = R.drawable.format_bar_button_heading_3_selector contentDescriptionRes = R.string.heading_3 } AztecTextFormat.FORMAT_HEADING_4 -> { backgroundRes = R.drawable.format_bar_button_heading_4_selector contentDescriptionRes = R.string.heading_4 } AztecTextFormat.FORMAT_HEADING_5 -> { backgroundRes = R.drawable.format_bar_button_heading_5_selector contentDescriptionRes = R.string.heading_5 } AztecTextFormat.FORMAT_HEADING_6 -> { backgroundRes = R.drawable.format_bar_button_heading_6_selector contentDescriptionRes = R.string.heading_6 } AztecTextFormat.FORMAT_PARAGRAPH -> { // keep default background and contentDescription check = false } else -> { AppLog.w(AppLog.T.EDITOR, "Unknown heading menu item - text format") return } } headingButton.setBackgroundDrawableRes(backgroundRes) headingButton.contentDescription = context.getString(contentDescriptionRes) headingButton.isChecked = check } private fun showCollapsedToolbar() { layoutExpanded.visibility = View.GONE buttonEllipsisCollapsed.visibility = View.GONE buttonEllipsisExpanded.visibility = View.VISIBLE } private fun showExpandedToolbar() { layoutExpanded.visibility = View.VISIBLE buttonEllipsisCollapsed.visibility = View.VISIBLE buttonEllipsisExpanded.visibility = View.GONE } private fun toggleHtmlMode(isHtmlMode: Boolean) { ToolbarAction.values().forEach { action -> if (action == ToolbarAction.HTML) { toggleButton(findViewById(action.buttonId), isHtmlMode) } else { toggleButtonState(findViewById(action.buttonId), !isHtmlMode) } } toolbarButtonPlugins.forEach { toggleButtonState(findViewById(it.action.buttonId), !isHtmlMode) } } private fun toggleListMenuSelection(listMenuItemId: Int, isChecked: Boolean) { val listButton = findViewById<ToggleButton>(ToolbarAction.LIST.buttonId) if (isChecked) { listMenu?.menu?.findItem(listMenuItemId)?.isChecked = true when (listMenuItemId) { R.id.list_ordered -> updateListMenuItem(AztecTextFormat.FORMAT_ORDERED_LIST, listButton) R.id.list_unordered -> updateListMenuItem(AztecTextFormat.FORMAT_UNORDERED_LIST, listButton) R.id.task_list -> updateListMenuItem(AztecTextFormat.FORMAT_TASK_LIST, listButton) else -> { AppLog.w(AppLog.T.EDITOR, "Unknown list menu item") updateListMenuItem(AztecTextFormat.FORMAT_UNORDERED_LIST, listButton) // Use unordered list selector by default. } } } else { listMenu?.menu?.findItem(R.id.list_none)?.isChecked = true updateListMenuItem(AztecTextFormat.FORMAT_NONE, listButton) } } fun enableFormatButtons(isEnabled: Boolean) { ToolbarAction.values().forEach { action -> if (action != ToolbarAction.HTML) { toggleButtonState(findViewById(action.buttonId), isEnabled) } } toolbarButtonPlugins.forEach { toggleButtonState(findViewById(it.action.buttonId), isEnabled) } } fun isMediaModeEnabled(): Boolean { return isMediaModeEnabled } fun enableMediaMode(isEnabled: Boolean) { isMediaModeEnabled = isEnabled toolbarButtonPlugins.forEach { button -> if (button !is IMediaToolbarButton) button.toolbarStateAboutToChange(this, !isEnabled) } } @SuppressLint("InflateParams") private fun showDialogShortcuts() { val layout = LayoutInflater.from(context).inflate(R.layout.dialog_shortcuts, null) val builder = AlertDialog.Builder(context) builder.setView(layout) dialogShortcuts = builder.create() dialogShortcuts!!.show() } fun hideMediaToolbar() { if (!isMediaToolbarVisible) return buttonMediaExpanded.startAnimation(mediaButtonSpinLeft) stylingToolbar.startAnimation(layoutMediaTranslateInStart) mediaToolbar.startAnimation(layoutMediaTranslateOutStart) isMediaToolbarVisible = false } fun showMediaToolbar() { if (isMediaToolbarVisible) return buttonMediaCollapsed.startAnimation(mediaButtonSpinRight) stylingToolbar.startAnimation(layoutMediaTranslateOutEnd) mediaToolbar.visibility = View.VISIBLE mediaToolbar.startAnimation(layoutMediaTranslateInEnd) isMediaToolbarVisible = true } override fun toggleMediaToolbar() { if (isMediaToolbarVisible) { hideMediaToolbar() } else { showMediaToolbar() } } }
mpl-2.0
b69dc6aea0fcf1c148f6a4deb00efa74
42.237031
137
0.623634
5.754222
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/login/LoginPresenter.kt
2
2422
package ru.fantlab.android.ui.modules.login import com.github.kittinunf.fuel.core.FuelError import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers import ru.fantlab.android.App import ru.fantlab.android.data.dao.model.Login import ru.fantlab.android.data.dao.model.User import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class LoginPresenter : BasePresenter<LoginMvp.View>(), LoginMvp.Presenter { override fun proceedWithoutLogin() { PrefGetter.setProceedWithoutLogin(true) sendToView { it.onSuccessfullyLoggedIn() } } override fun login(username: String, password: String) { val usernameIsEmpty = InputHelper.isEmpty(username) val passwordIsEmpty = InputHelper.isEmpty(password) sendToView { it.onEmptyUserName(usernameIsEmpty) } sendToView { it.onEmptyPassword(passwordIsEmpty) } if (!usernameIsEmpty && !passwordIsEmpty) { manageDisposable( DataManager.login(username, password).toObservable() .subscribe({ response -> onLoginResponse(response.login) }) { throwable -> if (throwable is FuelError) when (throwable.response.statusCode) { 401 -> sendToView { it.onWrongPassword() } 404 -> sendToView { it.onWrongUsername() } 500 -> sendToView { it.showSignInFailed() } } else sendToView { it.showSignInFailed() } } ) } } private fun onLoginResponse(login: Login) { PrefGetter.setToken(login.token) PrefGetter.setRefreshToken(login.refreshToken) makeRestCall( DataManager.getUser(login.userId.toInt()).toObservable(), Consumer { onUserResponse(it.user) } ) } private fun onUserResponse(user: User) { if (user.blocked == 1) { if (user.blockEndDate != null) { sendToView { it.showUserBlocked(user.blockEndDate) } } else { sendToView { it.showUserBlockedForever() } } } else { manageDisposable( Single.fromCallable { PrefGetter.setLoggedUser(user) PrefGetter.setProceedWithoutLogin(false) App.instance.initFuel() }.doOnSuccess { _ -> sendToView { it.onSuccessfullyLoggedIn() } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe() ) } } }
gpl-3.0
f7842119e41584ff18430d6c6df4c45f
33.126761
81
0.73204
3.832278
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/award/overview/AwardOverviewFragment.kt
2
4235
package ru.fantlab.android.ui.modules.award.overview import android.content.Context import android.os.Bundle import android.view.View import androidx.annotation.StringRes import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import kotlinx.android.synthetic.main.award_overview_layout.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.Award import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.provider.glide.GlideApp import ru.fantlab.android.provider.scheme.LinkParserHelper import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.award.AwardPagerMvp class AwardOverviewFragment : BaseFragment<AwardOverviewMvp.View, AwardOverviewPresenter>(), AwardOverviewMvp.View { private var pagerCallback: AwardPagerMvp.View? = null override fun fragmentLayout() = R.layout.award_overview_layout override fun providePresenter() = AwardOverviewPresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { stateLayout.hideReload() presenter.onFragmentCreated(arguments!!) } override fun onInitViews(award: Award) { hideProgress() if (award.isOpened == 0) { showErrorMessage(getString(R.string.award_not_opened)) activity?.finish() return } val awardLabel = if (!award.rusname.isEmpty()) { if (!award.name.isEmpty()) { String.format("%s / %s", award.rusname, award.name) } else { award.rusname } } else { award.name } pagerCallback?.onSetTitle(awardLabel) coverLayouts.setUrl("https://${LinkParserHelper.HOST_DATA}/images/awards/${award.awardId}") if (!InputHelper.isEmpty(award.countryName)) { awardCountryText.text = award.countryName awardCountryInfoBlock.visibility = View.VISIBLE } else awardCountryInfoBlock.visibility = View.GONE if (!InputHelper.isEmpty(award.minDate)) { awardDate.text = award.minDate.split("-")[0] + " г." awardDateBlock.visibility = View.VISIBLE } else awardDateBlock.visibility = View.GONE if (!InputHelper.isEmpty(award.homepage)) { awardSite.html = award.homepage authorSiteBlock.visibility = View.VISIBLE } else authorSiteBlock.visibility = View.GONE if (award.rusname.isBlank()) { awardName.text = award.name awardNameOrig.visibility = View.GONE } else { awardName.text = award.rusname if (award.name.isBlank()) { awardNameOrig.visibility = View.GONE } else awardNameOrig.text = award.name } if (!InputHelper.isEmpty(award.description)) { awardDescriptionText.html = award.description awardDescriptionBlock.visibility = View.VISIBLE } else awardDescriptionBlock.visibility = View.GONE if (!InputHelper.isEmpty(award.comment)) { commentsText.html = award.comment commentsBLock.visibility = View.VISIBLE } else commentsBLock.visibility = View.GONE if (!InputHelper.isEmpty(award.notes)) { notesText.html = award.notes notesBLock.visibility = View.VISIBLE } else notesBLock.visibility = View.GONE } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { progress.visibility = View.VISIBLE } override fun hideProgress() { progress.visibility = View.GONE } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun onShowErrorView(msgRes: String?) { parentView.visibility = View.GONE stateLayout.setEmptyText(R.string.network_error) stateLayout.showErrorState() } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } override fun onAttach(context: Context) { super.onAttach(context) if (context is AwardPagerMvp.View) { pagerCallback = context } } override fun onDetach() { pagerCallback = null super.onDetach() } override fun onSetTitle(title: String) { pagerCallback?.onSetTitle(title) } companion object { fun newInstance(awardId: Int): AwardOverviewFragment { val view = AwardOverviewFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, awardId).end() return view } } }
gpl-3.0
90ce7400a582cb0e7784f2c010bcde92
27.614865
93
0.754369
3.727113
false
false
false
false
yichiuan/Moedict-Android
moedict-android/app/src/main/java/com/yichiuan/moedict/data/MoeRepository.kt
1
2668
package com.yichiuan.moedict.data import android.content.Context import android.support.annotation.VisibleForTesting import io.reactivex.Completable import moe.Dictionary import moe.Index import moe.Word import java.io.InputStream import java.nio.ByteBuffer import java.util.* class MoeRepository internal constructor(private val context: Context) { companion object { private const val MOD_MASK = 0x3FF // 0b1111111111 private const val BUFFER_SIZE = (1024.0 * 1024.0 * 1.2).toInt() // 1.2 MB private const val MOE_INDEX_DATAPATH = "moe/index.bin" } private val appendable = StringBuilder() private val formatter = Formatter(appendable) private var dictBuffer: ByteArray? = null private var index: Index? = null fun getMoeWord(word: String): Word? { val firstWord = word.codePointAt(0) val mod = firstWord and MOD_MASK // code point % 1024 appendable.setLength(0) val dataPath = formatter.format("moe/%d.bin", mod).toString() val dict = Dictionary.getRootAsDictionary(loadDictData(dataPath)) return dict.wordsByKey(word) } @VisibleForTesting internal fun getMoeDictionary(mod: Int): Dictionary { appendable.setLength(0) val dataPath = formatter.format("moe/%d.bin", mod).toString() return Dictionary.getRootAsDictionary(loadDictData(dataPath)) } fun loadIndexData(): Completable { return Completable.fromAction { if (index == null) { index = Index.getRootAsIndex(loadData(MOE_INDEX_DATAPATH, null)) } } } private fun loadDictData(dataPath: String): ByteBuffer? { if (dictBuffer == null) { dictBuffer = ByteArray(BUFFER_SIZE) } return loadData(dataPath, dictBuffer) } private fun loadData(dataPath: String, buffer: ByteArray?): ByteBuffer? { var byteBuffer: ByteBuffer? = null context.assets.open(dataPath).use { byteBuffer = loadData(it, buffer) } return byteBuffer } private fun loadData(inputStream: InputStream, buffer: ByteArray?): ByteBuffer { var readBuffer = buffer val size = inputStream.available() if (readBuffer == null || readBuffer.size < size) { readBuffer = ByteArray(size) } val readSize = inputStream.read(readBuffer, 0, size) return ByteBuffer.wrap(readBuffer, 0, readSize) } fun search(query: String): ArrayList<Int> { return index!!.search(query) } fun getWord(position: Int): String? { return index!!.words(position) } }
apache-2.0
2244963479c5451e9fab291e828da0f6
26.802083
84
0.648801
4.331169
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/max_height/AddMaxHeightForm.kt
1
7259
package de.westnordost.streetcomplete.quests.max_height import android.os.Bundle import androidx.appcompat.app.AlertDialog import android.text.InputFilter import android.text.method.DigitsKeyListener import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.OtherAnswer import de.westnordost.streetcomplete.util.TextChangedWatcher import de.westnordost.streetcomplete.quests.max_height.Measurement.* private enum class Measurement { METRIC, IMPERIAL } class AddMaxHeightForm : AbstractQuestFormAnswerFragment<MaxHeightAnswer>() { override val otherAnswers = listOf( OtherAnswer(R.string.quest_maxheight_answer_noSign) { confirmNoSign() } ) private var meterInput: EditText? = null private var feetInput: EditText? = null private var inchInput: EditText? = null private var heightUnitSelect: Spinner? = null private var meterInputSign: View? = null private var feetInputSign: View? = null override fun isFormComplete() = getHeightFromInput() != null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) val unit = if (countryInfo.measurementSystem[0] == "metric") METRIC else IMPERIAL setMaxHeightSignLayout(R.layout.quest_maxheight, unit) return view } private fun setMaxHeightSignLayout(resourceId: Int, unit: Measurement) { val contentView = setContentView(resourceId) meterInput = contentView.findViewById(R.id.meterInput) feetInput = contentView.findViewById(R.id.feetInput) inchInput = contentView.findViewById(R.id.inchInput) val onTextChangedListener = TextChangedWatcher { checkIsFormComplete() } meterInput?.addTextChangedListener(onTextChangedListener) feetInput?.addTextChangedListener(onTextChangedListener) inchInput?.addTextChangedListener(onTextChangedListener) meterInputSign = contentView.findViewById(R.id.meterInputSign) feetInputSign = contentView.findViewById(R.id.feetInputSign) heightUnitSelect = contentView.findViewById(R.id.heightUnitSelect) val measurementUnits = countryInfo.measurementSystem heightUnitSelect?.visibility = if (measurementUnits.size == 1) View.GONE else View.VISIBLE heightUnitSelect?.adapter = ArrayAdapter(context!!, R.layout.spinner_item_centered, getSpinnerItems(measurementUnits)) heightUnitSelect?.setSelection(0) heightUnitSelect?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parentView: AdapterView<*>, selectedItemView: View, position: Int, id: Long) { val heightUnit = if (heightUnitSelect?.selectedItem == "m") METRIC else IMPERIAL switchLayout(heightUnit) } override fun onNothingSelected(parentView: AdapterView<*>) {} } inchInput?.filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend -> val destStr = dest.toString() val input = destStr.substring(0, dstart) + source.toString() + destStr.substring(dend, destStr.length) if(input.isEmpty() || input.toIntOrNull() != null && input.toInt() <= 12) { null } else { "" } }) /* Workaround for an Android bug that it assumes the decimal separator to always be the "." for EditTexts with inputType "numberDecimal", independent of Locale. See https://issuetracker.google.com/issues/36907764 . Affected Android versions are all versions till (exclusive) Android Oreo. */ /* actually, let's not care about which separator the user uses, he might be confused whether he should use the one as displayed on the sign or in his phone's locale */ //char separator = DecimalFormatSymbols.getInstance(getCountryInfo().getLocale()).getDecimalSeparator(); meterInput?.keyListener = DigitsKeyListener.getInstance("0123456789,.") switchLayout(unit) } private fun switchLayout(unit: Measurement) { val isMetric = unit == METRIC val isImperial = unit == IMPERIAL meterInputSign?.visibility = if (isMetric) View.VISIBLE else View.GONE feetInputSign?.visibility = if (isImperial) View.VISIBLE else View.GONE if (isMetric) meterInput?.requestFocus() if (isImperial) feetInput?.requestFocus() } private fun getSpinnerItems(units: List<String>) = units.mapNotNull { when(it) { "metric" -> "m" "imperial" -> "ft" else -> null } } private fun confirmNoSign() { activity?.let { AlertDialog.Builder(it) .setMessage(R.string.quest_maxheight_answer_noSign_question) .setPositiveButton(R.string.quest_generic_hasFeature_yes) { _, _ -> applyAnswer(NoMaxHeightSign(true)) } .setNegativeButton(R.string.quest_generic_hasFeature_no) { _, _ -> applyAnswer(NoMaxHeightSign(false)) } .show() } } override fun onClickOk() { if (userSelectedUnrealisticHeight()) { confirmUnusualInput { applyMaxHeightFormAnswer() } } else { applyMaxHeightFormAnswer() } } private fun userSelectedUnrealisticHeight(): Boolean { val height = getHeightFromInput() ?: return false val m = height.toMeters() return m > 6 || m < 1.9 } private fun applyMaxHeightFormAnswer() { applyAnswer(MaxHeight(getHeightFromInput()!!)) } private fun getHeightFromInput(): Measure? { if (isMetric()) { val input = meterInput?.text?.toString().orEmpty().trim().replace(",", ".") if (input.isNotEmpty()) return MetricMeasure(input.toDouble()) } else { val feetString = feetInput?.text?.toString().orEmpty().trim() val inchString = inchInput?.text?.toString().orEmpty().trim() if (feetString.isNotEmpty() && inchString.isNotEmpty()) { return ImperialMeasure(feetString.toInt(), inchString.toInt()) } } return null } private fun isMetric() = heightUnitSelect?.let { it.selectedItem == "m" } ?: (countryInfo.measurementSystem[0] == "metric") private fun confirmUnusualInput(callback: () -> (Unit)) { activity?.let { AlertDialog.Builder(it) .setTitle(R.string.quest_generic_confirmation_title) .setMessage(R.string.quest_maxheight_unusualInput_confirmation_description) .setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> callback() } .setNegativeButton(R.string.quest_generic_confirmation_no, null) .show() } } }
gpl-3.0
3fc2ea061bff1f52610ee504e1904da6
40.011299
126
0.671993
4.87836
false
false
false
false
docker-client/docker-compose-v3
src/main/kotlin/de/gesellix/docker/compose/interpolation/Template.kt
1
3187
package de.gesellix.docker.compose.interpolation import com.google.re2j.Pattern class Template { private val delimiter = "\\$" private val substitution = "[_a-z][_a-z0-9]*(?::?-[^}]+)?" private val patternString = "$delimiter(?i:(?P<escaped>$delimiter)|(?P<named>$substitution)|{(?P<braced>$substitution)}|(?P<invalid>))" private val pattern: Pattern = Pattern.compile(patternString) fun substitute(input: String, environment: Map<String, String>): String { val result = StringBuffer() val m = pattern.matcher(input) while (m.find()) { var substitution: String? = null if (m.group(2) != null) { // named substitution = m.group(2) } else if (m.group(3) != null) { // braced substitution = m.group(3) } if (substitution != null) { // Soft default (fall back if unset or empty) if (substitution.contains(":-")) { val (name, defaultValue) = partition(substitution, Regex(":-")) val (value, ok) = lookupEnv(name, environment) if (ok && value != "") { m.appendReplacement(result, value as String) } else { m.appendReplacement(result, defaultValue) } continue } // Hard default (fall back if-and-only-if empty) if (substitution.contains("-")) { val (name, defaultValue) = partition(substitution, Regex("-")) val (value, ok) = lookupEnv(name, environment) if (ok) { m.appendReplacement(result, value as String) } else { m.appendReplacement(result, defaultValue) } continue } // No default (fall back to empty string) val (value, ok) = lookupEnv(substitution, environment) if (ok) { m.appendReplacement(result, value as String) } else { m.appendReplacement(result, "") } continue } if (m.group(1) != null) { // escaped m.appendReplacement(result, m.group(1)) continue } // invalid throw IllegalStateException("Invalid template: $input") } m.appendTail(result) return result.toString() } data class Partitions(val left: String, val right: String) private fun partition(s: String, sep: Regex): Partitions { if (s.contains(sep)) { val parts = s.split(sep, 2) return Partitions(parts[0], parts[1]) } return Partitions(s, "") } data class Result(val result: String?, val found: Boolean) private fun lookupEnv(name: String, environment: Map<String, String>): Result { return Result(environment[name], environment.containsKey(name)) } }
mit
d1cf66a8413a853a0eb55ccd5423a98a
34.808989
139
0.497019
4.814199
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/analytic/AnalyticContentProvider.kt
2
3619
package org.stepik.android.view.analytic import android.content.ContentProvider import android.content.ContentValues import android.database.Cursor import android.net.Uri import android.os.Bundle import io.reactivex.BackpressureStrategy import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.PublishSubject import org.stepic.droid.base.App import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepik.android.domain.analytic.interactor.AnalyticInteractor import org.stepik.android.view.injection.analytic.AnalyticComponent import java.util.concurrent.TimeUnit import javax.inject.Inject class AnalyticContentProvider : ContentProvider() { companion object { private const val FLUSH_INTERVAL = 30L const val FLUSH = "flush" const val LOG = "log" } private lateinit var component: AnalyticComponent private val compositeDisposable = CompositeDisposable() private val analyticsSubject = PublishSubject.create<Unit>() @Inject @BackgroundScheduler lateinit var backgroundScheduler: Scheduler @Inject lateinit var analyticInteractor: AnalyticInteractor override fun insert(uri: Uri, values: ContentValues?): Uri? { throw UnsupportedOperationException() } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { throw UnsupportedOperationException() } override fun onCreate(): Boolean = true private fun injectComponent() { if (context == null) return component = App.component() .analyticProviderComponentBuilder() .build() component.inject(this) subscribeForFlushUpdates() } private fun subscribeForFlushUpdates() { val timerSource = Observable .interval(FLUSH_INTERVAL, TimeUnit.SECONDS) .map { Unit } compositeDisposable += Observable .merge(timerSource, analyticsSubject) .toFlowable(BackpressureStrategy.LATEST) .concatMapCompletable { analyticInteractor.flushEvents() } .subscribeOn(backgroundScheduler) .subscribeBy( onError = { subscribeForFlushUpdates() } ) } override fun call(method: String, arg: String?, extras: Bundle?): Bundle? { if (!::component.isInitialized) { injectComponent() } when (method) { LOG -> logEvent(arg, extras) FLUSH -> flushEvents() } return super.call(method, arg, extras) } private fun logEvent(eventName: String?, bundle: Bundle?) { if (eventName == null || bundle == null) return compositeDisposable += analyticInteractor .logEvent(eventName, bundle) .subscribeOn(backgroundScheduler) .subscribe() } private fun flushEvents() { analyticsSubject.onNext(Unit) } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException() } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { throw UnsupportedOperationException() } override fun getType(uri: Uri): String? { throw UnsupportedOperationException() } }
apache-2.0
f9f9661d0e8271aecade8833db8a0f58
29.677966
142
0.673114
5.229769
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/persistence/model/StorageLocation.kt
2
1674
package org.stepic.droid.persistence.model import android.os.Parcel import android.os.Parcelable import java.io.File class StorageLocation( val path: File, val freeSpaceBytes: Long = path.freeSpace, val totalSpaceBytes: Long = path.totalSpace, val type: Type ) : Parcelable { enum class Type { APP_INTERNAL, // app's internal dir Context::getFilesDir, for this dir type relative paths should be used PRIMARY, // default external dir SECONDARY // additional external dirs } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as StorageLocation if (type == Type.APP_INTERNAL && other == Type.APP_INTERNAL) return true if (path.canonicalPath != other.path.canonicalPath) return false return true } override fun hashCode(): Int = path.canonicalPath.hashCode() override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeSerializable(path) parcel.writeLong(freeSpaceBytes) parcel.writeLong(totalSpaceBytes) parcel.writeInt(type.ordinal) } override fun describeContents(): Int = 0 companion object CREATOR : Parcelable.Creator<StorageLocation> { override fun createFromParcel(parcel: Parcel): StorageLocation = StorageLocation( parcel.readSerializable() as File, parcel.readLong(), parcel.readLong(), Type.values()[parcel.readInt()] ) override fun newArray(size: Int): Array<StorageLocation?> = arrayOfNulls(size) } }
apache-2.0
be5eb1c7dd08d8d17bcb717e2a418976
30.603774
113
0.653524
4.866279
false
false
false
false
PlateStack/PlateAPI
src/main/kotlin/org/platestack/api/message/Message.kt
1
4005
/* * Copyright (C) 2017 José Roberto de Araújo Júnior * * 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.platestack.api.message import org.platestack.api.structure.remap import org.platestack.structure.immutable.ImmutableMap import org.platestack.structure.immutable.immutableMapOf import org.platestack.structure.immutable.toImmutableHashMap import java.io.Serializable import java.math.BigDecimal import java.math.BigInteger data class Message(val sentence: Sentence, val parameterValues: ImmutableMap<String, ParameterValue>): Serializable { constructor(sentence: Sentence, parameters: Map<String, Serializable>) : this(sentence, parameters.mapValues { ParameterValue.create(it.value) }.toImmutableHashMap()) constructor(rawText: String): this(Sentence(rawText), immutableMapOf()) val parameters: Map<String, Serializable> = parameterValues.remap { it.value.value } fun copy(sentence: Sentence = this.sentence, parameters: Map<String, Serializable> = this.parameters) = Message(sentence, parameters) sealed class ParameterValue: Serializable { companion object { @JvmStatic fun create(obj: Serializable) = when(obj) { // Common is ParameterValue -> obj is Message -> MessageValue(obj) is Text -> TextValue(obj) is Int -> IntValue(obj) is Long -> LongValue(obj) is Float -> FloatValue(obj) is Double -> DoubleValue(obj) // Not Common is ChatColor -> ChatColorValue(obj) is ChatFormat -> ChatFormatValue(obj) is Style -> StyleValue(obj) is Byte -> ByteValue(obj) is Short -> ShortValue(obj) is Char -> CharValue(obj) is BigDecimal -> BigDecimalValue(obj) is BigInteger -> BigIntegerValue(obj) else -> TODO("Unable to store $obj as a parameter value") } } abstract val value: Serializable class BigDecimalValue(override val value: BigDecimal): ParameterValue() class BigIntegerValue(override val value: BigInteger): ParameterValue() class MessageValue(override val value: Message): ParameterValue() class TextValue(override val value: Text): ParameterValue() class ChatColorValue(override val value: ChatColor): ParameterValue() class ChatFormatValue(override val value: ChatFormat): ParameterValue() class StyleValue(override val value: Style): ParameterValue() class ByteValue(val byte: Byte): ParameterValue() { override val value: Byte get() = byte } class ShortValue(val short: Short): ParameterValue() { override val value: Short get() = short } class CharValue(val char: Char): ParameterValue() { override val value: Char get() = char } class IntValue(val int: Int): ParameterValue() { override val value: Int get() = int } class LongValue(val long: Long): ParameterValue() { override val value: Long get() = long } class FloatValue(val float: Float): ParameterValue() { override val value: Float get() = float } class DoubleValue(val double: Double): ParameterValue() { override val value: Double get() = double } } }
apache-2.0
f1c9bf9a69700ff34c5029fbbc75718d
39.02
137
0.644928
4.827503
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/util/RxUtil.kt
1
2099
package exh.util import com.pushtorefresh.storio.operations.PreparedOperation import com.pushtorefresh.storio.sqlite.operations.get.PreparedGetObject import kotlinx.coroutines.suspendCancellableCoroutine import rx.* import rx.subjects.ReplaySubject import kotlin.coroutines.resumeWithException /** * Transform a cold single to a hot single * * Note: Behaves like a ReplaySubject * All generated items are buffered in memory! */ fun <T> Single<T>.melt(): Single<T> { return toObservable().melt().toSingle() } /** * Transform a cold observable to a hot observable * * Note: Behaves like a ReplaySubject * All generated items are buffered in memory! */ fun <T> Observable<T>.melt(): Observable<T> { val rs = ReplaySubject.create<T>() subscribe(rs) return rs } suspend fun <T> Single<T>.await(subscribeOn: Scheduler? = null): T { return suspendCancellableCoroutine { continuation -> val self = if (subscribeOn != null) subscribeOn(subscribeOn) else this lateinit var sub: Subscription sub = self.subscribe({ continuation.resume(it) { sub.unsubscribe() } }, { if (!continuation.isCancelled) continuation.resumeWithException(it) }) continuation.invokeOnCancellation { sub.unsubscribe() } } } suspend fun <T> PreparedOperation<T>.await(): T = asRxSingle().await() suspend fun <T> PreparedGetObject<T>.await(): T? = asRxSingle().await() suspend fun Completable.awaitSuspending(subscribeOn: Scheduler? = null) { return suspendCancellableCoroutine { continuation -> val self = if (subscribeOn != null) subscribeOn(subscribeOn) else this lateinit var sub: Subscription sub = self.subscribe({ continuation.resume(Unit) { sub.unsubscribe() } }, { if (!continuation.isCancelled) continuation.resumeWithException(it) }) continuation.invokeOnCancellation { sub.unsubscribe() } } }
apache-2.0
b98d08a8408a304267ec974aaf39a5c6
28.56338
78
0.646498
4.643805
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt
1
2825
package info.nightscout.androidaps.plugins.general.overview.notifications import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject @Suppress("SpellCheckingInspection") class NotificationWithAction constructor( injector: HasAndroidInjector ) : Notification() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var nsClientPlugin: NSClientPlugin init { injector.androidInjector().inject(this) } constructor(injector: HasAndroidInjector, id: Int, text: String, level: Int) : this(injector) { this.id = id date = System.currentTimeMillis() this.text = text this.level = level } constructor (injector: HasAndroidInjector, nsAlarm: NSAlarm) : this(injector) { date = System.currentTimeMillis() when (nsAlarm.level()) { 0 -> { id = NS_ANNOUNCEMENT level = ANNOUNCEMENT text = nsAlarm.message() validTo = System.currentTimeMillis() + T.mins(60).msecs() } 1 -> { id = NS_ALARM level = NORMAL text = nsAlarm.title() soundId = R.raw.alarm } 2 -> { id = NS_URGENT_ALARM level = URGENT text = nsAlarm.title() soundId = R.raw.urgentalarm } } buttonText = R.string.snooze action = Runnable { nsClientPlugin.handleClearAlarm(nsAlarm, 60 * 60 * 1000L) // Adding current time to snooze if we got staleData aapsLogger.debug(LTag.NOTIFICATION, "Notification text is: $text") val msToSnooze = sp.getInt(R.string.key_nsalarm_staledatavalue, 15) * 60 * 1000L aapsLogger.debug(LTag.NOTIFICATION, "snooze nsalarm_staledatavalue in minutes is ${T.msecs(msToSnooze).mins()} currentTimeMillis is: ${System.currentTimeMillis()}") sp.putLong(R.string.key_snoozedTo, System.currentTimeMillis() + msToSnooze) } } fun action(buttonText: Int, action: Runnable) { this.buttonText = buttonText this.action = action } }
agpl-3.0
8c51d7787ca6fe248a6389077f1d972e
35.701299
176
0.652743
4.586039
false
false
false
false
cyclestreets/android
libraries/cyclestreets-fragments/src/main/java/net/cyclestreets/MainNavDrawerActivity.kt
1
8732
package net.cyclestreets import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.util.SparseArray import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.transition.Fade import com.google.android.material.navigation.NavigationView import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial import net.cyclestreets.addphoto.AddPhotoFragment import net.cyclestreets.fragments.R import net.cyclestreets.iconics.IconicsHelper.materialIcons import net.cyclestreets.itinerary.ItineraryAndElevationFragment import net.cyclestreets.routing.Journey import net.cyclestreets.routing.Route import net.cyclestreets.routing.Waypoints import net.cyclestreets.util.Logging private val TAG = Logging.getTag(MainNavDrawerActivity::class.java) private const val DRAWER_ITEMID_SELECTED_KEY = "DRAWER_ITEM_SELECTED" abstract class MainNavDrawerActivity : AppCompatActivity(), OnNavigationItemSelectedListener, Route.Listener { private lateinit var drawerLayout: DrawerLayout private lateinit var navigationView: NavigationView private lateinit var toolbar: Toolbar private var selectedItem: Int = 0 private val menuItemIdToFragment = object : SparseArray<Class<out Fragment>>() { init { put(R.id.nav_journey_planner, RouteMapFragment::class.java) put(R.id.nav_itinerary, ItineraryAndElevationFragment::class.java) put(R.id.nav_photomap, PhotoMapFragment::class.java) put(R.id.nav_addphoto, AddPhotoFragment::class.java) put(R.id.nav_blog, BlogFragment::class.java) put(R.id.nav_settings, SettingsFragment::class.java) } } private val fragmentToMenuItemId = mapOf( RouteMapFragment::class.java to R.id.nav_journey_planner, ItineraryAndElevationFragment::class.java to R.id.nav_itinerary, PhotoMapFragment::class.java to R.id.nav_photomap, AddPhotoFragment::class.java to R.id.nav_addphoto, BlogFragment::class.java to R.id.nav_blog, SettingsFragment::class.java to R.id.nav_settings ) // If you're in one of these fragments at pause, then you'll be returned to it on resume. private val resumableFragments = setOf(R.id.nav_journey_planner, R.id.nav_photomap, R.id.nav_addphoto, R.id.nav_settings) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_navdrawer_activity) val (burgerIcon, addPhotoIcon, blogIcon, settingsIcon) = materialIcons(context = this, iconIds = listOf(GoogleMaterial.Icon.gmd_menu, GoogleMaterial.Icon.gmd_add_a_photo, GoogleMaterial.Icon.gmd_chat, GoogleMaterial.Icon.gmd_settings)) burgerIcon.setTint(resources.getColor(R.color.cs_primary_material_light, null)) drawerLayout = findViewById(R.id.drawer_layout) navigationView = (findViewById<NavigationView>(R.id.nav_view)).apply { setNavigationItemSelectedListener(this@MainNavDrawerActivity) menu.findItem(R.id.nav_itinerary).isVisible = Route.routeAvailable() menu.findItem(R.id.nav_addphoto).icon = addPhotoIcon menu.findItem(R.id.nav_blog).icon = blogIcon menu.findItem(R.id.nav_settings).icon = settingsIcon } toolbar = findViewById(R.id.toolbar) toolbar.visibility = View.VISIBLE setSupportActionBar(toolbar) supportActionBar!!.apply { setDisplayHomeAsUpEnabled(true) setHomeAsUpIndicator(burgerIcon) } if (CycleStreetsAppSupport.isFirstRun()) onFirstRun() else if (CycleStreetsAppSupport.isNewVersion()) onNewVersion() CycleStreetsAppSupport.splashScreenSeen() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { setBlogStateTitle() drawerLayout.openDrawer(GravityCompat.START) return true } } return super.onOptionsItemSelected(item) } //////////// OnNavigationItemSelectedListener method implementation override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { // Swap UI fragments based on the selection this.supportFragmentManager.beginTransaction().let { ft -> ft.replace(R.id.content_frame, instantiateFragmentFor(menuItem)) ft.commit() } updateMenuDisplayFor(menuItem) return true } private fun currentMenuItemId(): Int? { return this.supportFragmentManager.findFragmentById(R.id.content_frame)?.javaClass?.let { fragmentToMenuItemId[it] } } private fun updateMenuDisplayFor(menuItem: MenuItem) { // set item as selected to persist highlight menuItem.isChecked = true // close drawer when item is tapped drawerLayout.closeDrawers() // Save which item is selected selectedItem = menuItem.itemId // Update the ActionBar title to be the title of the chosen fragment toolbar.title = menuItem.title } private fun instantiateFragmentFor(menuItem: MenuItem): Fragment { val fragmentClass = menuItemIdToFragment.get(menuItem.itemId) try { return fragmentClass.newInstance().apply { enterTransition = Fade() exitTransition = Fade() } } catch (e: InstantiationException) { throw RuntimeException(e) } catch (e: IllegalAccessException) { throw RuntimeException(e) } } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(navigationView)) { drawerLayout.closeDrawers() return } visibleFragment()?.let { if (it is Undoable && it.onBackPressed()) return if (it !is RouteMapFragment) { showPage(R.id.nav_journey_planner) return } } super.onBackPressed() } private fun visibleFragment(): Fragment? { for (fragment in supportFragmentManager.fragments) if (fragment?.isVisible() == true) return fragment return null } protected open fun onFirstRun() {} protected open fun onNewVersion() {} fun showPage(menuItemId: Int): Boolean { val menuItem = navigationView.menu.findItem(menuItemId) if (menuItem != null) { Log.d(TAG, "Loading page with menuItemId=$menuItemId (${menuItem.title})") onNavigationItemSelected(menuItem) return true } Log.d(TAG, "Page with menuItemId=$menuItemId could not be found") return false } public override fun onResume() { val selectedItem = prefs().getInt(DRAWER_ITEMID_SELECTED_KEY, R.id.nav_journey_planner) if (!showPage(selectedItem)) showPage(R.id.nav_journey_planner) super.onResume() Route.registerListener(this) setBlogStateTitle() } public override fun onPause() { Route.unregisterListener(this) currentMenuItemId()?.let { saveCurrentMenuSelection(it) } super.onPause() } private fun saveCurrentMenuSelection(menuItemId: Int) { if (resumableFragments.contains(menuItemId)) prefs().edit().let { it.putInt(DRAWER_ITEMID_SELECTED_KEY, selectedItem) it.apply() } } private fun prefs(): SharedPreferences { return getSharedPreferences("net.cyclestreets.CycleStreets", Context.MODE_PRIVATE) } private fun setBlogStateTitle() { val titleId = if (BlogState.isBlogUpdateAvailable(this)) R.string.blog_updated else R.string.blog navigationView.menu.findItem(R.id.nav_blog).title = getString(titleId) } ////////// Route.Listener method implementations override fun onNewJourney(journey: Journey, waypoints: Waypoints) { navigationView.menu.findItem(R.id.nav_itinerary).isVisible = Route.routeAvailable() invalidateOptionsMenu() } override fun onResetJourney() { navigationView.menu.findItem(R.id.nav_itinerary).isVisible = Route.routeAvailable() invalidateOptionsMenu() } }
gpl-3.0
edfab40eb32f0c5f9470baf0e925db51
36.800866
190
0.677508
4.763775
false
false
false
false
AltBeacon/android-beacon-library
lib/src/main/java/org/altbeacon/beacon/service/IntentScanStrategyCoordinator.kt
1
12217
package org.altbeacon.beacon.service import android.bluetooth.BluetoothManager import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.content.ComponentName import android.content.Context import android.content.pm.PackageItemInfo import android.content.pm.PackageManager import android.os.Build import android.os.Handler import androidx.annotation.RequiresApi import org.altbeacon.beacon.Beacon import org.altbeacon.beacon.BeaconManager import org.altbeacon.beacon.Region import org.altbeacon.beacon.distance.ModelSpecificDistanceCalculator import org.altbeacon.beacon.logging.LogManager import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class IntentScanStrategyCoordinator(val context: Context) { private lateinit var scanHelper: ScanHelper private lateinit var scanState: ScanState private var initialized = false private var started = false private var longScanForcingEnabled = false private var lastCycleEnd: Long = 0 var strategyFailureDetectionCount = 0 var lastStrategyFailureDetectionCount = 0 var disableOnFailure = false val executor = Executors.newFixedThreadPool(1) fun ensureInitialized() { if (!initialized) { initialized = true scanHelper = ScanHelper(context) if (Beacon.getDistanceCalculator() == null) { val defaultDistanceCalculator = ModelSpecificDistanceCalculator(context, BeaconManager.getDistanceModelUpdateUrl()); Beacon.setDistanceCalculator(defaultDistanceCalculator); } reinitialize() } } fun reinitialize() { if (!initialized) { ensureInitialized() // this will call reinitialize return } var newScanState = ScanState.restore(context) if (newScanState == null) { newScanState = ScanState(context) } scanState = newScanState scanState.setLastScanStartTimeMillis(System.currentTimeMillis()) scanHelper.monitoringStatus = scanState.getMonitoringStatus() scanHelper.rangedRegionState = scanState.getRangedRegionState() scanHelper.setBeaconParsers(scanState.getBeaconParsers()) scanHelper.setExtraDataBeaconTracker(scanState.getExtraBeaconDataTracker()) } fun applySettings() { scanState.applyChanges(BeaconManager.getInstanceForApplication(context)) reinitialize() if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { restartBackgroundScan() } } @RequiresApi(Build.VERSION_CODES.O) fun start() { started = true ensureInitialized() val beaconManager = BeaconManager.getInstanceForApplication(context) scanHelper.setExtraDataBeaconTracker(ExtraDataBeaconTracker()) beaconManager.setScannerInSameProcess(true) val longScanForcingEnabledString = getManifestMetadataValue("longScanForcingEnabled") if (longScanForcingEnabledString != null && longScanForcingEnabledString == "true") { LogManager.i( BeaconService.TAG, "longScanForcingEnabled to keep scans going on Android N for > 30 minutes" ) longScanForcingEnabled = true } scanHelper.reloadParsers() LogManager.d(TAG, "starting background scan") var regions = HashSet<Region>() var wildcardRegions = HashSet<Region>() for (region in beaconManager.rangedRegions) { if (region.identifiers.size == 0) { wildcardRegions.add(region) } else { regions.add(region) } } for (region in beaconManager.monitoredRegions) { if (region.identifiers.size == 0) { wildcardRegions.add(region) } else { regions.add(region) } } if (wildcardRegions.size > 0) { if (regions.size > 0) { LogManager.w(TAG, "Wildcard regions are being used for beacon ranging or monitoring. The wildcard regions are ignored with intent scan strategy active.") } else { regions = wildcardRegions } } scanHelper.startAndroidOBackgroundScan(scanState.getBeaconParsers(), ArrayList<Region>(regions)) lastCycleEnd = java.lang.System.currentTimeMillis() ScanJobScheduler.getInstance().scheduleForIntentScanStrategy(context) } private fun getManifestMetadataValue(key: String): String? { val value: String? = null try { val info: PackageItemInfo = context.getPackageManager().getServiceInfo( ComponentName( context, BeaconService::class.java ), PackageManager.GET_META_DATA ) if (info != null && info.metaData != null) { return info.metaData[key].toString() } } catch (e: PackageManager.NameNotFoundException) { } return null } @RequiresApi(Build.VERSION_CODES.O) fun stop() { ensureInitialized() LogManager.d(TAG, "stopping background scan") scanHelper.stopAndroidOBackgroundScan() ScanJobScheduler.getInstance().cancelSchedule(context) started = false } @RequiresApi(Build.VERSION_CODES.O) fun restartBackgroundScan() { ensureInitialized() LogManager.d(TAG, "restarting background scan") scanHelper.stopAndroidOBackgroundScan() // We may need to pause between these two events? scanHelper.startAndroidOBackgroundScan(scanState.getBeaconParsers()) } @RequiresApi(Build.VERSION_CODES.O) fun processScanResults(scanResults: ArrayList<ScanResult?>) { ensureInitialized() for (scanResult in scanResults) { if (scanResult != null) { //LogManager.d(TAG, "Got scan result: "+scanResult) scanHelper.processScanResult(scanResult.device, scanResult.rssi, scanResult.scanRecord?.bytes, scanResult.timestampNanos/1000) } } val now = java.lang.System.currentTimeMillis() val beaconManager = BeaconManager.getInstanceForApplication(context) var scanPeriod = beaconManager.foregroundScanPeriod if (beaconManager.backgroundMode) { scanPeriod = beaconManager.backgroundScanPeriod } if (now - lastCycleEnd > scanPeriod) { LogManager.d(TAG, "End of scan cycle"); lastCycleEnd = now scanHelper.getCycledLeScanCallback().onCycleEnd() } } fun performPeriodicProcessing(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { processScanResults(ArrayList<ScanResult?>()) // Use this opportunity to run a brief scan without a filter to see if we are able to // detect something without a filter. This would be an indication that the filtered // scan used in this strategy won't work runBackupScan(context) } } @RequiresApi(21) fun runBackupScan(context: Context) { if (!started) { LogManager.i(TAG, "Not doing backup scan because we are not started") return } var anythingDetectedWithIntentScan = scanHelper.anyBeaconsDetectedThisCycle() if (anythingDetectedWithIntentScan) { LogManager.d(TAG, "We have detected beacons with the intent scan. No need to do a backup scan.") strategyFailureDetectionCount = 0 lastStrategyFailureDetectionCount = 0 return } LogManager.i(TAG, "Starting backup scan on background thread") executor.execute({ LogManager.i(TAG, "Starting backup scan") val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager val adapter = manager.adapter var beaconDetected = false val scanStartTime = System.currentTimeMillis() if (adapter != null) { val scanner: BluetoothLeScanner? = adapter.getBluetoothLeScanner() if (scanner != null) { val callback: ScanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { super.onScanResult(callbackType, result) scanHelper.processScanResult(result.device, result.rssi, result.scanRecord?.bytes, result.timestampNanos) try { scanner.stopScan(this) } catch (e: IllegalStateException) { /* do nothing */ } // caught if bluetooth is off here } override fun onBatchScanResults(results: List<ScanResult>) { super.onBatchScanResults(results) } override fun onScanFailed(errorCode: Int) { super.onScanFailed(errorCode) LogManager.d(TAG, "Sending onScanFailed event") } } try { scanner.startScan(callback) while (beaconDetected == false) { LogManager.d(TAG, "Waiting for beacon detection...") try { Thread.sleep(1000L) } catch (e: InterruptedException) { /* do nothing */ } if (System.currentTimeMillis() - scanStartTime > 30000L) { LogManager.d(TAG, "Timeout running backup scan to look for beacons") break } if (scanHelper.anyBeaconsDetectedThisCycle()) { // We have detected beacons with the backup scan but we failed to do so with the regular scan // this indicates a failure in the intent scanning technique. if (strategyFailureDetectionCount == lastStrategyFailureDetectionCount) { LogManager.e(TAG, "We have detected a beacon with the backup scan without a filter. We never detected one with the intent scan with a filter. This technique will not work.") } lastStrategyFailureDetectionCount = strategyFailureDetectionCount strategyFailureDetectionCount++ } } scanner.stopScan(callback) } catch (e: IllegalStateException) { LogManager.d(TAG, "Bluetooth is off. Cannot run backup scan") } catch (e: NullPointerException) { // Needed to stop a crash caused by internal NPE thrown by Android. See issue #636 LogManager.e(TAG, "NullPointerException. Cannot run backup scan", e) } } else { LogManager.d(TAG, "Cannot get scanner") } } LogManager.d(TAG, "backup scan complete") if (disableOnFailure && strategyFailureDetectionCount > 0) { BeaconManager.getInstanceForApplication(context).handleStategyFailover() } // Call this a second time to clear out beacons detected in the log 5-25 minute region if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { [email protected](ArrayList<ScanResult?>()) } }) } companion object { val TAG = "IntentScanCoord" } }
apache-2.0
10ccf251ce946e8761928750b1643f81
42.480427
211
0.597446
5.575993
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimKeyGroupBase.kt
1
6721
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.api import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import com.maddyhome.idea.vim.key.CommandPartNode import com.maddyhome.idea.vim.key.KeyMapping import com.maddyhome.idea.vim.key.KeyMappingLayer import com.maddyhome.idea.vim.key.MappingInfo import com.maddyhome.idea.vim.key.MappingOwner import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.RequiredShortcut import com.maddyhome.idea.vim.key.RootNode import com.maddyhome.idea.vim.key.ShortcutOwnerInfo import com.maddyhome.idea.vim.vimscript.model.expressions.Expression import java.awt.event.KeyEvent import java.util.* import javax.swing.KeyStroke import kotlin.math.min abstract class VimKeyGroupBase : VimKeyGroup { @JvmField val myShortcutConflicts: MutableMap<KeyStroke, ShortcutOwnerInfo> = LinkedHashMap() val requiredShortcutKeys: MutableSet<RequiredShortcut> = HashSet(300) val keyRoots: MutableMap<MappingMode, CommandPartNode<VimActionsInitiator>> = EnumMap(MappingMode::class.java) val keyMappings: MutableMap<MappingMode, KeyMapping> = EnumMap(MappingMode::class.java) override var operatorFunction: OperatorFunction? = null override fun removeKeyMapping(modes: Set<MappingMode>, keys: List<KeyStroke>) { modes.map { getKeyMapping(it) }.forEach { it.delete(keys) } } override fun removeKeyMapping(modes: Set<MappingMode>) { modes.map { getKeyMapping(it) }.forEach { it.delete() } } override fun hasmapto(mode: MappingMode, toKeys: List<KeyStroke>): Boolean { return this.getKeyMapping(mode).hasmapto(toKeys) } override fun getKeyMapping(mode: MappingMode): KeyMapping { return keyMappings.getOrPut(mode) { KeyMapping() } } override fun resetKeyMappings() { keyMappings.clear() } /** * Returns the root of the key mapping for the given mapping mode * * @param mappingMode The mapping mode * @return The key mapping tree root */ override fun getKeyRoot(mappingMode: MappingMode) = keyRoots.getOrPut(mappingMode) { RootNode() } override fun getKeyMappingLayer(mode: MappingMode): KeyMappingLayer = getKeyMapping(mode) protected fun checkCommand( mappingModes: Set<MappingMode>, action: EditorActionHandlerBase, keys: List<KeyStroke>, ) { for (mappingMode in mappingModes) { checkIdentity(mappingMode, action.id, keys) } checkCorrectCombination(action, keys) } private fun checkIdentity(mappingMode: MappingMode, actName: String, keys: List<KeyStroke>) { val keySets = identityChecker!!.getOrPut(mappingMode) { HashSet() } if (keys in keySets) { throw RuntimeException("This keymap already exists: $mappingMode keys: $keys action:$actName") } keySets.add(keys.toMutableList()) } private fun checkCorrectCombination(action: EditorActionHandlerBase, keys: List<KeyStroke>) { for (entry in prefixes!!.entries) { val prefix = entry.key if (prefix.size == keys.size) continue val shortOne = min(prefix.size, keys.size) var i = 0 while (i < shortOne) { if (prefix[i] != keys[i]) break i++ } val actionExceptions = listOf( "VimInsertDeletePreviousWordAction", "VimInsertAfterCursorAction", "VimInsertBeforeCursorAction", "VimFilterVisualLinesAction", "VimAutoIndentMotionAction" ) if (i == shortOne && action.id !in actionExceptions && entry.value !in actionExceptions) { throw RuntimeException( "Prefix found! $keys in command ${action.id} is the same as ${prefix.joinToString(", ") { it.toString() }} in ${entry.value}" ) } } prefixes!![keys.toMutableList()] = action.id } override val savedShortcutConflicts: MutableMap<KeyStroke, ShortcutOwnerInfo> get() = myShortcutConflicts protected fun initIdentityChecker() { identityChecker = EnumMap(MappingMode::class.java) prefixes = HashMap() } var identityChecker: MutableMap<MappingMode, MutableSet<MutableList<KeyStroke>>>? = null var prefixes: MutableMap<MutableList<KeyStroke>, String>? = null override fun getKeyMappingByOwner(owner: MappingOwner): List<Pair<List<KeyStroke>, MappingInfo>> { return MappingMode.values().map { getKeyMapping(it) }.flatMap { it.getByOwner(owner) } } private fun registerKeyMapping(fromKeys: List<KeyStroke>, owner: MappingOwner) { val oldSize = requiredShortcutKeys.size for (key in fromKeys) { if (key.keyChar == KeyEvent.CHAR_UNDEFINED) { requiredShortcutKeys.add(RequiredShortcut(key, owner)) } } if (requiredShortcutKeys.size != oldSize) { updateShortcutKeysRegistration() } } private fun unregisterKeyMapping(owner: MappingOwner) { val oldSize = requiredShortcutKeys.size requiredShortcutKeys.removeIf { it.owner == owner } if (requiredShortcutKeys.size != oldSize) { updateShortcutKeysRegistration() } } override fun removeKeyMapping(owner: MappingOwner) { MappingMode.values().map { getKeyMapping(it) }.forEach { it.delete(owner) } unregisterKeyMapping(owner) } override fun putKeyMapping( modes: Set<MappingMode>, fromKeys: List<KeyStroke>, owner: MappingOwner, toKeys: List<KeyStroke>, recursive: Boolean, ) { modes.map { getKeyMapping(it) }.forEach { it.put(fromKeys, toKeys, owner, recursive) } registerKeyMapping(fromKeys, owner) } override fun putKeyMapping( modes: Set<MappingMode>, fromKeys: List<KeyStroke>, owner: MappingOwner, toExpr: Expression, originalString: String, recursive: Boolean, ) { modes.map { getKeyMapping(it) }.forEach { it.put(fromKeys, toExpr, owner, originalString, recursive) } registerKeyMapping(fromKeys, owner) } override fun putKeyMapping( modes: Set<MappingMode>, fromKeys: List<KeyStroke>, owner: MappingOwner, extensionHandler: ExtensionHandler, recursive: Boolean, ) { modes.map { getKeyMapping(it) }.forEach { it.put(fromKeys, owner, extensionHandler, recursive) } registerKeyMapping(fromKeys, owner) } override fun getMapTo(mode: MappingMode, toKeys: List<KeyStroke>): List<Pair<List<KeyStroke>, MappingInfo>> { return getKeyMapping(mode).getMapTo(toKeys) } override fun unregisterCommandActions() { requiredShortcutKeys.clear() keyRoots.clear() identityChecker?.clear() prefixes?.clear() } }
mit
c1e3e25ebd5880bf705fb43f40fd3c77
33.466667
135
0.723255
4.229704
false
false
false
false
dbrant/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/nearby/NearbyParentFragmentPresenterTest.kt
1
18605
package fr.free.nrw.commons.nearby import com.mapbox.mapboxsdk.annotations.Marker import com.nhaarman.mockitokotlin2.* import fr.free.nrw.commons.bookmarks.locations.BookmarkLocationsDao import fr.free.nrw.commons.location.LatLng import fr.free.nrw.commons.location.LocationServiceManager.LocationChangeType import fr.free.nrw.commons.nearby.contract.NearbyParentFragmentContract import fr.free.nrw.commons.nearby.presenter.NearbyParentFragmentPresenter import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations /** * The unit test class for NearbyParentFragmentPresenter */ class NearbyParentFragmentPresenterTest { @Mock internal lateinit var nearbyParentFragmentView: NearbyParentFragmentContract.View @Mock internal lateinit var bookmarkLocationsDao: BookmarkLocationsDao @Mock internal lateinit var latestLocation: LatLng @Mock internal lateinit var cameraTarget: LatLng @Mock internal lateinit var selectedLabels: List<Label> @Mock internal lateinit var marker: Marker private lateinit var nearbyPresenter: NearbyParentFragmentPresenter private lateinit var mapboxCameraTarget: com.mapbox.mapboxsdk.geometry.LatLng /** * initial setup */ @Before @Throws(Exception::class) fun setUp() { MockitoAnnotations.initMocks(this) nearbyPresenter = NearbyParentFragmentPresenter(bookmarkLocationsDao) nearbyPresenter.attachView(nearbyParentFragmentView) } /** * Tests nearby operations are initialized */ @Test fun testInitializeNearbyMapOperations() { nearbyPresenter.initializeMapOperations() verify(nearbyParentFragmentView).enableFABRecenter() expectMapAndListUpdate() nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED) verify(nearbyParentFragmentView).disableFABRecenter(); verify(nearbyParentFragmentView).setProgressBarVisibility(true) verify(nearbyParentFragmentView).populatePlaces(latestLocation) verify(nearbyParentFragmentView).addSearchThisAreaButtonAction() verify(nearbyParentFragmentView).setCheckBoxAction() } /** * Test lockUnlockNearby method to lock nearby case */ @Test fun testLockUnlockNearbyForLocked() { nearbyPresenter.lockUnlockNearby(true) verify(nearbyParentFragmentView).disableFABRecenter() } /** * Test lockUnlockNearby method to unlock nearby case */ @Test fun testLockUnlockNearbyForUnlocked() { nearbyPresenter.lockUnlockNearby(false) verify(nearbyParentFragmentView).enableFABRecenter() } /** * Test updateMapAndList method returns with zero interactions when location is locked */ @Test fun testUpdateMapAndListWhenLocationLocked() { nearbyPresenter.lockUnlockNearby(true) nearbyPresenter.updateMapAndList(null) verify(nearbyParentFragmentView).disableFABRecenter() verifyZeroInteractions(nearbyParentFragmentView) } /** * Test updateMapAndList method returns with zero interactions when network connection * is not established */ @Test fun testUpdateMapAndListWhenNoNetworkConnection() { nearbyPresenter.lockUnlockNearby(false) whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(false) nearbyPresenter.updateMapAndList(null) verify(nearbyParentFragmentView).enableFABRecenter() verify(nearbyParentFragmentView).isNetworkConnectionEstablished() verifyNoMoreInteractions(nearbyParentFragmentView) } /** * Test updateMapAndList method returns with zero interactions when last location is null */ @Test fun testUpdateMapAndListWhenLastLocationIsNull() { nearbyPresenter.lockUnlockNearby(false) whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(true) whenever(nearbyParentFragmentView.getLastLocation()).thenReturn(null) nearbyPresenter.updateMapAndList(null) verify(nearbyParentFragmentView).enableFABRecenter() verify(nearbyParentFragmentView).isNetworkConnectionEstablished() verify(nearbyParentFragmentView).getLastLocation() verifyNoMoreInteractions(nearbyParentFragmentView) } /** * Test updateMapAndList method updates parent fragment view with latest location of user * at significant location change */ @Test fun testPlacesPopulatedForLatestLocationWhenLocationSignificantlyChanged() { expectMapAndListUpdate() nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED) updateMapSignificantly() } /** * Test updateMapAndList method updates parent fragment view with latest location of user * at map is updated location change type */ @Test fun testPlacesPopulatedForLatestLocationWhenLocationMapUpdated() { expectMapAndListUpdate() nearbyPresenter.updateMapAndList(LocationChangeType.MAP_UPDATED) updateMapSignificantly() } fun updateMapSignificantly() { verify(nearbyParentFragmentView).disableFABRecenter() verify(nearbyParentFragmentView).setProgressBarVisibility(true) verify(nearbyParentFragmentView).populatePlaces(latestLocation) } /** * Test updateMapAndList method updates parent fragment view with camera target location * at search custom area mode */ @Test fun testPlacesPopulatedForCameraTargetLocationWhenSearchCustomArea() { expectMapAndListUpdate() whenever(nearbyParentFragmentView.getCameraTarget()).thenReturn(cameraTarget) nearbyPresenter.updateMapAndList(LocationChangeType.SEARCH_CUSTOM_AREA) verify(nearbyParentFragmentView).disableFABRecenter() verify(nearbyParentFragmentView).setProgressBarVisibility(true) verify(nearbyParentFragmentView).populatePlaces(cameraTarget) } /** * Test testUpdateMapAndList tracks users location if current location marker is visible and * location is slightly changed */ @Test fun testUserTrackedWhenCurrentLocationMarkerVisible() { expectMapAndListUpdate() whenever(nearbyParentFragmentView.isCurrentLocationMarkerVisible()).thenReturn(true) nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SLIGHTLY_CHANGED) verify(nearbyParentFragmentView).recenterMap(latestLocation) } /** * Test testUpdateMapAndList doesn't track users location if current location marker is * invisible and location is slightly changed */ @Test fun testUserNotTrackedWhenCurrentLocationMarkerInvisible() { expectMapAndListUpdate() whenever(nearbyParentFragmentView.isCurrentLocationMarkerVisible()).thenReturn(false) nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SLIGHTLY_CHANGED) verify(nearbyParentFragmentView).enableFABRecenter() verify(nearbyParentFragmentView).isNetworkConnectionEstablished() verify(nearbyParentFragmentView).getLastLocation() verify(nearbyParentFragmentView).isCurrentLocationMarkerVisible() verifyNoMoreInteractions(nearbyParentFragmentView) } /** * Test search this area button became visible after user moved the camera target to far * away from current target. Distance between these two point is 111.19 km, so our camera target * is at outside of previously searched region if we set latestSearchRadius below 111.19. Thus, * setSearchThisAreaButtonVisibility(true) should be verified. */ @Test fun testSearchThisAreaButtonVisibleWhenMoveToFarPosition() { NearbyController.latestSearchLocation = Mockito.spy(LatLng(2.0,1.0,0.0F)) mapboxCameraTarget = Mockito.spy(com.mapbox.mapboxsdk.geometry.LatLng(1.0,1.0,0.0)) // Distance between these two point is 111.19 km NearbyController.latestSearchRadius = 111.0*1000 // To meter whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(true) nearbyPresenter.onCameraMove(mapboxCameraTarget) verify(nearbyParentFragmentView).setSearchThisAreaButtonVisibility(true) } /** * Test search this area button became visible after user moved the camera target to far * away from current target. Distance between these two point is 111.19 km, so our camera target * is at inside of previously searched region if we set latestSearchRadius above 111.19. Thus, * setSearchThisAreaButtonVisibility(false) should be verified. */ @Test fun testSearchThisAreaButtonInvisibleWhenMoveToClosePosition() { NearbyController.latestSearchLocation = Mockito.spy(LatLng(2.0,1.0,0.0F)) mapboxCameraTarget = Mockito.spy(com.mapbox.mapboxsdk.geometry.LatLng(1.0,1.0,0.0)) // Distance between these two point is 111.19 km NearbyController.latestSearchRadius = 112.0*1000 // To meter whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(true) nearbyPresenter.onCameraMove(mapboxCameraTarget) verify(nearbyParentFragmentView).setSearchThisAreaButtonVisibility(false) } /** * Multi selection should overwrite single selection of marker types. Ie. when user choose *"parks", then they multi select to display all or none, we overwrite previous "park" filter. * * We expect zero interaction from view when state is UNKNOWN */ @Test fun testFilterByMarkerTypeMultiSelectUNKNOWN() { val state = CheckBoxTriStates.UNKNOWN nearbyPresenter.filterByMarkerType(selectedLabels,state,false,true) verifyZeroInteractions(nearbyParentFragmentView) } /** * Multi selection should overwrite single selection of marker types. Ie. when user choose *"parks", then they multi select to display all or none, we overwrite previous "park" filter. * * We expect just filterOutAllMarkers and setRecyclerViewAdapterItemsGreyedOut is called when * the state is UNCHECKED */ @Test fun testFilterByMarkerTypeMultiSelectUNCHECKED() { val state = CheckBoxTriStates.UNCHECKED nearbyPresenter.filterByMarkerType(selectedLabels,state,false,true) verify(nearbyParentFragmentView).filterOutAllMarkers() verify(nearbyParentFragmentView).setRecyclerViewAdapterItemsGreyedOut() verifyNoMoreInteractions(nearbyParentFragmentView) } /** * Multi selection should overwrite single selection of marker types. Ie. when user choose *"parks", then they multi select to display all or none, we overwrite previous "park" filter. * * We expect just displayAllMarkers and setRecyclerViewAdapterAllSelected is called when * the state is CHECKED */ @Test fun testFilterByMarkerTypeMultiSelectCHECKED() { val state = CheckBoxTriStates.CHECKED nearbyPresenter.filterByMarkerType(selectedLabels, state, false,true) verify(nearbyParentFragmentView).displayAllMarkers() verify(nearbyParentFragmentView).setRecyclerViewAdapterAllSelected() verifyNoMoreInteractions(nearbyParentFragmentView) } /** * We expect just filterMarkersByLabels is called when filterForAllNoneType is false */ @Test fun testFilterByMarkerTypeSingleSelect() { nearbyPresenter.filterByMarkerType(selectedLabels, 0, true,false) verify(nearbyParentFragmentView).filterMarkersByLabels(any(), any(), any(), any(), any()); verifyNoMoreInteractions(nearbyParentFragmentView) } /** * Test if bottom sheet gets hidden after search view gained focus */ @Test fun testSearchViewFocusWhenBottomSheetExpanded() { whenever(nearbyParentFragmentView.isListBottomSheetExpanded()).thenReturn(true) nearbyPresenter.searchViewGainedFocus() verify(nearbyParentFragmentView).hideBottomSheet() } /** * Test if bottom details sheet gets hidden after search view gained focus */ @Test fun testSearchViewFocusWhenDetailsBottomSheetVisible() { whenever(nearbyParentFragmentView.isListBottomSheetExpanded()).thenReturn(false) whenever(nearbyParentFragmentView.isDetailsBottomSheetVisible()).thenReturn(true) nearbyPresenter.searchViewGainedFocus() verify(nearbyParentFragmentView).hideBottomDetailsSheet() } /** * Test if the search is close to current location, when last location is null we expect it to * return true */ @Test fun testSearchCloseToCurrentLocationNullLastLocation() { whenever(nearbyParentFragmentView.getLastFocusLocation()).thenReturn(null) val isClose = nearbyPresenter?.searchCloseToCurrentLocation() assertTrue(isClose!!) } /** * Test if the search is close to current location, when far */ @Test fun testSearchCloseToCurrentLocationWhenFar() { whenever(nearbyParentFragmentView.getLastFocusLocation()). thenReturn(com.mapbox.mapboxsdk.geometry.LatLng(1.0,1.0,0.0)) whenever(nearbyParentFragmentView.getCameraTarget()). thenReturn(LatLng(2.0,1.0,0.0F)) //111.19 km real distance, return false if 148306.444306 > currentLocationSearchRadius NearbyController.currentLocationSearchRadius = 148306.0 val isClose = nearbyPresenter?.searchCloseToCurrentLocation() assertFalse(isClose!!) } /** * Test if the search is close to current location, when close */ @Test fun testSearchCloseToCurrentLocationWhenClose() { whenever(nearbyParentFragmentView.getLastFocusLocation()). thenReturn(com.mapbox.mapboxsdk.geometry.LatLng(1.0,1.0,0.0)) whenever(nearbyParentFragmentView.getCameraTarget()). thenReturn(LatLng(2.0,1.0,0.0F)) //111.19 km real distance, return false if 148253.333 > currentLocationSearchRadius NearbyController.currentLocationSearchRadius = 148307.0 val isClose = nearbyPresenter?.searchCloseToCurrentLocation() assertTrue(isClose!!) } fun expectMapAndListUpdate() { nearbyPresenter.lockUnlockNearby(false) whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(true) whenever(nearbyParentFragmentView.getLastLocation()).thenReturn(latestLocation) } @Test fun testSetActionListeners() { nearbyPresenter.setActionListeners(any()) verify(nearbyParentFragmentView).setFABPlusAction(any()) verify(nearbyParentFragmentView).setFABRecenterAction(any()) } @Test fun testBackButtonClickedWhenBottomSheetExpanded() { whenever(nearbyParentFragmentView.isListBottomSheetExpanded()).thenReturn(true) nearbyPresenter.backButtonClicked() verify(nearbyParentFragmentView).listOptionMenuItemClicked() } @Test fun testBackButtonClickedWhenDetailsBottomSheetVisible() { whenever(nearbyParentFragmentView.isListBottomSheetExpanded()).thenReturn(false) whenever(nearbyParentFragmentView.isDetailsBottomSheetVisible()).thenReturn(true) nearbyPresenter.backButtonClicked() verify(nearbyParentFragmentView).setBottomSheetDetailsSmaller() } @Test fun testBackButtonClickedWhenNoSheetVisible() { whenever(nearbyParentFragmentView.isListBottomSheetExpanded()).thenReturn(false) whenever(nearbyParentFragmentView.isDetailsBottomSheetVisible()).thenReturn(false) nearbyPresenter.backButtonClicked() verify(nearbyParentFragmentView).setTabItemContributions() } @Test fun testMarkerUnselected() { nearbyPresenter.markerUnselected() verify(nearbyParentFragmentView).hideBottomSheet(); } @Test fun testMarkerSelected() { nearbyPresenter.markerSelected(marker) verify(nearbyParentFragmentView).displayBottomSheetWithInfo(marker) } @Test fun testOnWikidataEditSuccessful() { nearbyPresenter.onWikidataEditSuccessful() expectMapAndListUpdate() nearbyPresenter.updateMapAndList(LocationChangeType.MAP_UPDATED) updateMapSignificantly() } @Test fun testOnLocationChangedSignificantly() { nearbyPresenter.onLocationChangedSignificantly(latestLocation) expectMapAndListUpdate() nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SIGNIFICANTLY_CHANGED) updateMapSignificantly() } @Test fun testOnLocationChangedSlightly() { nearbyPresenter.onLocationChangedSlightly(latestLocation) expectMapAndListUpdate() whenever(nearbyParentFragmentView.isCurrentLocationMarkerVisible()).thenReturn(true) nearbyPresenter.updateMapAndList(LocationChangeType.LOCATION_SLIGHTLY_CHANGED) verify(nearbyParentFragmentView).recenterMap(latestLocation) } @Test fun testOnCameraMoveWhenSearchLocationNull() { NearbyController.latestSearchLocation = null nearbyPresenter.onCameraMove(Mockito.mock(com.mapbox.mapboxsdk.geometry.LatLng::class.java)) verify(nearbyParentFragmentView).setProjectorLatLngBounds() verify(nearbyParentFragmentView).setSearchThisAreaButtonVisibility(false) } @Test fun testOnCameraMoveWhenNetworkConnectionNotEstablished() { NearbyController.latestSearchLocation = latestLocation whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(false) nearbyPresenter.onCameraMove(Mockito.mock(com.mapbox.mapboxsdk.geometry.LatLng::class.java)) verify(nearbyParentFragmentView).setProjectorLatLngBounds() verify(nearbyParentFragmentView).isNetworkConnectionEstablished() verifyZeroInteractions(nearbyParentFragmentView) } @Test fun testOnCameraMoveWhenNetworkConnectionEstablished() { NearbyController.latestSearchLocation = latestLocation whenever(nearbyParentFragmentView.isNetworkConnectionEstablished()).thenReturn(false) nearbyPresenter.onCameraMove(Mockito.mock(com.mapbox.mapboxsdk.geometry.LatLng::class.java)) verify(nearbyParentFragmentView).setProjectorLatLngBounds() verify(nearbyParentFragmentView).isNetworkConnectionEstablished() verifyZeroInteractions(nearbyParentFragmentView) } }
apache-2.0
ef032edb3d0959a228d8af40be174b79
40.905405
100
0.744639
5.923273
false
true
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/local/subscription/dialog/FeedGroupDialogViewModel.kt
3
5532
package org.schabi.newpipe.local.subscription.dialog import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.functions.BiFunction import io.reactivex.rxjava3.processors.BehaviorProcessor import io.reactivex.rxjava3.schedulers.Schedulers import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.local.feed.FeedDatabaseManager import org.schabi.newpipe.local.subscription.FeedGroupIcon import org.schabi.newpipe.local.subscription.SubscriptionManager import org.schabi.newpipe.local.subscription.item.PickerSubscriptionItem class FeedGroupDialogViewModel( applicationContext: Context, private val groupId: Long = FeedGroupEntity.GROUP_ALL_ID, initialQuery: String = "", initialShowOnlyUngrouped: Boolean = false ) : ViewModel() { private var feedDatabaseManager: FeedDatabaseManager = FeedDatabaseManager(applicationContext) private var subscriptionManager = SubscriptionManager(applicationContext) private var filterSubscriptions = BehaviorProcessor.create<String>() private var toggleShowOnlyUngrouped = BehaviorProcessor.create<Boolean>() private var subscriptionsFlowable = Flowable .combineLatest( filterSubscriptions.startWithItem(initialQuery), toggleShowOnlyUngrouped.startWithItem(initialShowOnlyUngrouped), BiFunction { t1: String, t2: Boolean -> Filter(t1, t2) } ) .distinctUntilChanged() .switchMap { (query, showOnlyUngrouped) -> subscriptionManager.getSubscriptions(groupId, query, showOnlyUngrouped) }.map { list -> list.map { PickerSubscriptionItem(it) } } private val mutableGroupLiveData = MutableLiveData<FeedGroupEntity>() private val mutableSubscriptionsLiveData = MutableLiveData<Pair<List<PickerSubscriptionItem>, Set<Long>>>() private val mutableDialogEventLiveData = MutableLiveData<DialogEvent>() val groupLiveData: LiveData<FeedGroupEntity> = mutableGroupLiveData val subscriptionsLiveData: LiveData<Pair<List<PickerSubscriptionItem>, Set<Long>>> = mutableSubscriptionsLiveData val dialogEventLiveData: LiveData<DialogEvent> = mutableDialogEventLiveData private var actionProcessingDisposable: Disposable? = null private var feedGroupDisposable = feedDatabaseManager.getGroup(groupId) .subscribeOn(Schedulers.io()) .subscribe(mutableGroupLiveData::postValue) private var subscriptionsDisposable = Flowable .combineLatest( subscriptionsFlowable, feedDatabaseManager.subscriptionIdsForGroup(groupId), BiFunction { t1: List<PickerSubscriptionItem>, t2: List<Long> -> t1 to t2.toSet() } ) .subscribeOn(Schedulers.io()) .subscribe(mutableSubscriptionsLiveData::postValue) override fun onCleared() { super.onCleared() actionProcessingDisposable?.dispose() subscriptionsDisposable.dispose() feedGroupDisposable.dispose() } fun createGroup(name: String, selectedIcon: FeedGroupIcon, selectedSubscriptions: Set<Long>) { doAction( feedDatabaseManager.createGroup(name, selectedIcon) .flatMapCompletable { feedDatabaseManager.updateSubscriptionsForGroup(it, selectedSubscriptions.toList()) } ) } fun updateGroup(name: String, selectedIcon: FeedGroupIcon, selectedSubscriptions: Set<Long>, sortOrder: Long) { doAction( feedDatabaseManager.updateSubscriptionsForGroup(groupId, selectedSubscriptions.toList()) .andThen(feedDatabaseManager.updateGroup(FeedGroupEntity(groupId, name, selectedIcon, sortOrder))) ) } fun deleteGroup() { doAction(feedDatabaseManager.deleteGroup(groupId)) } private fun doAction(completable: Completable) { if (actionProcessingDisposable == null) { mutableDialogEventLiveData.value = DialogEvent.ProcessingEvent actionProcessingDisposable = completable .subscribeOn(Schedulers.io()) .subscribe { mutableDialogEventLiveData.postValue(DialogEvent.SuccessEvent) } } } fun filterSubscriptionsBy(query: String) { filterSubscriptions.onNext(query) } fun clearSubscriptionsFilter() { filterSubscriptions.onNext("") } fun toggleShowOnlyUngrouped(showOnlyUngrouped: Boolean) { toggleShowOnlyUngrouped.onNext(showOnlyUngrouped) } sealed class DialogEvent { object ProcessingEvent : DialogEvent() object SuccessEvent : DialogEvent() } data class Filter(val query: String, val showOnlyUngrouped: Boolean) class Factory( private val context: Context, private val groupId: Long = FeedGroupEntity.GROUP_ALL_ID, private val initialQuery: String = "", private val initialShowOnlyUngrouped: Boolean = false ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return FeedGroupDialogViewModel( context.applicationContext, groupId, initialQuery, initialShowOnlyUngrouped ) as T } } }
gpl-3.0
37d221327410b58b6643a8d70f28c8b4
39.977778
117
0.725777
5.386563
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/iso7816/ISO7816TLV.kt
1
16031
/* * ISO7816TLV.kt * * Copyright 2018-2019 Michael Farrell <[email protected]> * Copyright 2018 Google * * 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 au.id.micolous.metrodroid.card.iso7816 import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.ui.ListItemRecursive import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.Preferences /** * Utilities for decoding BER-TLV values. * * Reference: https://en.wikipedia.org/wiki/X.690#BER_encoding */ object ISO7816TLV { private const val TAG = "ISO7816TLV" private const val MAX_TLV_FIELD_LENGTH = 0xffff /** * Gets the _length_ of a TLV tag identifier octets. * * @param buf TLV data buffer * @param p Offset within [buf] to read from * @return The number of bytes for this tag's identifier octets. */ private fun getTLVIDLen(buf: ImmutableByteArray, p: Int): Int { // One byte version: if the lower 5 bits (tag number) != 0x1f. if (buf[p].toInt() and 0x1f != 0x1f) return 1 // Multi-byte version: if the first byte has the lower 5 bits == 0x1f then subsequent // bytes contain the tag number. Bit 8 is set when there (is/are) more byte(s) for the // tag number. var len = 1 while (buf[p + len++].toInt() and 0x80 != 0); return len } /** * Decodes the length octets for a TLV tag. * * @param buf TLV data buffer * @param p Offset within [buf] to start reading the length octets from * @return A `[Triple]<[Int], [Int]>`: the number of bytes for this tag's length octets, the * length of the _contents octets_, and the length of the _end of contents octets_. * * Returns `null` if invalid. */ private fun decodeTLVLen(buf: ImmutableByteArray, p: Int): Triple<Int, Int, Int>? { val headByte = buf[p].toInt() and 0xff if (headByte shr 7 == 0) { // Definite, short form (1 byte) // Length is the lower 7 bits of the first byte return Triple(1, headByte and 0x7f, 0) } // Decode other forms val numfollowingbytes = headByte and 0x7f if (numfollowingbytes == 0) { // Indefinite form. // Value is terminated by two NULL bytes. val endPos = buf.indexOf(ImmutableByteArray.empty(2), p + 1) return if (endPos == -1) { // No null terminators! Log.e(TAG, "No null terminator for indef tag at $p!") null } else { Triple(1, endPos - p - 1, 2) } } else if (numfollowingbytes >= 8) { // Definite, long form // // We got 8 or more following bytes for storing the length. We can only decode // this if all bytes but the last 8 are NULL, and the 8th-to-last top bit is also 0. val topBytes = buf.sliceOffLen(p + 1, numfollowingbytes - 8) if (!(topBytes.isEmpty() || topBytes.isAllZero()) || buf[p + 1 + numfollowingbytes - 7].toInt() and 0x80 == 0x80) { // We can't decode Log.e(TAG, "Definite long form at $p is too big for signed long " + "($numfollowingbytes), cannot decode!") return null } } // Definite form, long form val length = buf.byteArrayToInt(p + 1, numfollowingbytes) if (length > MAX_TLV_FIELD_LENGTH) { // 64 KiB field length is enough for anyone(tm). :) Log.e(TAG, "Definite long form at $p of > $MAX_TLV_FIELD_LENGTH bytes " + "($length)") return null } else if (length < 0) { // Shouldn't get negative values either. Log.e(TAG, "Definite log form at $p has negative value? ($length)") return null } return Triple(1 + numfollowingbytes, length, 0) } /** * Iterates over BER-TLV encoded data lazily with a [Sequence]. * * @param buf The BER-TLV encoded data to iterate over * @return [Sequence] of [Triple] of `id, header, data` */ fun berTlvIterate(buf: ImmutableByteArray) : Sequence<Triple<ImmutableByteArray, ImmutableByteArray, ImmutableByteArray>> { return sequence { // Skip null bytes at start: // "Before, between, or after TLV-coded data objects, '00' bytes without any meaning may // occur (for example, due to erased or modified TLV-coded data objects)." var p = buf.indexOfFirst { it != 0.toByte() } if (p == -1) { // No non-null bytes return@sequence } // Skip ID p = getTLVIDLen(buf, 0) val (startoffset, alldatalen, alleoclen) = decodeTLVLen(buf, p) ?: return@sequence if (p < 0 || startoffset < 0 || alldatalen < 0 || alleoclen < 0) { Log.w(TAG, "Invalid TLV reading header: p=$p, startoffset=$startoffset, " + "alldatalen=$alldatalen, alleoclen=$alleoclen") return@sequence } p += startoffset val fulllen = p + alldatalen while (p < fulllen) { // Skip null bytes if (buf[p] == 0.toByte()) { p++ continue } val idlen = getTLVIDLen(buf, p) if (p + idlen >= buf.size) break // EOF val id = buf.sliceOffLenSafe(p, idlen) if (id == null) { Log.w(TAG, "Invalid TLV ID data at $p: out of bounds") break } // Log.d(TAG, "($p) id=${id.getHexString()}") val (hlen, datalen, eoclen) = decodeTLVLen(buf, p + idlen) ?: break if (idlen < 0 || hlen < 0 || datalen < 0 || eoclen < 0) { // Invalid lengths, abort! Log.w(TAG, "Invalid TLV data at $p (<0): idlen=$idlen, hlen=$hlen, " + "datalen=$datalen, eoclen=$eoclen") break } val header = buf.sliceOffLenSafe(p, idlen + hlen) val data = buf.sliceOffLenSafe(p + idlen + hlen, datalen) if (header == null || data == null) { // Invalid ranges, abort! Log.w(TAG, "Invalid TLV data at $p: out of bounds") break } if ((id.isAllZero() || id.isEmpty()) && (header.isEmpty() || header.isAllZero()) && data.isEmpty()) { // Skip empty tag continue } // Log.d(TAG, "($p) id=${id.toHexString()}, header=${header.getHexString()}, " + // "data=${data.getHexString()}") yield(Triple(id, header, data)) p += idlen + hlen + datalen + eoclen } } } // TODO: Replace with Sequence /** * Iterates over Processing Options Data Object List (PDOL), tag 9f38. * * This is a list of tags needed by the ICC for the GET PROCESSING OPTIONS (GPO) command. * * The lengths in this context are the expected length in the request. */ fun pdolIterate(buf: ImmutableByteArray, iterator: (id: ImmutableByteArray, len: Int) -> Unit) { var p = 0 while (p < buf.size) { val idlen = getTLVIDLen(buf, p) if (idlen < 0) break val (lenlen, datalen, eoclen) = decodeTLVLen(buf, p + idlen) ?: break if (lenlen < 0 || datalen < 0 || eoclen != 0) break iterator(buf.sliceOffLen(p, idlen), datalen) p += idlen + lenlen } } fun findBERTLV(buf: ImmutableByteArray, target: String, keepHeader: Boolean): ImmutableByteArray? { return findBERTLV(buf, ImmutableByteArray.fromHex(target), keepHeader) } fun findBERTLV(buf: ImmutableByteArray, target: ImmutableByteArray, keepHeader: Boolean): ImmutableByteArray? { val result = berTlvIterate(buf).firstOrNull { it.first == target } ?: return null return if (keepHeader) { result.second + result.third } else { result.third } } fun findRepeatedBERTLV(buf: ImmutableByteArray, target: String, keepHeader: Boolean): Sequence<ImmutableByteArray> { return findRepeatedBERTLV(buf, ImmutableByteArray.fromHex(target), keepHeader) } fun findRepeatedBERTLV( buf: ImmutableByteArray, target: ImmutableByteArray, keepHeader: Boolean): Sequence<ImmutableByteArray> { return berTlvIterate(buf).filter { it.first == target }.map { if (keepHeader) { it.second + it.third } else { it.third } } } /** * Parses BER-TLV data, and builds [ListItem] and [ListItemRecursive] for each of the tags. */ fun infoBerTLV(buf: ImmutableByteArray): List<ListItem> { return berTlvIterate(buf).map { (id, header, data) -> if (id[0].toInt() and 0xe0 == 0xa0) { try { ListItemRecursive(id.toHexString(), null, infoBerTLV(header + data)) } catch (e: Exception) { ListItem(id.toHexDump(), data.toHexDump()) } } else { ListItem(id.toHexDump(), data.toHexDump()) } }.toList() } fun infoWithRaw(buf: ImmutableByteArray) = listOfNotNull( ListItemRecursive.collapsedValue(R.string.iso7816_raw, buf.toHexDump()), try { ListItemRecursive(R.string.iso7816_tlv, null, infoBerTLV(buf)) } catch (e: Exception) { null }) fun removeTlvHeader(buf: ImmutableByteArray): ImmutableByteArray { val p = getTLVIDLen(buf, 0) // todo check if past eof val (startoffset, datalen, _) = decodeTLVLen(buf, p) ?: return ImmutableByteArray.empty() return buf.sliceOffLen(p+startoffset, datalen) } private fun makeListItem(tagDesc: TagDesc, data: ImmutableByteArray) : ListItem? { return when (tagDesc.contents) { TagContents.HIDE -> null // TODO: Move into TagDesc TagContents.DUMP_LONG -> if (Preferences.hideCardNumbers) { null } else { ListItem(tagDesc.name, data.toHexDump()) } else -> { val v = tagDesc.interpretTag(data) when { v.isEmpty() -> null else -> ListItem(tagDesc.name, v) } } } } /** * Parses BER-TLV data, and builds [ListItem] for each of the tags. * * This replaces the names with human-readable names, and does not operate recursively. * @param includeUnknown If `true`, include tags that did not appear in [tagMap] */ fun infoBerTLV(tlv: ImmutableByteArray, tagMap: Map<String, TagDesc>, includeUnknown: Boolean = false) = berTlvIterate(tlv).mapNotNull { (id, _, data) -> val idStr = id.toHexString() val d = tagMap[idStr] if (d == null) { if (includeUnknown) { ListItem(FormattedString(idStr), data.toHexDump()) } else { null } } else { makeListItem(d, data) } }.toList() /** * Like [infoBerTLV], but also returns a list of IDs that were unknown in the process. */ fun infoBerTLVWithUnknowns(tlv: ImmutableByteArray, tagMap: Map<String, TagDesc>): Pair<List<ListItem>, Set<String>> { val unknownIds = mutableSetOf<String>() return Pair(berTlvIterate(tlv).mapNotNull { (id, _, data) -> val idStr = id.toHexString() val d = tagMap[idStr] if (d == null) { unknownIds.add(idStr) ListItem(FormattedString(idStr), data.toHexDump()) } else { makeListItem(d, data) } }.toList(), unknownIds.toSet()) } /** * Iterates over Simple-TLV encoded data lazily with a [Sequence]. * * Simple-TLV format is defined in ISO7816-4. * * @param buf The Simple-TLV encoded data to iterate over * @return [Sequence] of [Pair] of `id, data` */ fun simpleTlvIterate(buf: ImmutableByteArray) : Sequence<Pair<Int, ImmutableByteArray>> { return sequence { // Skip null bytes at start: // "Before, between, or after TLV-coded data objects, '00' bytes without any meaning may // occur (for example, due to erased or modified TLV-coded data objects)." var p = buf.indexOfFirst { it != 0.toByte() } if (p == -1) { // No non-null bytes return@sequence } while (p < buf.count()) { val tag = buf[p++].toInt() and 0xff var len = buf[p++].toInt() and 0xff // If the length byte is FF, then the length is stored in the subsequent 2 bytes // (big-endian). if (len == 0xff) { len = buf.byteArrayToInt(p, 2) and 0xffff p += 2 } // Skip empty tag if (len < 1) continue val d = buf.sliceOffLenSafe(p, len) ?: return@sequence // Invalid length yield(Pair(tag, d)) p += len } } } /** * Iterates over Compact-TLV encoded data lazily with a [Sequence]. * * @param buf The Compact-TLV encoded data to iterate over * @return [Sequence] of [Pair] of `id, data` */ fun compactTlvIterate(buf: ImmutableByteArray) : Sequence<Pair<Int, ImmutableByteArray>> { return sequence { // Skip null bytes at start: // "Before, between, or after TLV-coded data objects, '00' bytes without any meaning may // occur (for example, due to erased or modified TLV-coded data objects)." var p = buf.indexOfFirst { it != 0.toByte() } if (p == -1) { // No non-null bytes return@sequence } while (p < buf.count()) { val tag = buf[p].toInt() and 0xf0 shr 4 val len = buf[p++].toInt() and 0xf // Skip empty tag if (len < 1) continue val d = buf.sliceOffLenSafe(p, len) ?: return@sequence // Invalid length yield(Pair(tag, d)) p += len } } } }
gpl-3.0
dc251d4b05a8453d3fda67130911ef51
35.852874
103
0.532967
4.501825
false
false
false
false
Major-/Vicis
scene3d/src/main/kotlin/rs/emulate/scene3d/backend/opengl/OpenGLRenderer.kt
1
1839
package rs.emulate.scene3d.backend.opengl import org.lwjgl.glfw.GLFW.* import org.lwjgl.opengl.GL.createCapabilities import org.lwjgl.opengl.GL11.* import org.lwjgl.system.MemoryUtil.NULL import rs.emulate.scene3d.Geometry import rs.emulate.scene3d.Node import rs.emulate.scene3d.Scene import rs.emulate.scene3d.backend.RenderTarget import rs.emulate.scene3d.backend.Renderer import rs.emulate.scene3d.backend.opengl.target.OpenGLRenderTarget val Node.glState: OpenGLGeometryState get() = metadata.computeIfAbsent(OpenGLRenderer.GL_METADATA_KEY) { OpenGLGeometryState() } as OpenGLGeometryState /** * A scene renderer that uses modern OpenGL to render the scene. * * @param scene The scene to render. * @param target The render target to blit the scene to. */ class OpenGLRenderer(val visible: Boolean = false) : Renderer { override fun render(scene: Scene, target: RenderTarget, alpha: Float) { target.bind() glClearColor(0f, 0.0f, 0f, 0f) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) glViewport(0, 0, scene.width, scene.height) val geometryNodes = scene.discover { it is Geometry } for (node in geometryNodes) { val geometry = node as Geometry val glState = geometry.glState if (geometry.dirty && !geometry.lock.isLocked) { if (!glState.initialized) { glState.initialize(geometry) } else { glState.update(geometry) } } else { glState.draw(scene.camera, geometry) } } target.blit() } override fun dispose() { // @todo - find all `Geometry` nodes and deallocate their resources } companion object { const val GL_METADATA_KEY = "OpenGLState" } }
isc
4df8d60c843ff7f926f1337059473e66
30.706897
117
0.656335
3.980519
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/yargor/YarGorSubscription.kt
1
5171
/* * YarGorSubscription.kt * * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.transit.yargor import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.Daystamp import au.id.micolous.metrodroid.time.TimestampFull import au.id.micolous.metrodroid.transit.Subscription import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.hexString @Parcelize data class YarGorSubscription(override val validFrom: Daystamp, override val validTo: Daystamp, override val purchaseTimestamp: TimestampFull, private val mType: Int, private val mL: ImmutableByteArray, private val mM: Byte, private val mTransports: Byte, private val mN: ImmutableByteArray, private val mChecksum: ImmutableByteArray ) : Subscription() { override val subscriptionName: String? get() = when (mType) { 0x9613 -> Localizer.localizeString(R.string.yargor_sub_weekday_tram) 0x9615 -> Localizer.localizeString(R.string.yargor_sub_weekday_trolley) 0x9621 -> Localizer.localizeString(R.string.yargor_sub_allday_all) else -> Localizer.localizeString(R.string.unknown_format, mType.toString(16)) } private val transportsDesc: String get() { val t = mutableListOf<String>() for (i in 0..7) { if ((mTransports.toInt() and (0x1 shl i)) != 0) t += when (i) { 0 -> Localizer.localizeString(R.string.mode_bus) 1 -> Localizer.localizeString(R.string.mode_tram) 2 -> Localizer.localizeString(R.string.mode_trolleybus) else -> Localizer.localizeString(R.string.unknown_format, i) } } return t.joinToString() } override val info: List<ListItem>? get() = listOf( ListItem(R.string.yargor_transports_valid, transportsDesc) ) override fun getRawFields(level: TransitData.RawLevel): List<ListItem> = listOf( ListItem(FormattedString("L"), mL.toHexDump()), ListItem("M", mM.hexString), ListItem(FormattedString("N"), mN.toHexDump()) ) + if (level == TransitData.RawLevel.ALL) listOf( ListItem("Type", mType.toString(16)), ListItem(FormattedString("Checksum"), mChecksum.toHexDump()) ) else listOf() companion object { private fun parseDate(data: ImmutableByteArray, off: Int): Daystamp = Daystamp(year = 2000 + (data[off].toInt() and 0xff), month = (data[off + 1].toInt() and 0xff) - 1, day = (data[off + 2].toInt() and 0xff)) private fun parseTimestamp(data: ImmutableByteArray, off: Int): TimestampFull = TimestampFull(tz = YarGorTransitData.TZ, year = 2000 + (data[off].toInt() and 0xff), month = (data[off + 1].toInt() and 0xff) - 1, day = data[off + 2].toInt() and 0xff, hour = data[off + 3].toInt() and 0xff, min = data[off + 4].toInt() and 0xff) fun parse(sector: ClassicSector): YarGorSubscription { val block0 = sector[0].data val block1 = sector[1].data return YarGorSubscription( mType = block0.byteArrayToInt(0, 2), validFrom = parseDate(block0, 2), validTo = parseDate(block0, 5), mL = block0.sliceOffLen(8, 6), mTransports = block0[14], mM = block0[15], purchaseTimestamp = parseTimestamp(block1, 0), mN = block1.sliceOffLen(5, 5), mChecksum = block1.sliceOffLen(10, 6) ) } } }
gpl-3.0
1fe26d300e924c2fc823389be11d1b23
43.973913
89
0.583059
4.592362
false
false
false
false
nonylene/MackerelAgentAndroid
app/src/main/java/net/nonylene/mackerelagent/host/spec/CPU.kt
1
2118
package net.nonylene.mackerelagent.host.spec import com.google.gson.annotations.SerializedName import net.nonylene.mackerelagent.utils.splitBy import java.io.File //case "processor": //cur = make(map[string]interface{}) //if modelName != "" { // cur["model_name"] = modelName //} // results = append(results, cur) // case "Processor": // modelName = val // case "vendor_id", "model", "stepping", "physical id", "core id", "model name", "cache size": // cur[strings.Replace(key, " ", "_", -1)] = val // case "cpu family": //cur["family"] = val //case "cpu cores": //cur["cores"] = val //case "cpu MHz": //cur["mhz"] = val // https://github.com/mackerelio/mackerel-agent/blob/master/spec/linux/cpu.go fun getCPUSpec(): List<CPUCoreSpec> { // ignore duplicate (core) return File("/proc/cpuinfo").readLines().filter { it.contains(':') }.map { it.split(":").map(String::trim) }.splitBy { it.first() == "processor" // remove first element }.drop(1).map { val map = it.map { it[0] to it[1] }.toMap() CPUCoreSpec( map["vendor_id"], map["model"], map["stepping"], map["physical id"], map["core id"], map["model name"], map["cache size"], map["cpu family"], map["cpu cores"], map["cpu MHz"] ) } } data class CPUCoreSpec( @SerializedName("vendor_id") val vendorId: String?, @SerializedName("model") val model: String?, @SerializedName("stepping") val stepping: String?, @SerializedName("physical_id") val physicalId: String?, @SerializedName("core_id") val coreId: String?, @SerializedName("model_name") val modelName: String?, @SerializedName("cache_size") val cacheSize: String?, @SerializedName("family") val cpuFamily: String?, @SerializedName("cores") val cpuCores: String?, @SerializedName("") val cpuMHz: String? )
mit
39063f09890d37d11e0b61795cabec0d
28.027397
95
0.553352
3.929499
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/src/com/intellij/cce/evaluation/EvaluationProcess.kt
8
3204
package com.intellij.cce.evaluation import com.intellij.cce.evaluation.step.FinishEvaluationStep import com.intellij.cce.workspace.EvaluationWorkspace import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.registry.Registry import kotlin.system.measureTimeMillis class EvaluationProcess private constructor(private val steps: List<EvaluationStep>) { companion object { fun build(init: Builder.() -> Unit, stepFactory: StepFactory): EvaluationProcess { val builder = Builder() builder.init() return builder.build(stepFactory) } } fun startAsync(workspace: EvaluationWorkspace) = ApplicationManager.getApplication().executeOnPooledThread { start(workspace) } fun start(workspace: EvaluationWorkspace): EvaluationWorkspace { val stats = mutableMapOf<String, Long>() var currentWorkspace = workspace var hasError = false for (step in steps) { if (hasError && step !is UndoableEvaluationStep.UndoStep && step !is FinishEvaluationStep) continue println("Starting step: ${step.name} (${step.description})") val duration = measureTimeMillis { val result = step.start(currentWorkspace) if (result == null) hasError = true else currentWorkspace = result } stats[step.name] = duration } currentWorkspace.saveAdditionalStats("evaluation_process", stats) return currentWorkspace } class Builder { var shouldGenerateActions: Boolean = false var shouldInterpretActions: Boolean = false var shouldGenerateReports: Boolean = false var shouldReorderElements: Boolean = false var shouldHighlightInIde: Boolean = false fun build(factory: StepFactory): EvaluationProcess { val steps = mutableListOf<EvaluationStep>() val isTestingEnvironment = ApplicationManager.getApplication().isUnitTestMode if (!isTestingEnvironment && (shouldGenerateActions || shouldInterpretActions)) { factory.setupSdkStep()?.let { steps.add(it) } if (!Registry.`is`("evaluation.plugin.disable.sdk.check")) { steps.add(factory.checkSdkConfiguredStep()) } } if (shouldInterpretActions) { factory.setupStatsCollectorStep()?.let { steps.add(it) } steps.add(factory.setupCompletionStep()) } if (shouldGenerateActions) { steps.add(factory.generateActionsStep()) } if (shouldInterpretActions) { if (shouldGenerateActions) { steps.add(factory.interpretActionsStep()) } else { steps.add(factory.interpretActionsOnNewWorkspaceStep()) } } if (shouldReorderElements) { steps.add(factory.reorderElements()) } if (shouldHighlightInIde) { steps.add(factory.highlightTokensInIdeStep()) } if (shouldGenerateReports) { steps.add(factory.generateReportStep()) } for (step in steps.reversed()) { if (step is UndoableEvaluationStep) steps.add(step.undoStep()) } if (!isTestingEnvironment) { steps.add(factory.finishEvaluationStep()) } return EvaluationProcess(steps) } } }
apache-2.0
7a575783a20d91bb6396d300bfc78a2b
30.732673
110
0.684457
4.789238
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/providers/RootTypeBookmarkProvider.kt
8
1133
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.providers import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkProvider import com.intellij.ide.scratch.RootType import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil internal class RootTypeBookmarkProvider(private val project: Project) : BookmarkProvider { override fun getWeight() = 150 override fun getProject() = project override fun compare(bookmark1: Bookmark, bookmark2: Bookmark): Int { bookmark1 as RootTypeBookmark bookmark2 as RootTypeBookmark return StringUtil.naturalCompare(bookmark1.type.id, bookmark2.type.id) } override fun createBookmark(map: MutableMap<String, String>): RootTypeBookmark? { val id = map["root.type.id"] ?: return null return createBookmark(RootType.getAllRootTypes().firstOrNull { it.id == id }) } override fun createBookmark(context: Any?) = when (context) { is RootType -> RootTypeBookmark(this, context) else -> null } }
apache-2.0
4a796e50f2ae693d2ba0c8a4018d723d
38.068966
120
0.766108
4.196296
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/SearchNotPropertyCandidatesAction.kt
1
6631
// 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.actions.internal import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.ProgressManager.progress import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.load.java.isFromJava import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe class SearchNotPropertyCandidatesAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val psiFile = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return val desc = psiFile.findModuleDescriptor() val result = Messages.showInputDialog( KotlinBundle.message("enter.package.fqname"), KotlinBundle.message("search.for.not.property.candidates"), Messages.getQuestionIcon()) val packageDesc = try { val fqName = FqName.fromSegments(result!!.split('.')) desc.getPackage(fqName) } catch (e: Exception) { return } ProgressManager.getInstance().runProcessWithProgressSynchronously( { runReadAction { ProgressManager.getInstance().progressIndicator!!.isIndeterminate = true processAllDescriptors(packageDesc, project) } }, KotlinBundle.message("searching.for.not.property.candidates"), true, project ) } private fun processAllDescriptors(desc: DeclarationDescriptor, project: Project) { val processed = mutableSetOf<DeclarationDescriptor>() var pFunctions = 0 val matchedDescriptors = mutableSetOf<FunctionDescriptor>() fun recursive(desc: DeclarationDescriptor) { if (desc in processed) return progress( KotlinBundle.message("step.1.collecting.0.1.2", processed.size, pFunctions, matchedDescriptors.size), "$desc" ) when (desc) { is ModuleDescriptor -> recursive(desc.getPackage(FqName("java"))) is ClassDescriptor -> desc.unsubstitutedMemberScope.getContributedDescriptors { true }.forEach(::recursive) is PackageViewDescriptor -> desc.memberScope.getContributedDescriptors { true }.forEach(::recursive) is FunctionDescriptor -> { if (desc.isFromJava) { val name = desc.fqNameUnsafe.shortName().asString() if (name.length > 3 && ((name.startsWith("get") && desc.valueParameters.isEmpty() && desc.returnType != null) || (name.startsWith("set") && desc.valueParameters.size == 1)) ) { if (desc in matchedDescriptors) return matchedDescriptors += desc } } pFunctions++ return } } processed += desc } recursive(desc) val resultDescriptors = mutableSetOf<FunctionDescriptor>() matchedDescriptors.flatMapTo(resultDescriptors) { sequenceOf(it, *(it.overriddenDescriptors.toTypedArray())).asIterable() } println("Found ${resultDescriptors.size} accessors") fun PsiMethod.isTrivial(): Boolean { val t = this.text val s = t.indexOf('{') val e = t.lastIndexOf('}') return if (s != e && s != -1) t.substring(s, e).lines().size <= 3 else true } val descriptorToPsiBinding = mutableMapOf<FunctionDescriptor, PsiMethod>() var i = 0 resultDescriptors.forEach { functionDescriptor -> progress(KotlinBundle.message("step.2.0.of.1", i++, resultDescriptors.size), "$functionDescriptor") val source = DescriptorToSourceUtilsIde.getAllDeclarations(project, functionDescriptor) .filterIsInstance<PsiMethod>() .firstOrNull() ?: return@forEach val abstract = source.modifierList.hasModifierProperty(PsiModifier.ABSTRACT) if (!abstract) { if (!source.isTrivial()) { descriptorToPsiBinding[functionDescriptor] = source } } } val nonTrivial = mutableSetOf<FunctionDescriptor>() i = 0 descriptorToPsiBinding.forEach { (t, u) -> progress(KotlinBundle.message("step.3.0.of.1", i++, descriptorToPsiBinding.size), "$t") val descriptors = t.overriddenDescriptors var impl = false descriptors.forEach { val source = DescriptorToSourceUtilsIde.getAllDeclarations(project, it).filterIsInstance<PsiMethod>().firstOrNull() if (source != null) { if (source.body != null || source.hasModifierProperty(PsiModifier.ABSTRACT)) nonTrivial += it impl = true } } if (u.body != null) if (!impl) nonTrivial += t } nonTrivial.forEach(::println) println("Non trivial count: ${nonTrivial.size}") } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val presentation = e.presentation val isVisible = e.project != null && isApplicationInternalMode() presentation.isVisible = isVisible presentation.isEnabled = isVisible && e.getData(CommonDataKeys.PSI_FILE) is KtFile } }
apache-2.0
d1993d302742cdc79bab90b3599bc6ea
40.45
158
0.620118
5.512053
false
false
false
false
consoleau/kotlin-jpa-specification-dsl
src/test/kotlin/au/com/console/jpaspecificationdsl/TvShowRepository.kt
1
1900
package au.com.console.jpaspecificationdsl import org.springframework.data.jpa.domain.Specification import org.springframework.data.jpa.repository.JpaSpecificationExecutor import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.OneToMany @Repository interface TvShowRepository : CrudRepository<TvShow, Int>, JpaSpecificationExecutor<TvShow> @Entity data class TvShow( @Id @GeneratedValue val id: Int = 0, val name: String = "", val synopsis: String = "", val availableOnNetflix: Boolean = false, val releaseDate: String? = null, @OneToMany(cascade = kotlin.arrayOf(javax.persistence.CascadeType.ALL)) val starRatings: Set<StarRating> = emptySet()) @Entity data class StarRating( @Id @GeneratedValue val id: Int = 0, val stars: Int = 0) // Convenience functions (using the DSL) that make assembling queries more readable and allows for dynamic queries. // Note: these functions return null for a null input. This means that when included in // and() or or() they will be ignored as if they weren't supplied. fun hasName(name: String?): Specification<TvShow>? = name?.let { TvShow::name.equal(it) } fun availableOnNetflix(available: Boolean?): Specification<TvShow>? = available?.let { TvShow::availableOnNetflix.equal(it) } fun hasReleaseDateIn(releaseDates: List<String>?): Specification<TvShow>? = releaseDates?.let { TvShow::releaseDate.`in`(releaseDates) } fun hasKeywordIn(keywords: List<String>?): Specification<TvShow>? = keywords?.let { or(keywords.map(::hasKeyword)) } fun hasKeyword(keyword: String?): Specification<TvShow>? = keyword?.let { TvShow::synopsis.like("%$keyword%") }
apache-2.0
5e28cd3cf3e45f6a07569164e55f3514
32.333333
115
0.73
4.19426
false
false
false
false
ktorio/ktor
ktor-network/ktor-network-tls/jvmAndNix/src/io/ktor/network/tls/OID.kt
1
3106
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls import io.ktor.util.* public data class OID(public val identifier: String) { public val asArray: IntArray = identifier.split(".", " ").map { it.trim().toInt() }.toIntArray() public companion object { public val OrganizationName: OID = OID("2.5.4.10") public val OrganizationalUnitName: OID = OID("2.5.4.11") public val CountryName: OID = OID("2.5.4.6") public val CommonName: OID = OID("2.5.4.3") public val SubjectAltName: OID = OID("2.5.29.17") /** * CA OID * */ public val BasicConstraints: OID = OID("2.5.29.19") public val KeyUsage: OID = OID("2.5.29.15") public val ExtKeyUsage: OID = OID("2.5.29.37") public val ServerAuth: OID = OID("1.3.6.1.5.5.7.3.1") public val ClientAuth: OID = OID("1.3.6.1.5.5.7.3.2") /** * Encryption OID */ public val RSAEncryption: OID = OID("1 2 840 113549 1 1 1") public val ECEncryption: OID = OID("1.2.840.10045.2.1") /** * Algorithm OID */ public val ECDSAwithSHA384Encryption: OID = OID("1.2.840.10045.4.3.3") public val ECDSAwithSHA256Encryption: OID = OID("1.2.840.10045.4.3.2") public val RSAwithSHA512Encryption: OID = OID("1.2.840.113549.1.1.13") public val RSAwithSHA384Encryption: OID = OID("1.2.840.113549.1.1.12") public val RSAwithSHA256Encryption: OID = OID("1.2.840.113549.1.1.11") public val RSAwithSHA1Encryption: OID = OID("1.2.840.113549.1.1.5") /** * EC curves */ public val secp256r1: OID = OID("1.2.840.10045.3.1.7") public fun fromAlgorithm(algorithm: String): OID = when (algorithm) { "SHA1withRSA" -> RSAwithSHA1Encryption "SHA384withECDSA" -> ECDSAwithSHA384Encryption "SHA256withECDSA" -> ECDSAwithSHA256Encryption "SHA384withRSA" -> RSAwithSHA384Encryption "SHA256withRSA" -> RSAwithSHA256Encryption else -> error("Could't find OID for $algorithm") } } } /** * Converts the provided [algorithm] name from the standard Signature algorithms into the corresponding * KeyPairGenerator algorithm name. * * See the * [Signature](https://docs.oracle.com/en/java/javase/17/docs/specs/security/standard-names.html#signature-algorithms) * and * [KeyPairGenerator](https://docs.oracle.com/en/java/javase/17/docs/specs/security/standard-names.html#keypairgenerator-algorithms) * sections in the Java Security Standard Algorithm Names Specification for information about standard algorithm names. */ public fun keysGenerationAlgorithm(algorithm: String): String = when { algorithm.endsWith("ecdsa", ignoreCase = true) -> "EC" algorithm.endsWith("dsa", ignoreCase = true) -> "DSA" algorithm.endsWith("rsa", ignoreCase = true) -> "RSA" else -> error("Couldn't find KeyPairGenerator algorithm for $algorithm") }
apache-2.0
4df6c3dfeed1659491454069618cc523
39.868421
132
0.641339
3.590751
false
false
false
false
ktorio/ktor
ktor-io/jvm/src/io/ktor/utils/io/ByteChannelSequentialJVM.kt
1
7310
package io.ktor.utils.io import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import java.nio.* @Suppress("DEPRECATION", "OverridingDeprecatedMember") public class ByteChannelSequentialJVM( initial: ChunkBuffer, autoFlush: Boolean ) : ByteChannelSequentialBase(initial, autoFlush) { @Volatile private var attachedJob: Job? = null @OptIn(InternalCoroutinesApi::class) override fun attachJob(job: Job) { attachedJob?.cancel() attachedJob = job job.invokeOnCompletion(onCancelling = true) { cause -> attachedJob = null if (cause != null) { cancel(cause.unwrapCancellationException()) } } } override suspend fun writeAvailable(src: ByteBuffer): Int { val count = tryWriteAvailable(src) return when { count > 0 -> count !src.hasRemaining() -> 0 else -> writeAvailableSuspend(src) } } private suspend fun writeAvailableSuspend(src: ByteBuffer): Int { awaitAtLeastNBytesAvailableForWrite(1) return writeAvailable(src) } override suspend fun writeFully(src: ByteBuffer) { tryWriteAvailable(src) if (!src.hasRemaining()) return writeFullySuspend(src) } private suspend fun writeFullySuspend(src: ByteBuffer) { while (src.hasRemaining()) { awaitAtLeastNBytesAvailableForWrite(1) val count = tryWriteAvailable(src) afterWrite(count) } } private fun tryWriteAvailable(src: ByteBuffer): Int { val srcRemaining = src.remaining() val availableForWrite = availableForWrite val count = when { closed -> throw closedCause ?: ClosedSendChannelException("Channel closed for write") srcRemaining == 0 -> 0 srcRemaining <= availableForWrite -> { writable.writeFully(src) srcRemaining } availableForWrite == 0 -> 0 else -> { val oldLimit = src.limit() src.limit(src.position() + availableForWrite) writable.writeFully(src) src.limit(oldLimit) availableForWrite } } afterWrite(count) return count } override suspend fun readAvailable(dst: ByteBuffer): Int { val rc = tryReadAvailable(dst) if (rc != 0) return rc if (!dst.hasRemaining()) return 0 return readAvailableSuspend(dst) } override fun readAvailable(min: Int, block: (ByteBuffer) -> Unit): Int { closedCause?.let { throw it } if (availableForRead < min) { return -1 } prepareFlushedBytes() var result: Int readable.readDirect(min) { val position = it.position() block(it) result = it.position() - position } return result } private suspend fun readAvailableSuspend(dst: ByteBuffer): Int { if (!await(1)) return -1 return readAvailable(dst) } override suspend fun readFully(dst: ByteBuffer): Int { val rc = tryReadAvailable(dst) if (rc == -1) throw EOFException("Channel closed") if (!dst.hasRemaining()) return rc return readFullySuspend(dst, rc) } private suspend fun readFullySuspend(dst: ByteBuffer, rc0: Int): Int { var count = rc0 while (dst.hasRemaining()) { if (!await(1)) throw EOFException("Channel closed") val rc = tryReadAvailable(dst) if (rc == -1) throw EOFException("Channel closed") count += rc } return count } private fun tryReadAvailable(dst: ByteBuffer): Int { closedCause?.let { throw it } if (closed && availableForRead == 0) { return -1 } if (!readable.canRead()) { prepareFlushedBytes() } val count = readable.readAvailable(dst) afterRead(count) return count } @Deprecated("Use read { } instead.") override fun <R> lookAhead(visitor: LookAheadSession.() -> R): R = visitor(Session(this)) @Deprecated("Use read { } instead.") override suspend fun <R> lookAheadSuspend(visitor: suspend LookAheadSuspendSession.() -> R): R = visitor(Session(this)) private class Session(private val channel: ByteChannelSequentialJVM) : LookAheadSuspendSession { override suspend fun awaitAtLeast(n: Int): Boolean { channel.closedCause?.let { throw it } return channel.await(n) } override fun consumed(n: Int) { channel.closedCause?.let { throw it } channel.discard(n) } override fun request(skip: Int, atLeast: Int): ByteBuffer? { channel.closedCause?.let { throw it } if (channel.isClosedForRead) return null if (channel.readable.isEmpty) { channel.prepareFlushedBytes() } val head = channel.readable.head if (head.readRemaining < skip + atLeast) return null val buffer = head.memory.buffer.slice() buffer.position(head.readPosition + skip) buffer.limit(head.writePosition) return buffer } } override suspend fun read(min: Int, consumer: (ByteBuffer) -> Unit) { require(min >= 0) if (!await(min)) throw EOFException("Channel closed while $min bytes expected") readable.readDirect(min) { bb -> consumer(bb) } } /** * Suspend until the channel has bytes to read or gets closed. Throws exception if the channel was closed with an error. */ override suspend fun awaitContent() { await(1) } override fun writeAvailable(min: Int, block: (ByteBuffer) -> Unit): Int { if (closed) { throw closedCause ?: ClosedSendChannelException("Channel closed for write") } if (availableForWrite < min) { return 0 } var result: Int writable.writeDirect(min) { val position = it.position() block(it) result = it.position() - position } return result } override suspend fun write(min: Int, block: (ByteBuffer) -> Unit) { if (closed) { throw closedCause ?: ClosedSendChannelException("Channel closed for write") } awaitAtLeastNBytesAvailableForWrite(min) val count = writable.writeByteBufferDirect(min) { block(it) } afterWrite(count) } override suspend fun writeWhile(block: (ByteBuffer) -> Boolean) { while (true) { if (closed) { throw closedCause ?: ClosedSendChannelException("Channel closed for write") } var shouldContinue: Boolean awaitAtLeastNBytesAvailableForWrite(1) val result = writable.writeByteBufferDirect(1) { shouldContinue = block(it) } afterWrite(result) if (!shouldContinue) break } } }
apache-2.0
d9d5b57a579cd913abcdf2486677460a
27.779528
124
0.581395
5.062327
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/library/setting/SortDirectionSetting.kt
2
844
package eu.kanade.tachiyomi.ui.library.setting import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.preference.PreferencesHelper enum class SortDirectionSetting(val flag: Int) { ASCENDING(0b01000000), DESCENDING(0b00000000); companion object { const val MASK = 0b01000000 fun fromFlag(flag: Int?): SortDirectionSetting { return values().find { mode -> mode.flag == flag } ?: ASCENDING } fun get(preferences: PreferencesHelper, category: Category?): SortDirectionSetting { return if (preferences.categorizedDisplaySettings().get() && category != null && category.id != 0) { fromFlag(category.sortDirection) } else { preferences.librarySortingAscending().get() } } } }
apache-2.0
8ca836593c53f8df652805141ce29ab0
32.76
112
0.649289
4.688889
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/MixinTargetInspection.kt
1
1239
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MIXIN import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiClass import com.intellij.psi.PsiElementVisitor class MixinTargetInspection : MixinInspection() { override fun getStaticDescription() = "A Mixin class must target either one or more classes or provide one or more string targets" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitClass(psiClass: PsiClass) { val mixin = psiClass.modifierList?.findAnnotation(MIXIN) ?: return // Check if @Mixin annotation has any targets defined if (mixin.findDeclaredAttributeValue("value") == null && mixin.findDeclaredAttributeValue("targets") == null) { holder.registerProblem(mixin, "@Mixin is missing a valid target class") } } } }
mit
bceddbb4d948a1f842b0af1c66321a91
33.416667
134
0.727199
4.897233
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/interaction/Pointer.kt
1
1189
package net.pureal.traits.interaction import net.pureal.traits.* trait Pointer { val moved: Observable<Pointer> val location: Vector2 fun relativeTo(transform: Transform2): Pointer = object : Pointer { override val moved: Observable<Pointer> = observable([email protected]) { this@Pointer } override val location: Vector2 = transform([email protected]) } } trait PointerKey { val pointer: Pointer val key: Key } fun pointerKey(pointer: Pointer, key: Key): PointerKey = object : PointerKey { override val pointer = pointer override val key = key } trait PointerKeys { val pointer: Pointer val keys: Iterable<Key> val pressed: Observable<PointerKey> val released: Observable<PointerKey> } fun pointerKeys(pointer: Pointer, keys: Iterable<Key>) = object : PointerKeys { override val pointer = pointer override val keys = keys override val pressed = observable((keys map { it.pressed })) { pointerKey(pointer, it) } override val released = observable((keys map { it.released })) { pointerKey(pointer, it) } } trait Scroll { val scrolled: Observable<Number> }
bsd-3-clause
ba7dfb9df4e07e62c8f3ce9a7564c308
27.775
97
0.680404
4.1
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/Light.kt
1
2054
package graphics.scenery import graphics.scenery.utils.extensions.plus import graphics.scenery.utils.extensions.times import org.joml.Vector3f import kotlin.math.sqrt import kotlin.reflect.full.createInstance /** * Abstract class for light [Node]s. * * @author Ulrik Guenther <[email protected]> */ abstract class Light(name: String = "Light") : Mesh(name) { /** Enum class to determine light type. */ enum class LightType { PointLight, DirectionalLight } /** Emission color of the light. */ @ShaderProperty abstract var emissionColor: Vector3f /** Intensity of the light. */ @ShaderProperty abstract var intensity: Float /** The light's type, stored as [LightType]. */ @ShaderProperty abstract val lightType: LightType companion object { /** * Creates a tetrahedron lights of type [T] and returns them as a list. * The [center] of the tetrahedron can be specified, as can be the [spread] of it, the light's [intensity], [color], and [radius]. */ inline fun <reified T: Light> createLightTetrahedron(center: Vector3f = Vector3f(0.0f), spread: Float = 1.0f, intensity: Float = 1.0f, color: Vector3f = Vector3f(1.0f), radius: Float = 5.0f): List<T> { val tetrahedron = listOf( Vector3f(1.0f, 0f, -1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(-1.0f,0f,-1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(0.0f,1.0f,1.0f/ sqrt(2.0).toFloat()) * spread, Vector3f(0.0f,-1.0f,1.0f/ sqrt(2.0).toFloat()) * spread) return tetrahedron.map { position -> val light = T::class.createInstance() light.spatial { this.position = position + center } light.emissionColor = color light.intensity = intensity if(light is PointLight) { light.lightRadius = radius } light } } } }
lgpl-3.0
065fce48f4997f545842d01915f90315
33.233333
210
0.5852
3.860902
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/actions/TranslationSortOrderDialog.kt
1
3436
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.actions import com.demonwav.mcdev.i18n.sorting.Ordering import java.awt.Component import java.awt.event.KeyEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import javax.swing.DefaultComboBoxModel import javax.swing.DefaultListCellRenderer import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JComponent import javax.swing.JDialog import javax.swing.JList import javax.swing.JPanel import javax.swing.JSpinner import javax.swing.KeyStroke import javax.swing.SpinnerNumberModel import javax.swing.WindowConstants class TranslationSortOrderDialog(excludeDefaultOption: Boolean, defaultSelection: Ordering) : JDialog() { private lateinit var contentPane: JPanel private lateinit var buttonOK: JButton private lateinit var buttonCancel: JButton private lateinit var comboSelection: JComboBox<Ordering> private lateinit var spinnerComments: JSpinner init { setContentPane(contentPane) isModal = true title = "Select Sort Order" getRootPane().defaultButton = buttonOK buttonOK.addActionListener { onOK() } buttonCancel.addActionListener { onCancel() } spinnerComments.model = SpinnerNumberModel(0, 0, Int.MAX_VALUE, 1) val availableOrderings = if (excludeDefaultOption) NON_DEFAULT_ORDERINGS else ALL_ORDERINGS comboSelection.model = DefaultComboBoxModel(availableOrderings) comboSelection.renderer = CellRenderer comboSelection.selectedItem = defaultSelection // call onCancel() when cross is clicked defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE addWindowListener( object : WindowAdapter() { override fun windowClosing(e: WindowEvent?) { onCancel() } } ) // call onCancel() on ESCAPE contentPane.registerKeyboardAction({ onCancel() }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) } private fun onOK() { dispose() } private fun onCancel() { comboSelection.selectedIndex = -1 dispose() } object CellRenderer : DefaultListCellRenderer() { override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { val displayValue = (value as? Ordering)?.text return super.getListCellRendererComponent(list, displayValue, index, isSelected, cellHasFocus) } } companion object { private val ALL_ORDERINGS = Ordering.values() private val NON_DEFAULT_ORDERINGS = Ordering.values() .filterNot { it == Ordering.LIKE_DEFAULT }.toTypedArray() fun show(excludeDefaultOption: Boolean, defaultSelection: Ordering): Pair<Ordering?, Int> { val dialog = TranslationSortOrderDialog(excludeDefaultOption, defaultSelection) dialog.pack() dialog.setLocationRelativeTo(dialog.owner) dialog.isVisible = true val order = dialog.comboSelection.selectedItem as? Ordering val comments = dialog.spinnerComments.value as Int return (order to comments) } } }
mit
1a605f74c678c75187be99b83cc76423
34.42268
152
0.697614
5.198185
false
false
false
false
google/android-fhir
engine/src/main/java/com/google/android/fhir/db/impl/entities/QuantityIndexEntity.kt
1
1607
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.db.impl.entities import androidx.room.Embedded import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import com.google.android.fhir.index.entities.QuantityIndex import java.util.UUID import org.hl7.fhir.r4.model.ResourceType @Entity( indices = [ Index(value = ["resourceType", "index_name", "index_value", "index_code"]), // keep this index for faster foreign lookup Index(value = ["resourceUuid"])], foreignKeys = [ ForeignKey( entity = ResourceEntity::class, parentColumns = ["resourceUuid"], childColumns = ["resourceUuid"], onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.NO_ACTION, deferred = true )] ) internal data class QuantityIndexEntity( @PrimaryKey(autoGenerate = true) val id: Long, val resourceUuid: UUID, val resourceType: ResourceType, @Embedded(prefix = "index_") val index: QuantityIndex )
apache-2.0
a11ee7ec663a59ade54cf66918542d2c
31.14
81
0.714375
4.195822
false
false
false
false