repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
kronenpj/iqtimesheet
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/SectionFragment.kt
1
14005
package com.github.kronenpj.iqtimesheet.IQTimeSheet import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.Button import android.widget.ListView import android.widget.TextView import com.github.kronenpj.iqtimesheet.TimeHelpers /** * A fragment representing a section of the application. */ class SectionFragment : Fragment() { /* * (non-Javadoc) * * @see com.github.rtyley.android.sherlock.roboguice.activity. * RoboFragmentActivity#onCreateView(LayoutInflater, ViewGroup, * Bundle) */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { Log.d(TAG, "in onCreateView (SectionFragment)") when (arguments!!.getInt(ARG_SECTION_NUMBER)) { 1 -> return setupTaskListFragment(inflater, container!!) 2 -> return setupDayReportFragment(inflater, container!!) 3 -> return setupWeekReportFragment(inflater, container!!) } return null } /** * Set up the task list fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupTaskListFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupTaskListFragment") val db = TimeSheetDbAdapter(activity!!.applicationContext) val rootView = inflater.inflate(R.layout.fragment_tasklist, container, false) val myTaskList = rootView.findViewById<ListView>(R.id.tasklistfragment) // Populate the ListView with an array adapter with the task items. (activity as TimeSheetActivity).refreshTaskListAdapter(myTaskList) // Make list items selectable. myTaskList.isEnabled = true myTaskList.choiceMode = ListView.CHOICE_MODE_SINGLE (activity as TimeSheetActivity).setSelected(myTaskList) registerForContextMenu(myTaskList) myTaskList.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val taskName = parent.getItemAtPosition(position) as String val taskID = db.getTaskIDByName(taskName) Log.i(TAG, "Processing change for task: $taskName / $taskID") if (db.processChange(taskID)) { val timeIn = db.timeInForLastClockEntry() (activity as TimeSheetActivity).startNotification(db.getTaskNameByID(taskID)!!, timeIn) (activity as TimeSheetActivity).setSelected() } else { (activity as TimeSheetActivity).clearSelected(myTaskList) Log.d(TAG, "Closed task ID: $taskID") (activity as TimeSheetActivity).stopNotification() } } // This can't be closed because of the onItemClickListener routine // above. // This probably leaks something, but I'll deal with that later. // TODO: See if not closing the DB causes problems.. // try { // db.close(); // } catch (Exception e) { // Log.i(TAG, "setupTaskListFragment db.close: " + e.toString()); // } return rootView } /** * Set up the day report fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupDayReportFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupDayReportFragment") //val db = TimeSheetDbAdapter(activity.applicationContext) //try { // db.open(); //} catch (Exception e) { // Log.i(TAG, "Database open threw exception" + e); //} val rootView = inflater.inflate(R.layout.fragment_reportlist, container, false) val reportList = rootView.findViewById(R.id.reportList) as ListView (activity as TimeSheetActivity).refreshReportListAdapter(reportList) val footerView = rootView.findViewById(R.id.reportfooter) as TextView try { footerView.textSize = TimeSheetActivity.prefs!!.totalsFontSize } catch (e: NullPointerException) { Log.d(TAG, "setupDayReportFragment: NullPointerException prefs: $e") } val child = arrayOf(rootView.findViewById(R.id.previous) as Button, rootView.findViewById(R.id.today) as Button, rootView.findViewById(R.id.next) as Button) /** * This method is what is registered with the button to cause an * action to occur when it is pressed. */ val mButtonListener = View.OnClickListener { v -> Log.d(TAG, "onClickListener view id: " + v.id) when (v.id) { R.id.previous -> { Log.d(TAG, "onClickListener button: previous") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") if (TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day) != TimeSheetActivity.prefs!!.weekStartDay) { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { if (TimeHelpers.millisToHour(TimeSheetActivity.day) < TimeSheetActivity.prefs!!.weekStartHour) { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { TimeSheetActivity.day = TimeHelpers.millisToStartOfDay(TimeSheetActivity.day) + TimeSheetActivity.prefs!!.weekStartHour * 3600 * 1000 - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } } R.id.today -> { Log.d(TAG, "onClickListener button: today") TimeSheetActivity.day = TimeHelpers.millisNow() } R.id.next -> { Log.d(TAG, "onClickListener button: next") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") if (TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day) != TimeSheetActivity.prefs!!.weekStartDay) { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { if (TimeHelpers.millisToHour(TimeSheetActivity.day) > TimeSheetActivity.prefs!!.weekStartHour) { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } else { TimeSheetActivity.day = TimeHelpers.millisToEndOfDay(TimeSheetActivity.day) + (TimeSheetActivity.prefs!!.weekStartHour * 3600 * 1000).toLong() + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } } } val headerView = v.rootView .findViewById(R.id.reportheader) as TextView val date = TimeHelpers.millisToDate(TimeSheetActivity.day) headerView.text = "Day Report - $date" Log.d(TAG, "New day is: $date") (activity as TimeSheetActivity).refreshReportListAdapter(v.rootView .findViewById(R.id.reportList) as ListView) } for (aChild in child) { try { aChild.setOnClickListener(mButtonListener) } catch (e: NullPointerException) { Log.e(TAG, "setOnClickListener: $e") } } return rootView } /** * Set up the week report fragment. * @param inflater The inflater given the task of instantiating the view. * * * @param container The view group into which the view will be inflated. * * * @return The inflated view. */ private fun setupWeekReportFragment(inflater: LayoutInflater, container: ViewGroup): View { Log.d(TAG, "in setupWeekReportFragment") //val db = TimeSheetDbAdapter(activity.applicationContext) //try { // db.open(); //} catch (Exception e) { // Log.i(TAG, "Database open threw exception" + e); //} val rootView = inflater.inflate(R.layout.fragment_weekreportlist, container, false) val reportList = rootView.findViewById(R.id.weekList) as ListView (activity as TimeSheetActivity).refreshWeekReportListAdapter(reportList) val footerView = rootView.findViewById(R.id.weekfooter) as TextView try { footerView.textSize = TimeSheetActivity.prefs!!.totalsFontSize } catch (e: NullPointerException) { Log.d(TAG, "setupWeekeportFragment: NullPointerException prefs: $e") } val child = arrayOf(rootView.findViewById(R.id.wprevious) as Button, rootView.findViewById(R.id.wtoday) as Button, rootView.findViewById(R.id.wnext) as Button) /** * This method is what is registered with the button to cause an * action to occur when it is pressed. */ val mButtonListener = View.OnClickListener { v -> Log.d(TAG, "onClickListener view id: " + v.id) when (v.id) { R.id.wprevious -> { Log.d(TAG, "onClickListener button: wprevious") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") // TimeSheetActivity.day = TimeHelpers.millisToStartOfWeek(TimeSheetActivity.day) - 1000; TimeSheetActivity.day = TimeHelpers.millisToStartOfWeek(TimeSheetActivity.day, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) - 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } R.id.wtoday -> { TimeSheetActivity.day = TimeHelpers.millisNow() Log.d(TAG, "onClickListener button: wtoday") } R.id.wnext -> { Log.d(TAG, "onClickListener button: wnext") Log.d(TAG, "onClickListener Day of week #: ${TimeHelpers.millisToDayOfWeek(TimeSheetActivity.day)}") Log.d(TAG, "onClickListener Preference #: ${TimeSheetActivity.prefs!!.weekStartDay}") Log.d(TAG, "onClickListener Previous date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") // TimeSheetActivity.day = TimeHelpers.millisToEndOfWeek(TimeSheetActivity.day) + 1000; TimeSheetActivity.day = TimeHelpers.millisToEndOfWeek(TimeSheetActivity.day, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) + 1000 Log.d(TAG, "onClickListener New date: ${TimeHelpers.millisToTimeDate(TimeSheetActivity.day)}") } } val headerView = v.rootView .findViewById(R.id.weekheader) as TextView val date = TimeHelpers.millisToDate(TimeSheetActivity.day) headerView.text = "Week Report - $date" Log.d(TAG, "New day is: $date") (activity as TimeSheetActivity).refreshWeekReportListAdapter(v.rootView .findViewById(R.id.weekList) as ListView) } for (aChild in child) { try { aChild.setOnClickListener(mButtonListener) } catch (e: NullPointerException) { Log.e(TAG, "setOnClickListener: $e") } } return rootView } companion object { private const val TAG = "SectionFragment" /** * The fragment argument representing the section number for this * fragment. */ const val ARG_SECTION_NUMBER = "section_number" } }
apache-2.0
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt
1
17094
package info.nightscout.androidaps.plugins.general.nsclient import android.content.Context import android.os.SystemClock import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.DeviceStatus import info.nightscout.androidaps.database.transactions.* import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.DataSyncSelector.* import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject class NSClientAddAckWorker( context: Context, params: WorkerParameters ) : Worker(context, params) { @Inject lateinit var dataWorker: DataWorker @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var repository: AppRepository @Inject lateinit var rxBus: RxBus @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP override fun doWork(): Result { var ret = Result.success() val ack = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as NSAddAck? ?: return Result.failure(workDataOf("Error" to "missing input data")) if (sp.getBoolean(R.string.key_ns_sync_slow, false)) SystemClock.sleep(1000) when (ack.originalObject) { is PairTemporaryTarget -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTemporaryTargetTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryTarget failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TemporaryTarget " + pair.value) dataSyncSelector.confirmLastTempTargetsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TemporaryTarget " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTempTargetsCompat() } is PairGlucoseValue -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdGlucoseValueTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of GlucoseValue failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of GlucoseValue " + pair.value) dataSyncSelector.confirmLastGlucoseValueIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked GlucoseValue " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedGlucoseValuesCompat() } is PairFood -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdFoodTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Food failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Food " + pair.value) dataSyncSelector.confirmLastFoodIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Food " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedFoodsCompat() } is PairTherapyEvent -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTherapyEventTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TherapyEvent failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TherapyEvent " + pair.value) dataSyncSelector.confirmLastTherapyEventIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TherapyEvent " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTherapyEventsCompat() } is PairBolus -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Bolus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Bolus " + pair.value) dataSyncSelector.confirmLastBolusIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Bolus " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedBolusesCompat() } is PairCarbs -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdCarbsTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Carbs failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of Carbs " + pair.value) dataSyncSelector.confirmLastCarbsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked Carbs " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedCarbsCompat() } is PairBolusCalculatorResult -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdBolusCalculatorResultTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of BolusCalculatorResult failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of BolusCalculatorResult " + pair.value) dataSyncSelector.confirmLastBolusCalculatorResultsIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked BolusCalculatorResult " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedBolusCalculatorResultsCompat() } is PairTemporaryBasal -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdTemporaryBasalTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryBasal failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of TemporaryBasal " + pair.value) dataSyncSelector.confirmLastTemporaryBasalIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked TemporaryBasal " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedTemporaryBasalsCompat() } is PairExtendedBolus -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdExtendedBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ExtendedBolus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of ExtendedBolus " + pair.value) dataSyncSelector.confirmLastExtendedBolusIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ExtendedBolus " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedExtendedBolusesCompat() } is PairProfileSwitch -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdProfileSwitchTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ProfileSwitch failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of ProfileSwitch " + pair.value) dataSyncSelector.confirmLastProfileSwitchIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ProfileSwitch " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedProfileSwitchesCompat() } is PairEffectiveProfileSwitch -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdEffectiveProfileSwitchTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of EffectiveProfileSwitch failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of EffectiveProfileSwitch " + pair.value) dataSyncSelector.confirmLastEffectiveProfileSwitchIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked EffectiveProfileSwitch " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedEffectiveProfileSwitchesCompat() } is DeviceStatus -> { val deviceStatus = ack.originalObject deviceStatus.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdDeviceStatusTransaction(deviceStatus)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of DeviceStatus failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to deviceStatus.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of DeviceStatus $deviceStatus") dataSyncSelector.confirmLastDeviceStatusIdIfGreater(deviceStatus.id) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked DeviceStatus " + deviceStatus.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedDeviceStatusesCompat() } is PairProfileStore -> { dataSyncSelector.confirmLastProfileStore(ack.originalObject.timestampSync) rxBus.send(EventNSClientNewLog("DBADD", "Acked ProfileStore " + ack.id)) } is PairOfflineEvent -> { val pair = ack.originalObject pair.value.interfaceIDs.nightscoutId = ack.id repository.runTransactionForResult(UpdateNsIdOfflineEventTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of OfflineEvent failed", error) ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of OfflineEvent " + pair.value) dataSyncSelector.confirmLastOfflineEventIdIfGreater(pair.updateRecordId) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked OfflineEvent " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting dataSyncSelector.processChangedOfflineEventsCompat() } } return ret } init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) } }
agpl-3.0
saletrak/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/textview/TextViewExtensions.kt
1
709
package io.github.feelfreelinux.wykopmobilny.utils.textview import android.text.SpannableStringBuilder import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.widget.TextView import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi fun TextView.prepareBody(html: String, handler : WykopLinkHandlerApi) { val sequence = html.toSpannable() val strBuilder = SpannableStringBuilder(sequence) val urls = strBuilder.getSpans(0, strBuilder.length, URLSpan::class.java) urls.forEach { span -> strBuilder.makeLinkClickable(span, handler) } text = strBuilder movementMethod = LinkMovementMethod.getInstance() }
mit
exponentjs/exponent
packages/expo-sqlite/android/src/main/java/expo/modules/sqlite/SQLiteModule.kt
2
5369
// Copyright 2015-present 650 Industries. All rights reserved. package expo.modules.sqlite import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import expo.modules.core.ExportedModule import expo.modules.core.Promise import expo.modules.core.interfaces.ExpoMethod import java.io.File import java.io.IOException import java.util.* private val TAG = SQLiteModule::class.java.simpleName private val EMPTY_ROWS = arrayOf<Array<Any?>>() private val EMPTY_COLUMNS = arrayOf<String?>() private val EMPTY_RESULT = SQLiteModule.SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null) private val DATABASES: MutableMap<String, SQLiteDatabase?> = HashMap() class SQLiteModule(private val mContext: Context) : ExportedModule(mContext) { override fun getName(): String { return "ExponentSQLite" } @ExpoMethod fun exec(dbName: String, queries: ArrayList<ArrayList<Any>>, readOnly: Boolean, promise: Promise) { try { val db = getDatabase(dbName) val results = queries.map { sqlQuery -> val sql = sqlQuery[0] as String val bindArgs = convertParamsToStringArray(sqlQuery[1] as ArrayList<Any?>) try { if (isSelect(sql)) { doSelectInBackgroundAndPossiblyThrow(sql, bindArgs, db) } else { // update/insert/delete if (readOnly) { SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, ReadOnlyException()) } else { doUpdateInBackgroundAndPossiblyThrow(sql, bindArgs, db) } } } catch (e: Throwable) { SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e) } } val data = pluginResultsToPrimitiveData(results) promise.resolve(data) } catch (e: Exception) { promise.reject("SQLiteError", e) } } @ExpoMethod fun close(dbName: String, promise: Promise) { DATABASES .remove(dbName) ?.close() promise.resolve(null) } // do a update/delete/insert operation private fun doUpdateInBackgroundAndPossiblyThrow( sql: String, bindArgs: Array<String?>?, db: SQLiteDatabase ): SQLitePluginResult { return db.compileStatement(sql).use { statement -> if (bindArgs != null) { for (i in bindArgs.size downTo 1) { if (bindArgs[i - 1] == null) { statement.bindNull(i) } else { statement.bindString(i, bindArgs[i - 1]) } } } if (isInsert(sql)) { val insertId = statement.executeInsert() val rowsAffected = if (insertId >= 0) 1 else 0 SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null) } else if (isDelete(sql) || isUpdate(sql)) { val rowsAffected = statement.executeUpdateDelete() SQLitePluginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null) } else { // in this case, we don't need rowsAffected or insertId, so we can have a slight // perf boost by just executing the query statement.execute() EMPTY_RESULT } } } // do a select operation private fun doSelectInBackgroundAndPossiblyThrow( sql: String, bindArgs: Array<String?>, db: SQLiteDatabase ): SQLitePluginResult { return db.rawQuery(sql, bindArgs).use { cursor -> val numRows = cursor.count if (numRows == 0) { return EMPTY_RESULT } val numColumns = cursor.columnCount val columnNames = cursor.columnNames val rows: Array<Array<Any?>> = Array(numRows) { arrayOfNulls(numColumns) } var i = 0 while (cursor.moveToNext()) { val row = rows[i] for (j in 0 until numColumns) { row[j] = getValueFromCursor(cursor, j, cursor.getType(j)) } rows[i] = row i++ } SQLitePluginResult(rows, columnNames, 0, 0, null) } } private fun getValueFromCursor(cursor: Cursor, index: Int, columnType: Int): Any? { return when (columnType) { Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(index) Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(index) Cursor.FIELD_TYPE_BLOB -> // convert byte[] to binary string; it's good enough, because // WebSQL doesn't support blobs anyway String(cursor.getBlob(index)) Cursor.FIELD_TYPE_STRING -> cursor.getString(index) else -> null } } @Throws(IOException::class) private fun pathForDatabaseName(name: String): String { val directory = File("${mContext.filesDir}${File.separator}SQLite") ensureDirExists(directory) return "$directory${File.separator}$name" } @Throws(IOException::class) private fun getDatabase(name: String): SQLiteDatabase { var database: SQLiteDatabase? = null val path = pathForDatabaseName(name) if (File(path).exists()) { database = DATABASES[name] } if (database == null) { DATABASES.remove(name) database = SQLiteDatabase.openOrCreateDatabase(path, null) DATABASES[name] = database } return database!! } internal class SQLitePluginResult( val rows: Array<Array<Any?>>, val columns: Array<String?>, val rowsAffected: Int, val insertId: Long, val error: Throwable? ) private class ReadOnlyException : Exception("could not prepare statement (23 not authorized)") }
bsd-3-clause
jgrandja/spring-security
config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/ContentSecurityPolicyDslTests.kt
2
4247
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.servlet.headers import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.web.servlet.invoke import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get /** * Tests for [ContentSecurityPolicyDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ContentSecurityPolicyDslTests { @JvmField val spring = SpringTestContext(this) @Autowired lateinit var mockMvc: MockMvc @Test fun `headers when content security policy configured then header in response`() { this.spring.register(ContentSecurityPolicyConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'") } } } @EnableWebSecurity open class ContentSecurityPolicyConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { } } } } } @Test fun `headers when content security policy configured with custom policy directives then custom directives in header`() { this.spring.register(CustomPolicyDirectivesConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, "default-src 'self'; script-src trustedscripts.example.com") } } } @EnableWebSecurity open class CustomPolicyDirectivesConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { policyDirectives = "default-src 'self'; script-src trustedscripts.example.com" } } } } } @Test fun `headers when report only content security policy report only header in response`() { this.spring.register(ReportOnlyConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY_REPORT_ONLY, "default-src 'self'") } } } @EnableWebSecurity open class ReportOnlyConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true contentSecurityPolicy { reportOnly = true } } } } } }
apache-2.0
Adventech/sabbath-school-android-2
features/settings/src/main/java/com/cryart/sabbathschool/settings/SSSettingsFragment.kt
1
2737
/* * Copyright (c) 2021. Adventech <[email protected]> * * 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.cryart.sabbathschool.settings import android.content.SharedPreferences import android.os.Bundle import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.model.AppConfig import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class SSSettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { @Inject lateinit var dailyReminder: DailyReminder @Inject lateinit var appConfig: AppConfig override fun onResume() { super.onResume() preferenceManager.sharedPreferences?.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceManager.sharedPreferences?.unregisterOnSharedPreferenceChangeListener(this) } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.ss_settings) val aboutPref = findPreference<Preference>(getString(R.string.ss_settings_version_key)) aboutPref?.summary = appConfig.version } override fun onSharedPreferenceChanged(pref: SharedPreferences?, key: String?) { when (key) { SSConstants.SS_SETTINGS_REMINDER_ENABLED_KEY, SSConstants.SS_SETTINGS_REMINDER_TIME_KEY -> { dailyReminder.reSchedule() } } } companion object { fun newInstance(): SSSettingsFragment = SSSettingsFragment() } }
mit
PolymerLabs/arcs
javatests/arcs/android/systemhealth/testapp/TestEntity.kt
1
5415
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.android.systemhealth.testapp import arcs.core.data.FieldType import arcs.core.data.RawEntity import arcs.core.data.Schema import arcs.core.data.SchemaFields import arcs.core.data.SchemaName import arcs.core.data.SchemaRegistry import arcs.core.entity.SingletonProperty import arcs.core.storage.RawReference import arcs.core.storage.keys.DatabaseStorageKey import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.storage.referencemode.ReferenceModeStorageKey import arcs.sdk.Entity import arcs.sdk.EntityBase import arcs.sdk.EntitySpec interface TestEntitySlice : Entity { var text: String var number: Double var boolean: Boolean var inlineEntity: InlineTestEntity } class TestEntity( text: String = "", number: Double = 0.0, boolean: Boolean = false, inlineText: String = "", var rawReference: RawReference? = null, val id: String? = null ) : EntityBase("TestEntity", SCHEMA, id), TestEntitySlice { override var text: String by SingletonProperty(this) override var number: Double by SingletonProperty(this) override var boolean: Boolean by SingletonProperty(this) override var inlineEntity: InlineTestEntity by SingletonProperty(this) init { this.text = text this.number = number this.boolean = boolean this.inlineEntity = InlineTestEntity(inlineText) } companion object : EntitySpec<TestEntity> { private const val schemaHash = "abcdef" override val SCHEMA = Schema( setOf(SchemaName("TestEntity")), SchemaFields( singletons = mapOf( "text" to FieldType.Text, "number" to FieldType.Number, "boolean" to FieldType.Boolean, "inlineEntity" to FieldType.InlineEntity(InlineTestEntity.SCHEMA_HASH), "reference" to FieldType.EntityRef(schemaHash) ), collections = emptyMap() ), schemaHash ) init { SchemaRegistry.register(SCHEMA) } override fun deserialize(data: RawEntity) = TestEntity().apply { deserialize( data, mapOf( schemaHash to TestEntity, InlineTestEntity.SCHEMA_HASH to InlineTestEntity ) ) } val singletonInMemoryStorageKey = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("singleton_reference"), storageKey = RamDiskStorageKey("singleton") ) val singletonMemoryDatabaseStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Memory( "singleton_reference", "arcs_test" ), storageKey = DatabaseStorageKey.Memory("singleton", "arcs_test") ) val singletonPersistentStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Persistent( "singleton_reference", "arcs_test" ), storageKey = DatabaseStorageKey.Persistent("singleton", "arcs_test") ) val collectionInMemoryStorageKey = ReferenceModeStorageKey( backingKey = RamDiskStorageKey("collection_reference"), storageKey = RamDiskStorageKey("collection") ) val collectionMemoryDatabaseStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Memory( "collection_reference", "arcs_test" ), storageKey = DatabaseStorageKey.Memory("collection", "arcs_test") ) val collectionPersistentStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Persistent( "collection_reference", "arcs_test" ), storageKey = DatabaseStorageKey.Persistent("collection", "arcs_test") ) val clearEntitiesMemoryDatabaseStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Memory( "cleared_entities_backing", "arcs_test" ), storageKey = DatabaseStorageKey.Memory( "cleared_entities_container", "arcs_test" ) ) val clearEntitiesPersistentStorageKey = ReferenceModeStorageKey( backingKey = DatabaseStorageKey.Persistent( "cleared_entities_backing", "arcs_test" ), storageKey = DatabaseStorageKey.Persistent( "cleared_entities_container", "arcs_test" ) ) const val text = "Test Text" const val number = 1234.0 const val boolean = true } enum class StorageMode { IN_MEMORY, PERSISTENT, MEMORY_DATABASE } } class InlineTestEntity( text: String = "" ) : EntityBase(ENTITY_CLASS_NAME, SCHEMA, isInlineEntity = true) { var text: String? by SingletonProperty(this) init { this.text = text } companion object : EntitySpec<InlineTestEntity> { const val ENTITY_CLASS_NAME = "InlineTestEntity" const val SCHEMA_HASH = "inline_abcdef" override val SCHEMA = Schema( names = setOf(SchemaName(ENTITY_CLASS_NAME)), fields = SchemaFields( singletons = mapOf( "text" to FieldType.Text ), collections = emptyMap() ), hash = SCHEMA_HASH ) init { SchemaRegistry.register(SCHEMA) } override fun deserialize(data: RawEntity) = InlineTestEntity().apply { deserialize(data) } } }
bsd-3-clause
PolymerLabs/arcs
javatests/arcs/showcase/inline/ArcsStorage.kt
1
1309
package arcs.showcase.inline import arcs.android.integration.IntegrationEnvironment import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout /** Container for WriteRecipe specific things */ @OptIn(ExperimentalCoroutinesApi::class) class ArcsStorage(private val env: IntegrationEnvironment) { // This is a helper for public methods to dispatcher the suspend calls onto a coroutine and // wait for the result, and to wrap the suspend methods in a timeout, converting a potential // test timeout into a more specific test failure. private inline fun <T> run(crossinline block: suspend () -> T) = runBlocking { withTimeout(30000) { block() } } fun all0(): List<MyLevel0> = run { env.getParticle<Reader0>(WriteRecipePlan).read() } fun put0(item: MyLevel0) = run { env.getParticle<Writer0>(WriteRecipePlan).write(item) } fun all1(): List<MyLevel1> = run { env.getParticle<Reader1>(WriteRecipePlan).read() } fun put1(item: MyLevel1) = run { env.getParticle<Writer1>(WriteRecipePlan).write(item) } fun all2(): List<MyLevel2> = run { env.getParticle<Reader2>(WriteRecipePlan).read() } fun put2(item: MyLevel2) = run { env.getParticle<Writer2>(WriteRecipePlan).write(item) } }
bsd-3-clause
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/scroll/MotionScrollFirstScreenLineStartAction.kt
1
1161
/* * 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.action.motion.scroll import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class MotionScrollFirstScreenLineStartAction : VimActionHandler.SingleExecution() { override val type: Command.Type = Command.Type.OTHER_READONLY override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_IGNORE_SCROLL_JUMP) override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { return injector.motion.scrollCurrentLineToDisplayTop(editor, cmd.rawCount, true) } }
mit
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimCaretListener.kt
1
312
/* * 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 interface VimCaretListener { fun caretRemoved(caret: VimCaret?) }
mit
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/modal/ModalFragment.kt
1
291
package org.hexworks.zircon.api.component.modal import org.hexworks.zircon.api.component.Fragment /** * A [ModalFragment] is a [Fragment] that is provided for convenience * and wraps a [Modal]. */ interface ModalFragment<T : ModalResult> : Fragment { override val root: Modal<T> }
apache-2.0
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/action/copy/YankVisualLinesActionTest.kt
1
2896
/* * 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 org.jetbrains.plugins.ideavim.action.copy import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.VimStateMachine import junit.framework.TestCase import org.jetbrains.plugins.ideavim.VimTestCase /** * @author Alex Plate */ class YankVisualLinesActionTest : VimTestCase() { fun `test from visual mode`() { val text = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val yankedTest = """ I found it in a legendary land all rocks and lavender and tufted grass, """.trimIndent() configureByText(text) typeText(injector.parser.parseKeys("vjY")) val savedText = VimPlugin.getRegister().lastRegister?.text ?: kotlin.test.fail() TestCase.assertEquals(yankedTest, savedText) } fun `test from visual mode till the end`() { val text = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, where it was sett${c}led on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val textAfter = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c}where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest("vjY", text, textAfter, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) val yankedTest = """ where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val savedText = VimPlugin.getRegister().lastRegister?.text ?: kotlin.test.fail() TestCase.assertEquals(yankedTest, savedText) } fun `test from line visual mode`() { val text = """ A Discovery I found it in a ${c}legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val yankedTest = """ I found it in a legendary land all rocks and lavender and tufted grass, """.trimIndent() configureByText(text) typeText(injector.parser.parseKeys("VjY")) val savedText = VimPlugin.getRegister().lastRegister?.text ?: kotlin.test.fail() TestCase.assertEquals(yankedTest, savedText) } }
mit
blindpirate/gradle
subprojects/docs/src/samples/templates/structuring-software-projects/android-app/app/src/main/java/com/example/myproduct/app/MyProductAppActivity.kt
3
1676
package com.example.myproduct.app import android.app.Activity import android.os.AsyncTask import android.os.Bundle import android.text.Html import android.text.method.LinkMovementMethod import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import com.example.myproduct.user.table.TableBuilder class MyProductAppActivity : Activity() { class DownloadTask: AsyncTask<Void, Void, List<MutableList<String>>>() { override fun doInBackground(vararg params: Void): List<MutableList<String>> { return TableBuilder.build() } override fun onPostExecute(result: List<MutableList<String>>) { } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val data = DownloadTask().execute().get() val scrollView = ScrollView(this) val table = TableLayout(this) scrollView.addView(table); data.forEach { rowData -> val row = TableRow(this@MyProductAppActivity) rowData.forEach { cellData -> row.addView(TextView(this@MyProductAppActivity).apply { setPadding(6, 6, 6, 6) if (cellData.contains("https://")) { movementMethod = LinkMovementMethod.getInstance() text = Html.fromHtml("<a href='$cellData'>$cellData</a>", Html.FROM_HTML_MODE_LEGACY) } else { text = cellData } }) } table.addView(row) } setContentView(scrollView) } }
apache-2.0
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/scan/SearchSuccessCallback.kt
1
3563
package org.ligi.passandroid.scan import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import androidx.core.app.NotificationCompat import androidx.core.graphics.scale import org.ligi.passandroid.R import org.ligi.passandroid.model.PassBitmapDefinitions import org.ligi.passandroid.model.PassStore import org.ligi.passandroid.model.pass.Pass import org.ligi.passandroid.ui.PassViewActivity import org.ligi.passandroid.ui.PassViewActivityBase import org.ligi.passandroid.ui.UnzipPassController import org.threeten.bp.ZonedDateTime import java.io.File internal class SearchSuccessCallback(private val context: Context, private val passStore: PassStore, private val foundList: MutableList<Pass>, private val findNotificationBuilder: NotificationCompat.Builder, private val file: File, private val notifyManager: NotificationManager) : UnzipPassController.SuccessCallback { override fun call(uuid: String) { val pass = passStore.getPassbookForId(uuid) val isDuplicate = foundList.any { it.id == uuid } if (pass != null && !isDuplicate) { foundList.add(pass) val iconBitmap = pass.getBitmap(passStore, PassBitmapDefinitions.BITMAP_ICON) passStore.classifier.moveToTopic(pass, getInitialTopic(pass)) if (iconBitmap != null) { val bitmap = scale2maxSize(iconBitmap, context.resources.getDimensionPixelSize(R.dimen.finger)) findNotificationBuilder.setLargeIcon(bitmap) } val foundString = context.getString(R.string.found_pass, pass.description) findNotificationBuilder.setContentTitle(foundString) if (foundList.size > 1) { val foundMoreString = context.getString(R.string.found__pass, foundList.size - 1) findNotificationBuilder.setContentText(foundMoreString) } else { findNotificationBuilder.setContentText(file.absolutePath) } val intent = Intent(context, PassViewActivity::class.java) intent.putExtra(PassViewActivityBase.EXTRA_KEY_UUID, uuid) findNotificationBuilder.setContentIntent(PendingIntent.getActivity(context, SearchPassesIntentService.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)) notifyManager.notify(SearchPassesIntentService.FOUND_NOTIFICATION_ID, findNotificationBuilder.build()) } } private fun scale2maxSize(bitmap: Bitmap, dimensionPixelSize: Int): Bitmap { val scale = dimensionPixelSize.toFloat() / if (bitmap.width > bitmap.height) bitmap.width else bitmap.height return bitmap.scale((bitmap.width * scale).toInt(), (bitmap.height * scale).toInt(), filter = false) } private fun getInitialTopic(pass: Pass): String { val passDate = getDateOfPassForComparison(pass) if (passDate != null && passDate.isBefore(ZonedDateTime.now())) { return context.getString(R.string.topic_archive) } return context.getString(R.string.topic_new) } private fun getDateOfPassForComparison(pass: Pass): ZonedDateTime? { if (pass.calendarTimespan != null && pass.calendarTimespan!!.from != null) { return pass.calendarTimespan!!.from } else if (pass.validTimespans != null && pass.validTimespans!!.isNotEmpty() && pass.validTimespans!![0].to != null) { return pass.validTimespans!![0].to } return null } }
gpl-3.0
iskandar1023/template
app/src/main/kotlin/substratum/theme/template/SubstratumLauncher.kt
1
8568
@file:Suppress("ConstantConditionIf") package substratum.theme.template import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.app.AlertDialog import android.util.Log import android.widget.Toast import com.github.javiersantos.piracychecker.PiracyChecker import com.github.javiersantos.piracychecker.PiracyCheckerUtils import com.github.javiersantos.piracychecker.enums.* import substratum.theme.template.AdvancedConstants.ORGANIZATION_THEME_SYSTEMS import substratum.theme.template.AdvancedConstants.OTHER_THEME_SYSTEMS import substratum.theme.template.AdvancedConstants.SHOW_DIALOG_REPEATEDLY import substratum.theme.template.AdvancedConstants.SHOW_LAUNCH_DIALOG import substratum.theme.template.ThemeFunctions.checkApprovedSignature import substratum.theme.template.ThemeFunctions.getSelfSignature import substratum.theme.template.ThemeFunctions.getSelfVerifiedPirateTools import substratum.theme.template.ThemeFunctions.isCallingPackageAllowed /** * NOTE TO THEMERS * * This class is a TEMPLATE of how you should be launching themes. As long as you keep the structure * of launching themes the same, you can avoid easy script crackers by changing how * functions/methods are coded, as well as boolean variable placement. * * The more you play with this the harder it would be to decompile and crack! */ class SubstratumLauncher : Activity() { private val debug = false private val tag = "SubstratumThemeReport" private val substratumIntentData = "projekt.substratum.THEME" private val getKeysIntent = "projekt.substratum.GET_KEYS" private val receiveKeysIntent = "projekt.substratum.RECEIVE_KEYS" private lateinit var piracyChecker: PiracyChecker private val themePiracyCheck by lazy { if (BuildConfig.ENABLE_APP_BLACKLIST_CHECK) { getSelfVerifiedPirateTools(applicationContext) } else { false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) /* STEP 1: Block hijackers */ val caller = callingActivity!!.packageName val organizationsSystem = ORGANIZATION_THEME_SYSTEMS.contains(caller) val supportedSystem = organizationsSystem || OTHER_THEME_SYSTEMS.contains(caller) if (!BuildConfig.SUPPORTS_THIRD_PARTY_SYSTEMS && !supportedSystem) { Log.e(tag, "This theme does not support the launching theme system. [HIJACK] ($caller)") Toast.makeText(this, String.format(getString(R.string.unauthorized_theme_client_hijack), caller), Toast.LENGTH_LONG).show() finish() } if (debug) { Log.d(tag, "'$caller' has been authorized to launch this theme. (Phase 1)") } /* STEP 2: Ensure that our support is added where it belongs */ val action = intent.action val sharedPref = getPreferences(Context.MODE_PRIVATE) var verified = false if ((action == substratumIntentData) or (action == getKeysIntent)) { // Assume this called from organization's app if (organizationsSystem) { verified = when { BuildConfig.ALLOW_THIRD_PARTY_SUBSTRATUM_BUILDS -> true else -> checkApprovedSignature(this, caller) } } } else { OTHER_THEME_SYSTEMS .filter { action?.startsWith(prefix = it, ignoreCase = true) ?: false } .forEach { verified = true } } if (!verified) { Log.e(tag, "This theme does not support the launching theme system. ($action)") Toast.makeText(this, R.string.unauthorized_theme_client, Toast.LENGTH_LONG).show() finish() return } if (debug) { Log.d(tag, "'$action' has been authorized to launch this theme. (Phase 2)") } /* STEP 3: Do da thang */ if (SHOW_LAUNCH_DIALOG) run { if (SHOW_DIALOG_REPEATEDLY) { showDialog() sharedPref.edit().remove("dialog_showed").apply() } else if (!sharedPref.getBoolean("dialog_showed", false)) { showDialog() sharedPref.edit().putBoolean("dialog_showed", true).apply() } else { startAntiPiracyCheck() } } else { startAntiPiracyCheck() } } override fun onDestroy() { super.onDestroy() piracyChecker.destroy() } private fun startAntiPiracyCheck() { if (BuildConfig.BASE_64_LICENSE_KEY.isEmpty() && debug && !BuildConfig.DEBUG) { Log.e(tag, PiracyCheckerUtils.getAPKSignature(this)) } piracyChecker = PiracyChecker(this) if (BuildConfig.ENFORCE_GOOGLE_PLAY_INSTALL) { piracyChecker.enableInstallerId(InstallerID.GOOGLE_PLAY) } if (BuildConfig.BASE_64_LICENSE_KEY.isNotEmpty()) { piracyChecker.enableGooglePlayLicensing(BuildConfig.BASE_64_LICENSE_KEY) } if (BuildConfig.APK_SIGNATURE_PRODUCTION.isNotEmpty()) { piracyChecker.enableSigningCertificate(BuildConfig.APK_SIGNATURE_PRODUCTION) } piracyChecker.callback(object : PiracyCheckerCallback() { override fun allow() { val returnIntent = if (intent.action == getKeysIntent) { Intent(receiveKeysIntent) } else { Intent() } val themeName = getString(R.string.ThemeName) val themeAuthor = getString(R.string.ThemeAuthor) val themePid = packageName returnIntent.putExtra("theme_name", themeName) returnIntent.putExtra("theme_author", themeAuthor) returnIntent.putExtra("theme_pid", themePid) returnIntent.putExtra("theme_debug", BuildConfig.DEBUG) returnIntent.putExtra("theme_piracy_check", themePiracyCheck) returnIntent.putExtra("encryption_key", BuildConfig.DECRYPTION_KEY) returnIntent.putExtra("iv_encrypt_key", BuildConfig.IV_KEY) val callingPackage = intent.getStringExtra("calling_package_name") if (!isCallingPackageAllowed(callingPackage)) { finish() } else { returnIntent.`package` = callingPackage } if (intent.action == substratumIntentData) { setResult(getSelfSignature(applicationContext), returnIntent) } else if (intent.action == getKeysIntent) { returnIntent.action = receiveKeysIntent sendBroadcast(returnIntent) } finish() } override fun dontAllow(error: PiracyCheckerError, pirateApp: PirateApp?) { val parse = String.format( getString(R.string.toast_unlicensed), getString(R.string.ThemeName)) Toast.makeText(this@SubstratumLauncher, parse, Toast.LENGTH_SHORT).show() finish() } }) if (!themePiracyCheck) { piracyChecker.start() } else { Toast.makeText(this, R.string.unauthorized, Toast.LENGTH_LONG).show() finish() } } private fun showDialog() { val dialog = AlertDialog.Builder(this, R.style.DialogStyle) .setCancelable(false) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.launch_dialog_title) .setMessage(R.string.launch_dialog_content) .setPositiveButton(R.string.launch_dialog_positive) { _, _ -> startAntiPiracyCheck() } if (getString(R.string.launch_dialog_negative).isNotEmpty()) { if (getString(R.string.launch_dialog_negative_url).isNotEmpty()) { dialog.setNegativeButton(R.string.launch_dialog_negative) { _, _ -> startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.launch_dialog_negative_url)))) finish() } } else { dialog.setNegativeButton(R.string.launch_dialog_negative) { _, _ -> finish() } } } dialog.show() } }
apache-2.0
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/SeriesListRelations.kt
1
446
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.Embedded import androidx.room.Relation data class SeriesListRelations( @Embedded var seriesListEntity: SeriesListEntity = SeriesListEntity(), @Relation( parentColumn = "series_list_id", entityColumn = "summary_series_list_id", entity = SummaryEntity::class ) var seriesListSummary: List<SummaryEntity> = mutableListOf() )
mit
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/localcontentmigration/ReaderSavedPostsProviderHelper.kt
1
825
package org.wordpress.android.localcontentmigration import org.wordpress.android.datasets.wrappers.ReaderPostTableWrapper import org.wordpress.android.localcontentmigration.LocalContentEntityData.ReaderPostsData import org.wordpress.android.models.ReaderTag import org.wordpress.android.models.ReaderTagType.BOOKMARKED import javax.inject.Inject class ReaderSavedPostsProviderHelper @Inject constructor( private val readerPostTableWrapper: ReaderPostTableWrapper, ): LocalDataProviderHelper { override fun getData(localEntityId: Int?): LocalContentEntityData = readerPostTableWrapper.getPostsWithTag( readerTag = ReaderTag("", "", "", "", BOOKMARKED), maxRows = 0, excludeTextColumn = false ).let { ReaderPostsData(posts = it) } }
gpl-2.0
edwardharks/Aircraft-Recognition
recognition/src/main/kotlin/com/edwardharker/aircraftrecognition/model/Aircraft.kt
1
484
package com.edwardharker.aircraftrecognition.model data class Aircraft( val id: String = "", val name: String = "", val shortDescription: String = "", val longDescription: String = "", val attribution: String = "", val attributionUrl: String = "", val metaData: Map<String, String> = emptyMap(), val filterOptions: Map<String, String> = emptyMap(), val images: List<Image> = emptyList(), val youtubeVideos: List<YoutubeVideo> = emptyList() )
gpl-3.0
KotlinNLP/SimpleDNN
examples/mnist/helpers/MNISTSequenceExampleExtractor.kt
1
1447
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package mnist.helpers import com.beust.klaxon.JsonArray import com.beust.klaxon.JsonBase import com.beust.klaxon.JsonObject import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import utils.SequenceExampleWithFinalOutput import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import utils.exampleextractor.ExampleExtractor /** * */ class MNISTSequenceExampleExtractor(val outputSize: Int) : ExampleExtractor<SequenceExampleWithFinalOutput<DenseNDArray>> { /** * */ override fun extract(jsonElement: JsonBase): SequenceExampleWithFinalOutput<DenseNDArray> { val jsonObject = jsonElement as JsonObject val outputGold = DenseNDArrayFactory.oneHotEncoder(length = 10, oneAt = jsonObject.int("digit")!!) val featuresList: List<DenseNDArray> = jsonElement.array<JsonArray<*>>("sequence_data")!!.map { val deltaX = (it[0] as Int).toDouble() val deltaY = (it[1] as Int).toDouble() DenseNDArrayFactory.arrayOf(doubleArrayOf(deltaX, deltaY)) } return SequenceExampleWithFinalOutput(featuresList, outputGold) } }
mpl-2.0
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/RustQualifiedReferenceElement.kt
1
1658
package org.rust.lang.core.psi import com.intellij.psi.PsiElement import org.rust.lang.core.resolve.ref.RustReference interface RustQualifiedReferenceElement : RustNamedElement { /** * Returns `true` if this is a fully qualified path. * * Paths in use items are special, they are implicitly FQ. * * Example: * * ```Rust * use ::foo::bar; // FQ * use foo::bar; // FQ, the same as the above * * fn main() { * ::foo::bar; // FQ * foo::bar; // not FQ * } * ``` * * Reference: * https://doc.rust-lang.org/reference.html#paths * https://doc.rust-lang.org/reference.html#use-declarations */ val isFullyQualified: Boolean /** * Returns true if this path references ancestor module via `self` and `super` chain. * * Paths can contain any combination of identifiers and self and super keywords. * However, a path is "well formed" only if it starts with `(self::)? (super::)*`. * In other words, in `foo::super::bar` the `super` is meaningless and resolves * to nothing. * * This check returns true for `(self::)? (super::)*` part of a path. * * Reference: * https://doc.rust-lang.org/reference.html#paths */ val isModulePrefix: Boolean /** * Returns true if this is a `self::` prefixed qualified-reference */ val isSelf: Boolean val separator: PsiElement? val qualifier: RustQualifiedReferenceElement? override val nameElement: PsiElement? override fun getReference(): RustReference }
mit
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImage.kt
5
2906
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.hasType class MarkdownImage(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement, MarkdownLink { val exclamationMark: PsiElement? get() = firstChild val link: MarkdownInlineLink? get() = findChildByType(MarkdownElementTypes.INLINE_LINK) override val linkText: MarkdownLinkText? get() = link?.children()?.filterIsInstance<MarkdownLinkText>()?.firstOrNull() override val linkDestination: MarkdownLinkDestination? get() = link?.children()?.filterIsInstance<MarkdownLinkDestination>()?.firstOrNull() val linkTitle: PsiElement? get() = link?.children()?.find { it.hasType(MarkdownElementTypes.LINK_TITLE) } fun collectLinkDescriptionText(): String? { return linkText?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET) } } fun collectLinkTitleText(): String? { return linkTitle?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE) } } private fun collectTextFromWrappedBlock(element: PsiElement, prefix: IElementType? = null, suffix: IElementType? = null): String? { val children = element.firstChild?.siblings(withSelf = true)?.toList() ?: return null val left = when (children.first().elementType) { prefix -> 1 else -> 0 } val right = when (children.last().elementType) { suffix -> children.size - 1 else -> children.size } val elements = children.subList(left, right) val content = elements.joinToString(separator = "") { it.text } return content.takeIf { it.isNotEmpty() } } companion object { /** * Useful for determining if some element is an actual image by it's leaf child. */ fun getByLeadingExclamationMark(exclamationMark: PsiElement): MarkdownImage? { if (!exclamationMark.hasType(MarkdownTokenTypes.EXCLAMATION_MARK)) { return null } val image = exclamationMark.parent ?: return null if (!image.hasType(MarkdownElementTypes.IMAGE) || image.firstChild != exclamationMark) { return null } return image as? MarkdownImage } } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinPluginCompatibilityVerifier.kt
1
1491
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.runInEdt import com.intellij.openapi.ui.Messages import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePluginVersion object KotlinPluginCompatibilityVerifier { @JvmStatic fun checkCompatibility() { val platformVersion = ApplicationInfo.getInstance().shortVersion ?: return val isAndroidStudio = KotlinPlatformUtils.isAndroidStudio val rawVersion = KotlinIdePlugin.version val kotlinPluginVersion = KotlinIdePluginVersion.parse(rawVersion).getOrNull() ?: return if (kotlinPluginVersion.platformVersion != platformVersion || kotlinPluginVersion.isAndroidStudio != isAndroidStudio) { val ideName = ApplicationInfo.getInstance().versionName runInEdt { Messages.showWarningDialog( KotlinBundle.message("plugin.verifier.compatibility.issue.message", rawVersion, ideName, platformVersion), KotlinBundle.message("plugin.verifier.compatibility.issue.title") ) } } } }
apache-2.0
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/actions/BookmarkTypeChooser.kt
1
9798
// 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.actions import com.intellij.ide.bookmark.BookmarkBundle.message import com.intellij.ide.bookmark.BookmarkType import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ExperimentalUI import com.intellij.ui.JBColor.namedColor import com.intellij.ui.components.JBTextField import com.intellij.ui.components.panels.RowGridLayout import com.intellij.ui.dsl.builder.BottomGap import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.util.ui.JBUI import com.intellij.util.ui.RegionPaintIcon import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.Nls import java.awt.* import java.awt.RenderingHints.KEY_ANTIALIASING import java.awt.RenderingHints.VALUE_ANTIALIAS_ON import java.awt.event.KeyEvent import java.awt.event.KeyListener import javax.swing.* private val ASSIGNED_FOREGROUND = namedColor("Bookmark.MnemonicAssigned.foreground", 0x000000, 0xBBBBBB) private val ASSIGNED_BACKGROUND = namedColor("Bookmark.MnemonicAssigned.background", 0xF7C777, 0x665632) private val CURRENT_FOREGROUND = namedColor("Bookmark.MnemonicCurrent.foreground", 0xFFFFFF, 0xFEFEFE) private val CURRENT_BACKGROUND = namedColor("Bookmark.MnemonicCurrent.background", 0x389FD6, 0x345F85) private val SHARED_CURSOR by lazy { Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } private val SHARED_LAYOUT by lazy { object : RowGridLayout(0, 4, 2, SwingConstants.CENTER) { override fun getCellSize(sizes: List<Dimension>) = when { ExperimentalUI.isNewUI() -> Dimension(JBUI.scale(30), JBUI.scale(34)) else -> Dimension(JBUI.scale(24), JBUI.scale(28)) } } } private object MySpacingConfiguration: IntelliJSpacingConfiguration() { override val verticalComponentGap: Int get() = 0 override val verticalSmallGap: Int get() = JBUI.scale(if (ExperimentalUI.isNewUI()) 16 else 8) } internal class BookmarkTypeChooser( private var current: BookmarkType?, assigned: Set<BookmarkType>, private var description: String?, private val onChosen: (BookmarkType, String) -> Unit ): JPanel(FlowLayout(FlowLayout.CENTER, 0, 0)) { private val bookmarkLayoutGrid = BookmarkLayoutGrid( current, assigned, { if (current == it) save() else current = it }, { save() } ) private lateinit var descriptionField: JBTextField val firstButton = bookmarkLayoutGrid.buttons().first() init { add(panel { customizeSpacingConfiguration(MySpacingConfiguration) { row { val lineLength = if (ExperimentalUI.isNewUI()) 63 else 55 comment(message("mnemonic.chooser.comment"), lineLength).apply { if (ExperimentalUI.isNewUI()) border = JBUI.Borders.empty(2, 4, 0, 4) } }.bottomGap(BottomGap.SMALL) row { cell(bookmarkLayoutGrid) .horizontalAlign(HorizontalAlign.CENTER) }.bottomGap(BottomGap.SMALL) row { descriptionField = textField() .horizontalAlign(HorizontalAlign.FILL) .applyToComponent { text = description ?: "" emptyText.text = message("mnemonic.chooser.description") isOpaque = false addKeyListener(object : KeyListener { override fun keyTyped(e: KeyEvent?) = Unit override fun keyReleased(e: KeyEvent?) = Unit override fun keyPressed(e: KeyEvent?) { if (e != null && e.modifiersEx == 0 && e.keyCode == KeyEvent.VK_ENTER) { save() } } }) } .component }.bottomGap(BottomGap.SMALL) row { cell(createLegend(ASSIGNED_BACKGROUND, message("mnemonic.chooser.legend.assigned.bookmark"))) cell(createLegend(CURRENT_BACKGROUND, message("mnemonic.chooser.legend.current.bookmark"))) } } }.apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.empty(0, 20, 14, 20) else -> JBUI.Borders.empty(12, 11) } isOpaque = false isFocusCycleRoot = true focusTraversalPolicy = object: LayoutFocusTraversalPolicy() { override fun accept(aComponent: Component?): Boolean { return super.accept(aComponent) && (aComponent !is JButton || aComponent == firstButton) } } }) border = JBUI.Borders.empty() background = namedColor("Popup.background") } private fun createLegend(color: Color, @Nls text: String) = JLabel(text).apply { icon = RegionPaintIcon(8) { g, x, y, width, height, _ -> g.color = color g.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON) g.fillOval(x, y, width, height) }.withIconPreScaled(false) } private fun save() { current?.let { onChosen(it, descriptionField.text) } } } private class BookmarkLayoutGrid( current: BookmarkType?, private val assigned: Set<BookmarkType>, private val onChosen: (BookmarkType) -> Unit, private val save: () -> Unit ) : BorderLayoutPanel(), KeyListener { companion object { const val TYPE_KEY: String = "BookmarkLayoutGrid.Type" } init { addToLeft(JPanel(SHARED_LAYOUT).apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.emptyRight(14) else -> JBUI.Borders.empty(5) } isOpaque = false BookmarkType.values() .filter { it.mnemonic.isDigit() } .forEach { add(createButton(it)) } }) addToRight(JPanel(SHARED_LAYOUT).apply { border = when { ExperimentalUI.isNewUI() -> JBUI.Borders.empty() else -> JBUI.Borders.empty(5) } isOpaque = false BookmarkType.values() .filter { it.mnemonic.isLetter() } .forEach { add(createButton(it)) } }) isOpaque = false updateButtons(current) } fun buttons() = UIUtil.uiTraverser(this).traverse().filter(JButton::class.java) fun createButton(type: BookmarkType) = JButton(type.mnemonic.toString()).apply { setMnemonic(type.mnemonic) isOpaque = false putClientProperty("ActionToolbar.smallVariant", true) putClientProperty(TYPE_KEY, type) addPropertyChangeListener { repaint() } addActionListener { onChosen(type) updateButtons(type) } inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "released") inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "pressed") cursor = SHARED_CURSOR addKeyListener(this@BookmarkLayoutGrid) } fun updateButtons(current: BookmarkType?) { buttons().forEach { val type = it.getClientProperty(TYPE_KEY) as? BookmarkType when { type == current -> { it.putClientProperty("JButton.textColor", CURRENT_FOREGROUND) it.putClientProperty("JButton.backgroundColor", CURRENT_BACKGROUND) it.putClientProperty("JButton.borderColor", CURRENT_BACKGROUND) } assigned.contains(type) -> { it.putClientProperty("JButton.textColor", ASSIGNED_FOREGROUND) it.putClientProperty("JButton.backgroundColor", ASSIGNED_BACKGROUND) it.putClientProperty("JButton.borderColor", ASSIGNED_BACKGROUND) } else -> { it.putClientProperty("JButton.textColor", UIManager.getColor("Bookmark.MnemonicAvailable.foreground")) it.putClientProperty("JButton.backgroundColor", UIManager.getColor("Popup.background")) it.putClientProperty("JButton.borderColor", UIManager.getColor("Bookmark.MnemonicAvailable.borderColor")) } } } } private fun offset(delta: Int, size: Int) = when { delta < 0 -> delta delta > 0 -> delta + size else -> size / 2 } private fun next(source: Component, dx: Int, dy: Int): Component? { val point = SwingUtilities.convertPoint(source, offset(dx, source.width), offset(dy, source.height), this) val component = next(source, dx, dy, point) if (component != null || !Registry.`is`("ide.bookmark.mnemonic.chooser.cyclic.scrolling.allowed")) return component if (dx > 0) point.x = 0 if (dx < 0) point.x = dx + width if (dy > 0) point.y = 0 if (dy < 0) point.y = dy + height return next(source, dx, dy, point) } private fun next(source: Component, dx: Int, dy: Int, point: Point): Component? { while (contains(point)) { val component = SwingUtilities.getDeepestComponentAt(this, point.x, point.y) if (component is JButton) return component point.translate(dx * source.width / 2, dy * source.height / 2) } return null } override fun keyTyped(event: KeyEvent) = Unit override fun keyReleased(event: KeyEvent) = Unit override fun keyPressed(event: KeyEvent) { if (event.modifiersEx == 0) { when (event.keyCode) { KeyEvent.VK_UP, KeyEvent.VK_KP_UP -> next(event.component, 0, -1)?.requestFocus() KeyEvent.VK_DOWN, KeyEvent.VK_KP_DOWN -> next(event.component, 0, 1)?.requestFocus() KeyEvent.VK_LEFT, KeyEvent.VK_KP_LEFT -> next(event.component, -1, 0)?.requestFocus() KeyEvent.VK_RIGHT, KeyEvent.VK_KP_RIGHT -> next(event.component, 1, 0)?.requestFocus() KeyEvent.VK_ENTER -> { val button = next(event.component, 0, 0) as? JButton button?.doClick() save() } else -> { val type = BookmarkType.get(event.keyCode.toChar()) if (type != BookmarkType.DEFAULT) { onChosen(type) save() } } } } } }
apache-2.0
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/event/Events.kt
1
250
package org.snakeskin.event /** * @author Cameron Earle * @version 7/16/17 * * This is a collection of built in events that are fired internally by the lib */ enum class Events { DISABLED, ENABLED, AUTO_ENABLED, TELEOP_ENABLED }
gpl-3.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/player/attribute/AttributeListViewController.kt
1
15641
package io.ipoli.android.player.attribute import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorInt import android.support.annotation.DrawableRes import android.support.v4.view.ViewPager import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.ListPopupWindow import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.R import io.ipoli.android.common.ViewUtils import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.view.* import io.ipoli.android.common.view.pager.BasePagerAdapter import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.player.attribute.AttributeListViewState.StateType.* import io.ipoli.android.player.data.AndroidAttribute import io.ipoli.android.player.data.Player import io.ipoli.android.tag.Tag import kotlinx.android.synthetic.main.controller_attribute_list.view.* import kotlinx.android.synthetic.main.item_attribute_bonus.view.* import kotlinx.android.synthetic.main.item_attribute_list.view.* import kotlinx.android.synthetic.main.view_default_toolbar.view.* /** * Created by Polina Zhelyazkova <[email protected]> * on 9/13/18. */ class AttributeListViewController(args: Bundle? = null) : ReduxViewController<AttributeListAction, AttributeListViewState, AttributeListReducer>(args) { override val reducer = AttributeListReducer private var attribute: Player.AttributeType? = null override var helpConfig: HelpConfig? = HelpConfig( io.ipoli.android.R.string.help_dialog_attribute_list_title, io.ipoli.android.R.string.help_dialog_attribute_list_message ) private val onPageChangeListener = object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { } override fun onPageSelected(position: Int) { val vm = (view!!.attributePager.adapter as AttributeAdapter).itemAt(position) colorLayout(vm) } } constructor(attribute: Player.AttributeType) : this() { this.attribute = attribute } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = inflater.inflate(R.layout.controller_attribute_list, container, false) view.attributePager.addOnPageChangeListener(onPageChangeListener) view.attributePager.adapter = AttributeAdapter() view.attributePager.clipToPadding = false view.attributePager.pageMargin = ViewUtils.dpToPx(8f, view.context).toInt() return view } override fun onCreateLoadAction() = AttributeListAction.Load(attribute) override fun onAttach(view: View) { super.onAttach(view) setToolbar(view.toolbar) showBackButton() toolbarTitle = stringRes(R.string.attributes) } override fun onDestroyView(view: View) { view.attributePager.removeOnPageChangeListener(onPageChangeListener) super.onDestroyView(view) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { return router.handleBack() } return super.onOptionsItemSelected(item) } override fun render(state: AttributeListViewState, view: View) { when (state.type) { LOADING -> { } DATA_LOADED -> { val vms = state.attributeViewModels (view.attributePager.adapter as AttributeAdapter).updateAll(vms) view.attributePager.currentItem = state.firstSelectedIndex!! colorLayout(vms[state.firstSelectedIndex]) } DATA_CHANGED -> { (view.attributePager.adapter as AttributeAdapter).updateAll(state.attributeViewModels) } } } private fun colorLayout(vm: AttributeViewModel) { view!!.toolbar.setBackgroundColor(vm.backgroundColor) activity?.window?.navigationBarColor = vm.backgroundColor activity?.window?.statusBarColor = vm.darkBackgroundColor } data class AttributeViewModel( val name: String, val attributeType: Player.AttributeType, val description: String, val level: String, val isActive: Boolean, val progress: Int, val max: Int, val currentProgress: String, @ColorInt val progressColor: Int, @ColorInt val secondaryProgressColor: Int, @ColorInt val backgroundColor: Int, @ColorInt val darkBackgroundColor: Int, @DrawableRes val background: Int, @DrawableRes val icon: Int, val attributeTags: List<Tag>, val tags: List<Tag>, val showTag1: Boolean, val showTag2: Boolean, val showTag3: Boolean, val showAddTag: Boolean, val bonuses: List<BonusViewModel> ) data class BonusViewModel( override val id: String, val title: String, val description: String, val isLocked: Boolean ) : RecyclerViewViewModel inner class BonusAdapter : BaseRecyclerViewAdapter<BonusViewModel>(R.layout.item_attribute_bonus) { override fun onBindViewModel(vm: BonusViewModel, view: View, holder: SimpleViewHolder) { view.bonusIcon.setImageResource( if (vm.isLocked) R.drawable.ic_lock_red_24dp else R.drawable.ic_done_green_24dp ) view.bonusTitle.text = vm.title view.bonusDescription.text = vm.description } } inner class AttributeAdapter : BasePagerAdapter<AttributeViewModel>() { override fun layoutResourceFor(item: AttributeViewModel) = R.layout.item_attribute_list override fun bindItem(item: AttributeViewModel, view: View) { view.attributeName.text = item.name view.attributeDescription.text = item.description view.attributeLevel.text = item.level view.attributeIconBack.setBackgroundResource(item.background) view.attributeIcon.setImageResource(item.icon) val square = view.attributeLevel.background as GradientDrawable square.mutate() square.color = ColorStateList.valueOf(item.darkBackgroundColor) view.attributeLevel.background = square if (item.isActive) { view.progressGroup.visible() view.hintGroup.invisible() view.attributeProgress.progressTintList = ColorStateList.valueOf(item.progressColor) view.attributeProgress.secondaryProgressTintList = ColorStateList.valueOf(item.secondaryProgressColor) view.attributeProgress.progress = item.progress view.attributeProgress.max = item.max view.attributeProgressText.text = item.currentProgress } else { view.progressGroup.invisible() view.hintGroup.visible() view.attributeHintIcon.setImageDrawable( IconicsDrawable(view.context) .icon(GoogleMaterial.Icon.gmd_info_outline) .color(attrData(R.attr.colorAccent)) .sizeDp(24) ) } renderTags(item, view) view.attributeBonusList.layoutManager = LinearLayoutManager(view.context) view.attributeBonusList.adapter = BonusAdapter() view.attributeBonusList.isNestedScrollingEnabled = false (view.attributeBonusList.adapter as BonusAdapter).updateAll(item.bonuses) } private fun renderTags( item: AttributeViewModel, view: View ) { if (item.showTag1) { view.tag1.visible() view.tag1.text = item.attributeTags[0].name renderTagIndicatorColor(view.tag1, item.attributeTags[0]) } else view.tag1.gone() if (item.showTag2) { view.tag2.visible() view.tag2.text = item.attributeTags[1].name renderTagIndicatorColor(view.tag2, item.attributeTags[1]) } else view.tag2.gone() if (item.showTag3) { view.tag3.visible() view.tag3.text = item.attributeTags[2].name renderTagIndicatorColor(view.tag3, item.attributeTags[2]) } else view.tag3.gone() view.tag1.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[0] ) ) } view.tag2.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[1] ) ) } view.tag3.onDebounceClick { dispatch( AttributeListAction.RemoveTag( item.attributeType, item.attributeTags[2] ) ) } if (item.showAddTag) { view.addTag.visible() val background = view.addTag.background as GradientDrawable background.setColor(item.backgroundColor) val popupWindow = ListPopupWindow(activity!!) popupWindow.anchorView = view.addTag popupWindow.width = ViewUtils.dpToPx(200f, activity!!).toInt() popupWindow.setAdapter(TagAdapter(item.tags)) popupWindow.setOnItemClickListener { _, _, position, _ -> dispatch(AttributeListAction.AddTag(item.attributeType, item.tags[position])) popupWindow.dismiss() } view.addTag.onDebounceClick { popupWindow.show() } } else view.addTag.gone() } private fun renderTagIndicatorColor(view: TextView, tag: Tag) { val indicator = view.compoundDrawablesRelative[0] as GradientDrawable indicator.mutate() indicator.setColor(colorRes(AndroidColor.valueOf(tag.color.name).color500)) view.setCompoundDrawablesRelativeWithIntrinsicBounds( indicator, null, view.compoundDrawablesRelative[2], null ) } inner class TagAdapter(tags: List<Tag>) : ArrayAdapter<Tag>( activity!!, R.layout.item_tag_popup, tags ) { override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup) = bindView(position, convertView, parent) override fun getView(position: Int, convertView: View?, parent: ViewGroup) = bindView(position, convertView, parent) private fun bindView(position: Int, convertView: View?, parent: ViewGroup): View { val view = if (convertView == null) { val inflater = LayoutInflater.from(context) inflater.inflate(R.layout.item_tag_popup, parent, false) as TextView } else { convertView as TextView } val item = getItem(position) view.text = item.name val color = AndroidColor.valueOf(item.color.name).color500 val indicator = view.compoundDrawablesRelative[0] as GradientDrawable indicator.mutate() val size = ViewUtils.dpToPx(8f, view.context).toInt() indicator.setSize(size, size) indicator.setColor(colorRes(color)) view.setCompoundDrawablesRelativeWithIntrinsicBounds( indicator, null, null, null ) return view } } } private val AttributeListViewState.attributeViewModels: List<AttributeViewModel> get() { val tagToCount = tags!!.map { it to 0 }.toMap().toMutableMap() attributes!!.forEach { it.tags.forEach { t -> tagToCount[t] = tagToCount[t]!! + 1 } } return attributes.map { val attr = AndroidAttribute.valueOf(it.type.name) val attributeTags = it.tags val tagCount = attributeTags.size val availableTags = tags.filter { t -> tagToCount[t]!! < 3 && !attributeTags.contains(t) } val attrRank = AttributeRank.of(it.level, rank!!) val lastRankIndex = Math.min(attrRank.ordinal + 2, Player.Rank.values().size) AttributeViewModel( name = stringRes(attr.title), attributeType = it.type, description = stringRes(attr.description), level = it.level.toString(), isActive = tagCount > 0, progress = ((it.progressForLevel * 100f) / it.progressForNextLevel).toInt(), max = 100, currentProgress = "${it.progressForLevel}/${it.progressForNextLevel}", progressColor = colorRes(attr.colorPrimaryDark), secondaryProgressColor = colorRes(attr.colorPrimary), backgroundColor = colorRes(attr.colorPrimary), darkBackgroundColor = colorRes(attr.colorPrimaryDark), background = attr.background, icon = attr.whiteIcon, attributeTags = attributeTags, tags = availableTags, showTag1 = tagCount > 0, showTag2 = tagCount > 1, showTag3 = tagCount > 2, showAddTag = tagCount < 3 && availableTags.isNotEmpty(), bonuses = Player.Rank.values().toList().subList( 1, lastRankIndex ).mapIndexed { i, r -> BonusViewModel( id = r.name, title = "Level ${(i + 1) * 10}: ${stringRes(attr.bonusNames[r]!!)}", description = stringRes(attr.bonusDescriptions[r]!!), isLocked = !(attrRank == Player.Rank.DIVINITY || i + 1 < lastRankIndex - 1) ) }.reversed() ) } } }
gpl-3.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt
4
3945
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtSecondaryConstructor import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryConstructor) : KotlinQuickFixAction<KtSecondaryConstructor>(element) { override fun getText() = KotlinBundle.message("fix.insert.delegation.call", keywordToUse) override fun getFamilyName() = KotlinBundle.message("insert.explicit.delegation.call") private val keywordToUse = if (isThis) "this" else "super" override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val newDelegationCall = element.replaceImplicitDelegationCallWithExplicit(isThis) val resolvedCall = newDelegationCall.resolveToCall(BodyResolveMode.FULL) val descriptor = element.unsafeResolveToDescriptor() // if empty call is ok and it's resolved to another constructor, do not move caret if (resolvedCall?.isReallySuccess() == true && resolvedCall.candidateDescriptor.original != descriptor) return val leftParOffset = newDelegationCall.valueArgumentList!!.leftParenthesis!!.textOffset editor?.moveCaret(leftParOffset + 1) } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false return element.hasImplicitDelegationCall() } object InsertThisDelegationCallFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType<KtSecondaryConstructor> { secondaryConstructor -> return if (secondaryConstructor.getContainingClassOrObject().getConstructorsCount() <= 1 || !secondaryConstructor.hasImplicitDelegationCall() ) null else InsertDelegationCallQuickfix(isThis = true, element = secondaryConstructor) } private fun KtClassOrObject.getConstructorsCount() = (descriptor as ClassDescriptor).constructors.size } object InsertSuperDelegationCallFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val secondaryConstructor = diagnostic.psiElement.getNonStrictParentOfType<KtSecondaryConstructor>() ?: return null if (!secondaryConstructor.hasImplicitDelegationCall()) return null val klass = secondaryConstructor.getContainingClassOrObject() as? KtClass ?: return null if (klass.hasPrimaryConstructor()) return null return InsertDelegationCallQuickfix(isThis = false, element = secondaryConstructor) } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/base/highlighting/src/org/jetbrains/kotlin/idea/base/highlighting/KotlinNameHighlightingStateUtils.kt
4
1147
// 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. @file:JvmName("KotlinNameHighlightingStateUtils") package org.jetbrains.kotlin.idea.base.highlighting import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly private val NAME_HIGHLIGHTING_STATE_KEY = Key<Boolean>("KOTLIN_NAME_HIGHLIGHTING_STATE") @get:ApiStatus.Internal @set:ApiStatus.Internal var Project.isNameHighlightingEnabled: Boolean get() = getUserData(NAME_HIGHLIGHTING_STATE_KEY) ?: true internal set(value) { // Avoid storing garbage in the user data val valueToPut = if (!value) false else null putUserData(NAME_HIGHLIGHTING_STATE_KEY, valueToPut) } @TestOnly @ApiStatus.Internal fun Project.withNameHighlightingDisabled(block: () -> Unit) { val oldValue = isNameHighlightingEnabled try { isNameHighlightingEnabled = false block() } finally { isNameHighlightingEnabled = oldValue } }
apache-2.0
GunoH/intellij-community
plugins/devkit/intellij.devkit.workspaceModel/tests/testData/virtualFileUrls/after/entity.kt
1
2036
package com.intellij.workspaceModel.test.api import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type interface EntityWithUrls : WorkspaceEntity { val simpleUrl: VirtualFileUrl val nullableUrl: VirtualFileUrl? val listOfUrls: List<VirtualFileUrl> val dataClassWithUrl: DataClassWithUrl //region generated code @GeneratedCodeApiVersion(1) interface Builder : EntityWithUrls, WorkspaceEntity.Builder<EntityWithUrls>, ObjBuilder<EntityWithUrls> { override var entitySource: EntitySource override var simpleUrl: VirtualFileUrl override var nullableUrl: VirtualFileUrl? override var listOfUrls: MutableList<VirtualFileUrl> override var dataClassWithUrl: DataClassWithUrl } companion object : Type<EntityWithUrls, Builder>() { operator fun invoke(simpleUrl: VirtualFileUrl, listOfUrls: List<VirtualFileUrl>, dataClassWithUrl: DataClassWithUrl, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): EntityWithUrls { val builder = builder() builder.simpleUrl = simpleUrl builder.listOfUrls = listOfUrls.toMutableWorkspaceList() builder.dataClassWithUrl = dataClassWithUrl builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: EntityWithUrls, modification: EntityWithUrls.Builder.() -> Unit) = modifyEntity( EntityWithUrls.Builder::class.java, entity, modification) //endregion data class DataClassWithUrl(val url: VirtualFileUrl)
apache-2.0
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyvalue/AccountValues.kt
1
17395
package org.thoughtcrime.securesms.keyvalue import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import androidx.annotation.VisibleForTesting import org.signal.core.util.logging.Log import org.signal.libsignal.protocol.IdentityKey import org.signal.libsignal.protocol.IdentityKeyPair import org.signal.libsignal.protocol.ecc.Curve import org.signal.libsignal.protocol.util.Medium import org.signal.libsignal.zkgroup.profiles.PniCredential import org.thoughtcrime.securesms.crypto.IdentityKeyUtil import org.thoughtcrime.securesms.crypto.MasterCipher import org.thoughtcrime.securesms.crypto.ProfileKeyUtil import org.thoughtcrime.securesms.crypto.storage.PreKeyMetadataStore import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.service.KeyCachingService import org.thoughtcrime.securesms.util.Base64 import org.thoughtcrime.securesms.util.TextSecurePreferences import org.thoughtcrime.securesms.util.Util import org.whispersystems.signalservice.api.push.ACI import org.whispersystems.signalservice.api.push.PNI import org.whispersystems.signalservice.api.push.SignalServiceAddress import java.security.SecureRandom internal class AccountValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(AccountValues::class.java) private const val KEY_SERVICE_PASSWORD = "account.service_password" private const val KEY_REGISTRATION_ID = "account.registration_id" private const val KEY_FCM_ENABLED = "account.fcm_enabled" private const val KEY_FCM_TOKEN = "account.fcm_token" private const val KEY_FCM_TOKEN_VERSION = "account.fcm_token_version" private const val KEY_FCM_TOKEN_LAST_SET_TIME = "account.fcm_token_last_set_time" private const val KEY_DEVICE_NAME = "account.device_name" private const val KEY_DEVICE_ID = "account.device_id" private const val KEY_ACI_IDENTITY_PUBLIC_KEY = "account.aci_identity_public_key" private const val KEY_ACI_IDENTITY_PRIVATE_KEY = "account.aci_identity_private_key" private const val KEY_ACI_SIGNED_PREKEY_REGISTERED = "account.aci_signed_prekey_registered" private const val KEY_ACI_NEXT_SIGNED_PREKEY_ID = "account.aci_next_signed_prekey_id" private const val KEY_ACI_ACTIVE_SIGNED_PREKEY_ID = "account.aci_active_signed_prekey_id" private const val KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT = "account.aci_signed_prekey_failure_count" private const val KEY_ACI_NEXT_ONE_TIME_PREKEY_ID = "account.aci_next_one_time_prekey_id" private const val KEY_PNI_IDENTITY_PUBLIC_KEY = "account.pni_identity_public_key" private const val KEY_PNI_IDENTITY_PRIVATE_KEY = "account.pni_identity_private_key" private const val KEY_PNI_SIGNED_PREKEY_REGISTERED = "account.pni_signed_prekey_registered" private const val KEY_PNI_NEXT_SIGNED_PREKEY_ID = "account.pni_next_signed_prekey_id" private const val KEY_PNI_ACTIVE_SIGNED_PREKEY_ID = "account.pni_active_signed_prekey_id" private const val KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT = "account.pni_signed_prekey_failure_count" private const val KEY_PNI_NEXT_ONE_TIME_PREKEY_ID = "account.pni_next_one_time_prekey_id" private const val KEY_PNI_CREDENTIAL = "account.pni_credential" @VisibleForTesting const val KEY_E164 = "account.e164" @VisibleForTesting const val KEY_ACI = "account.aci" @VisibleForTesting const val KEY_PNI = "account.pni" @VisibleForTesting const val KEY_IS_REGISTERED = "account.is_registered" } init { if (!store.containsKey(KEY_ACI)) { migrateFromSharedPrefsV1(ApplicationDependencies.getApplication()) } if (!store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { migrateFromSharedPrefsV2(ApplicationDependencies.getApplication()) } } public override fun onFirstEverAppLaunch() = Unit public override fun getKeysToIncludeInBackup(): List<String> { return listOf( KEY_ACI_IDENTITY_PUBLIC_KEY, KEY_ACI_IDENTITY_PRIVATE_KEY, KEY_PNI_IDENTITY_PUBLIC_KEY, KEY_PNI_IDENTITY_PRIVATE_KEY, ) } /** The local user's [ACI]. */ val aci: ACI? get() = ACI.parseOrNull(getString(KEY_ACI, null)) /** The local user's [ACI]. Will throw if not present. */ fun requireAci(): ACI { return ACI.parseOrThrow(getString(KEY_ACI, null)) } fun setAci(aci: ACI) { putString(KEY_ACI, aci.toString()) } /** The local user's [PNI]. */ val pni: PNI? get() = PNI.parseOrNull(getString(KEY_PNI, null)) /** The local user's [PNI]. Will throw if not present. */ fun requirePni(): PNI { return PNI.parseOrThrow(getString(KEY_PNI, null)) } fun setPni(pni: PNI) { putString(KEY_PNI, pni.toString()) } fun getServiceIds(): ServiceIds { return ServiceIds(requireAci(), pni) } /** The local user's E164. */ val e164: String? get() = getString(KEY_E164, null) fun setE164(e164: String) { putString(KEY_E164, e164) } /** The password for communicating with the Signal service. */ val servicePassword: String? get() = getString(KEY_SERVICE_PASSWORD, null) fun setServicePassword(servicePassword: String) { putString(KEY_SERVICE_PASSWORD, servicePassword) } /** A randomly-generated value that represents this registration instance. Helps the server know if you reinstalled. */ var registrationId: Int by integerValue(KEY_REGISTRATION_ID, 0) /** The identity key pair for the ACI identity. */ val aciIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, null)) ) } /** The identity key pair for the PNI identity. */ val pniIdentityKey: IdentityKeyPair get() { require(store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { "Not yet set!" } return IdentityKeyPair( IdentityKey(getBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, null)), Curve.decodePrivatePoint(getBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, null)) ) } fun hasAciIdentityKey(): Boolean { return store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the ACI identity. Should only be done once. */ fun generateAciIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_ACI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate an ANI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new ACI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } fun hasPniIdentityKey(): Boolean { return store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY) } /** Generates and saves an identity key pair for the PNI identity if one doesn't already exist. */ fun generatePniIdentityKeyIfNecessary() { synchronized(this) { if (store.containsKey(KEY_PNI_IDENTITY_PUBLIC_KEY)) { Log.w(TAG, "Tried to generate a PNI identity, but one was already set!", Throwable()) return } Log.i(TAG, "Generating a new PNI identity key pair.") val key: IdentityKeyPair = IdentityKeyUtil.generateIdentityKeyPair() store .beginWrite() .putBlob(KEY_PNI_IDENTITY_PUBLIC_KEY, key.publicKey.serialize()) .putBlob(KEY_PNI_IDENTITY_PRIVATE_KEY, key.privateKey.serialize()) .commit() } } /** When acting as a linked device, this method lets you store the identity keys sent from the primary device */ fun setIdentityKeysFromPrimaryDevice(aciKeys: IdentityKeyPair) { synchronized(this) { require(isLinkedDevice) { "Must be a linked device!" } store .beginWrite() .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, aciKeys.publicKey.serialize()) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, aciKeys.privateKey.serialize()) .commit() } } /** Only to be used when restoring an identity public key from an old backup */ fun restoreLegacyIdentityPublicKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity public key from backup.") putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, Base64.decode(base64)) } /** Only to be used when restoring an identity private key from an old backup */ fun restoreLegacyIdentityPrivateKeyFromBackup(base64: String) { Log.w(TAG, "Restoring legacy identity private key from backup.") putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, Base64.decode(base64)) } @get:JvmName("aciPreKeys") val aciPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_ACI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_ACI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } @get:JvmName("pniPreKeys") val pniPreKeys: PreKeyMetadataStore = object : PreKeyMetadataStore { override var nextSignedPreKeyId: Int by integerValue(KEY_PNI_NEXT_SIGNED_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) override var activeSignedPreKeyId: Int by integerValue(KEY_PNI_ACTIVE_SIGNED_PREKEY_ID, -1) override var isSignedPreKeyRegistered: Boolean by booleanValue(KEY_PNI_SIGNED_PREKEY_REGISTERED, false) override var signedPreKeyFailureCount: Int by integerValue(KEY_PNI_SIGNED_PREKEY_FAILURE_COUNT, 0) override var nextOneTimePreKeyId: Int by integerValue(KEY_PNI_NEXT_ONE_TIME_PREKEY_ID, SecureRandom().nextInt(Medium.MAX_VALUE)) } /** Indicates whether the user has the ability to receive FCM messages. Largely coupled to whether they have Play Service. */ @get:JvmName("isFcmEnabled") var fcmEnabled: Boolean by booleanValue(KEY_FCM_ENABLED, false) /** The FCM token, which allows the server to send us FCM messages. */ var fcmToken: String? get() { val tokenVersion: Int = getInteger(KEY_FCM_TOKEN_VERSION, 0) return if (tokenVersion == Util.getCanonicalVersionCode()) { getString(KEY_FCM_TOKEN, null) } else { null } } set(value) { store.beginWrite() .putString(KEY_FCM_TOKEN, value) .putInteger(KEY_FCM_TOKEN_VERSION, Util.getCanonicalVersionCode()) .putLong(KEY_FCM_TOKEN_LAST_SET_TIME, System.currentTimeMillis()) .apply() } /** When we last set the [fcmToken] */ val fcmTokenLastSetTime: Long get() = getLong(KEY_FCM_TOKEN_LAST_SET_TIME, 0) /** Whether or not the user is registered with the Signal service. */ val isRegistered: Boolean get() = getBoolean(KEY_IS_REGISTERED, false) fun setRegistered(registered: Boolean) { Log.i(TAG, "Setting push registered: $registered", Throwable()) val previous = isRegistered putBoolean(KEY_IS_REGISTERED, registered) ApplicationDependencies.getIncomingMessageObserver().notifyRegistrationChanged() if (previous != registered) { Recipient.self().live().refresh() } if (previous && !registered) { clearLocalCredentials(ApplicationDependencies.getApplication()) } } val deviceName: String? get() = getString(KEY_DEVICE_NAME, null) fun setDeviceName(deviceName: String) { putString(KEY_DEVICE_NAME, deviceName) } var deviceId: Int by integerValue(KEY_DEVICE_ID, SignalServiceAddress.DEFAULT_DEVICE_ID) val isPrimaryDevice: Boolean get() = deviceId == SignalServiceAddress.DEFAULT_DEVICE_ID val isLinkedDevice: Boolean get() = !isPrimaryDevice var pniCredential: PniCredential? set(value) = putBlob(KEY_PNI_CREDENTIAL, value?.serialize()) get() = getBlob(KEY_PNI_CREDENTIAL, null)?.let { PniCredential(it) } private fun clearLocalCredentials(context: Context) { putString(KEY_SERVICE_PASSWORD, Util.getSecret(18)) val newProfileKey = ProfileKeyUtil.createNew() val self = Recipient.self() SignalDatabase.recipients.setProfileKey(self.id, newProfileKey) ApplicationDependencies.getGroupsV2Authorization().clear() } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV1(context: Context) { Log.i(TAG, "[V1] Migrating account values from shared prefs.") putString(KEY_ACI, TextSecurePreferences.getStringPreference(context, "pref_local_uuid", null)) putString(KEY_E164, TextSecurePreferences.getStringPreference(context, "pref_local_number", null)) putString(KEY_SERVICE_PASSWORD, TextSecurePreferences.getStringPreference(context, "pref_gcm_password", null)) putBoolean(KEY_IS_REGISTERED, TextSecurePreferences.getBooleanPreference(context, "pref_gcm_registered", false)) putInteger(KEY_REGISTRATION_ID, TextSecurePreferences.getIntegerPreference(context, "pref_local_registration_id", 0)) putBoolean(KEY_FCM_ENABLED, !TextSecurePreferences.getBooleanPreference(context, "pref_gcm_disabled", false)) putString(KEY_FCM_TOKEN, TextSecurePreferences.getStringPreference(context, "pref_gcm_registration_id", null)) putInteger(KEY_FCM_TOKEN_VERSION, TextSecurePreferences.getIntegerPreference(context, "pref_gcm_registration_id_version", 0)) putLong(KEY_FCM_TOKEN_LAST_SET_TIME, TextSecurePreferences.getLongPreference(context, "pref_gcm_registration_id_last_set_time", 0)) } /** Do not alter. If you need to migrate more stuff, create a new method. */ private fun migrateFromSharedPrefsV2(context: Context) { Log.i(TAG, "[V2] Migrating account values from shared prefs.") val masterSecretPrefs: SharedPreferences = context.getSharedPreferences("SecureSMS-Preferences", 0) val defaultPrefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val storeWriter: KeyValueStore.Writer = store.beginWrite() if (masterSecretPrefs.hasStringData("pref_identity_public_v3")) { Log.i(TAG, "Migrating modern identity key.") val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_v3", null)!!) val identityPrivate = Base64.decode(masterSecretPrefs.getString("pref_identity_private_v3", null)!!) storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else if (masterSecretPrefs.hasStringData("pref_identity_public_curve25519")) { Log.i(TAG, "Migrating legacy identity key.") val masterCipher = MasterCipher(KeyCachingService.getMasterSecret(context)) val identityPublic = Base64.decode(masterSecretPrefs.getString("pref_identity_public_curve25519", null)!!) val identityPrivate = masterCipher.decryptKey(Base64.decode(masterSecretPrefs.getString("pref_identity_private_curve25519", null)!!)).serialize() storeWriter .putBlob(KEY_ACI_IDENTITY_PUBLIC_KEY, identityPublic) .putBlob(KEY_ACI_IDENTITY_PRIVATE_KEY, identityPrivate) } else { Log.w(TAG, "No pre-existing identity key! No migration.") } storeWriter .putInteger(KEY_ACI_NEXT_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_next_signed_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_ACTIVE_SIGNED_PREKEY_ID, defaultPrefs.getInt("pref_active_signed_pre_key_id", -1)) .putInteger(KEY_ACI_NEXT_ONE_TIME_PREKEY_ID, defaultPrefs.getInt("pref_next_pre_key_id", SecureRandom().nextInt(Medium.MAX_VALUE))) .putInteger(KEY_ACI_SIGNED_PREKEY_FAILURE_COUNT, defaultPrefs.getInt("pref_signed_prekey_failure_count", 0)) .putBoolean(KEY_ACI_SIGNED_PREKEY_REGISTERED, defaultPrefs.getBoolean("pref_signed_prekey_registered", false)) .commit() masterSecretPrefs .edit() .remove("pref_identity_public_v3") .remove("pref_identity_private_v3") .remove("pref_identity_public_curve25519") .remove("pref_identity_private_curve25519") .commit() defaultPrefs .edit() .remove("pref_local_uuid") .remove("pref_identity_public_v3") .remove("pref_next_signed_pre_key_id") .remove("pref_active_signed_pre_key_id") .remove("pref_signed_prekey_failure_count") .remove("pref_signed_prekey_registered") .remove("pref_next_pre_key_id") .remove("pref_gcm_password") .remove("pref_gcm_registered") .remove("pref_local_registration_id") .remove("pref_gcm_disabled") .remove("pref_gcm_registration_id") .remove("pref_gcm_registration_id_version") .remove("pref_gcm_registration_id_last_set_time") .commit() } private fun SharedPreferences.hasStringData(key: String): Boolean { return this.getString(key, null) != null } }
gpl-3.0
jk1/intellij-community
platform/lang-api/src/com/intellij/execution/configurations/RunConfigurationOptions.kt
2
1458
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.execution.configurations import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.annotations.* open class RunConfigurationOptions : BaseState() { @Tag("output_file") class OutputFileOptions : BaseState() { @get:Attribute("path") var fileOutputPath: String? by string() @get:Attribute("is_save") var isSaveOutput: Boolean by property(false) } // we use object instead of 2 fields because XML serializer cannot reuse tag for several fields @get:Property(surroundWithTag = false) var fileOutput: OutputFileOptions by property(OutputFileOptions()) @get:Attribute("show_console_on_std_out") var isShowConsoleOnStdOut: Boolean by property(false) @get:Attribute("show_console_on_std_err") var isShowConsoleOnStdErr: Boolean by property(false) @get:Property(surroundWithTag = false) @get:XCollection var logFiles: MutableList<LogFileOptions> by list<LogFileOptions>() } open class LocatableRunConfigurationOptions : RunConfigurationOptions() { @get:Attribute("nameIsGenerated") var isNameGenerated: Boolean by property(false) } open class ModuleBasedConfigurationOptions : LocatableRunConfigurationOptions() { @get:OptionTag(tag = "module", valueAttribute = "name", nameAttribute = "") var module: String? by string() }
apache-2.0
lansheng228/kotlin-examples
spring-boot-restful/src/main/kotlin/com/example/Greeting.kt
1
76
package com.example data class Greeting(val id: Long, val content: String)
gpl-3.0
marius-m/wt4
remote/src/main/java/lt/markmerkk/JiraNetworkUtils.kt
1
1769
package lt.markmerkk import lt.markmerkk.exceptions.AuthException import net.rcarz.jiraclient.JiraException import net.rcarz.jiraclient.RestException import org.slf4j.Logger object JiraNetworkUtils { } inline fun <reified T: Exception> Throwable.findException(): T? { val exceptions = mutableListOf<Throwable>() var iterableThrowable: Throwable? = this do { if (iterableThrowable != null) { exceptions.add(iterableThrowable) iterableThrowable = iterableThrowable.cause } else { iterableThrowable = null } } while (iterableThrowable != null) return exceptions .mapNotNull { if (it is T) { it } else { null } }.firstOrNull() } fun Throwable.isAuthException(): Boolean { val restAuthException = findException<RestException>()?.httpStatusCode == 401 val isAuthException = findException<AuthException>() != null return restAuthException || isAuthException } fun Logger.warnWithJiraException(message: String, throwable: Throwable) { val authException = throwable.findException<AuthException>() val restException = throwable.findException<RestException>() when { authException != null -> this.warn("$message / Authorization error") restException != null && restException.httpStatusCode == 401 -> this.warn("$message / Authorization error (401)!") restException != null -> this.warn("$message / Rest error (${restException.httpStatusCode}): ${restException.httpResult}") throwable is JiraException -> this.warn("$message / Jira error: ${throwable.message}") else -> this.warn(message, throwable) } }
apache-2.0
Shoebill/shoebill-common
src/main/java/net/gtaun/shoebill/common/AbstractShoebillContext.kt
1
1257
package net.gtaun.shoebill.common import net.gtaun.shoebill.entities.Destroyable import net.gtaun.util.event.EventManager import net.gtaun.util.event.EventManagerNode import java.util.HashSet @AllOpen abstract class AbstractShoebillContext(parentEventManager: EventManager) : Destroyable { private var isInitialized = false protected var eventManagerNode: EventManagerNode = parentEventManager.createChildNode() private val destroyables = mutableSetOf<Destroyable>() fun addDestroyable(destroyable: Destroyable) = destroyables.add(destroyable) fun removeDestroyable(destroyable: Destroyable) = destroyables.remove(destroyable) fun init() { if (isInitialized) return try { onInit() isInitialized = true } catch (e: Throwable) { e.printStackTrace() destroy() } } override fun destroy() { if (isDestroyed) return onDestroy() destroyables.forEach { it.destroy() } destroyables.clear() eventManagerNode.destroy() isInitialized = false } override val isDestroyed: Boolean get() = !isInitialized protected abstract fun onInit() protected abstract fun onDestroy() }
apache-2.0
ktorio/ktor
buildSrc/src/main/kotlin/test/server/tests/Logging.kt
1
1199
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package test.server.tests import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* internal fun Application.loggingTestServer() { routing { route("logging") { get { call.respondText("home page") } post { if ("Response data" != call.receiveText()) { call.respond(HttpStatusCode.BadRequest) } else { call.respondText("/", status = HttpStatusCode.Created) } } get("301") { call.respondRedirect("/logging") } route("non-utf") { post { call.respondBytes( bytes = byteArrayOf(-77, 111), contentType = ContentType.parse("application/octet-stream"), status = HttpStatusCode.Created ) } } } } }
apache-2.0
lansheng228/kotlin-examples
hello-world/src/test/kotlin/demo/HelloWorldTest.kt
1
188
package demo import kotlin.test.assertEquals import org.junit.Test class HelloWorldTest { @Test fun testGetGreeting() { assertEquals("Hello, world!", getGreeting()) } }
gpl-3.0
jk1/Intellij-idea-mail
src/main/kotlin/github/jk1/smtpidea/components/ServerConfig.kt
1
314
package github.jk1.smtpidea.config import java.util.concurrent.TimeUnit /** * */ public abstract class ServerConfig{ /** * If server should be automatically launched on project load */ public var launchOnStartup: Boolean = false public val connectionTimeout : Int = 60000 // 1 minute }
gpl-2.0
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/adapter/EditPlaylistAdapter.kt
2
2969
package io.casey.musikcube.remote.ui.tracks.adapter import android.content.SharedPreferences import android.text.TextUtils import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.websocket.model.ITrack import io.casey.musikcube.remote.ui.shared.extension.fallback import io.casey.musikcube.remote.ui.shared.extension.titleEllipsizeMode import io.casey.musikcube.remote.ui.tracks.model.EditPlaylistViewModel class EditPlaylistAdapter( private val viewModel: EditPlaylistViewModel, private val touchHelper: ItemTouchHelper, prefs: SharedPreferences) : RecyclerView.Adapter<EditPlaylistAdapter.ViewHolder>() { private val ellipsizeMode = titleEllipsizeMode(prefs) override fun getItemCount(): Int { return viewModel.count } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.edit_playlist_track_row, parent, false) val holder = ViewHolder(view, ellipsizeMode) val drag = view.findViewById<View>(R.id.dragHandle) val swipe = view.findViewById<View>(R.id.swipeHandle) view.setOnClickListener(emptyClickListener) drag.setOnTouchListener(dragTouchHandler) swipe.setOnTouchListener(dragTouchHandler) drag.tag = holder swipe.tag = holder return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(viewModel[position]) } private val emptyClickListener = { _: View -> } private val dragTouchHandler = object: View.OnTouchListener { override fun onTouch(view: View, event: MotionEvent?): Boolean { if (event?.actionMasked == MotionEvent.ACTION_DOWN) { if (view.id == R.id.dragHandle) { touchHelper.startDrag(view.tag as RecyclerView.ViewHolder) } else if (view.id == R.id.swipeHandle) { touchHelper.startSwipe(view.tag as RecyclerView.ViewHolder) return true } } return false } } class ViewHolder internal constructor(view: View, ellipsizeMode: TextUtils.TruncateAt) : RecyclerView.ViewHolder(view) { private val title = itemView.findViewById<TextView>(R.id.title) private val subtitle = itemView.findViewById<TextView>(R.id.subtitle) init { title.ellipsize = ellipsizeMode } fun bind(track: ITrack) { title.text = fallback(track.title, "-") subtitle.text = fallback(track.albumArtist, "-") } } }
bsd-3-clause
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/browse/SourceItem.kt
1
2336
package eu.kanade.tachiyomi.ui.browse.source.browse import android.view.View import androidx.recyclerview.widget.RecyclerView import com.fredporciuncula.flow.preferences.Preference import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.databinding.SourceComfortableGridItemBinding import eu.kanade.tachiyomi.databinding.SourceCompactGridItemBinding import eu.kanade.tachiyomi.ui.library.setting.DisplayModeSetting class SourceItem(val manga: Manga, private val displayMode: Preference<DisplayModeSetting>) : AbstractFlexibleItem<SourceHolder<*>>() { override fun getLayoutRes(): Int { return when (displayMode.get()) { DisplayModeSetting.COMPACT_GRID, DisplayModeSetting.COVER_ONLY_GRID -> R.layout.source_compact_grid_item DisplayModeSetting.COMFORTABLE_GRID -> R.layout.source_comfortable_grid_item DisplayModeSetting.LIST -> R.layout.source_list_item } } override fun createViewHolder( view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>> ): SourceHolder<*> { return when (displayMode.get()) { DisplayModeSetting.COMPACT_GRID, DisplayModeSetting.COVER_ONLY_GRID -> { SourceCompactGridHolder(SourceCompactGridItemBinding.bind(view), adapter) } DisplayModeSetting.COMFORTABLE_GRID -> { SourceComfortableGridHolder(SourceComfortableGridItemBinding.bind(view), adapter) } DisplayModeSetting.LIST -> { SourceListHolder(view, adapter) } } } override fun bindViewHolder( adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: SourceHolder<*>, position: Int, payloads: List<Any?>? ) { holder.onSetValues(manga) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other is SourceItem) { return manga.id!! == other.manga.id!! } return false } override fun hashCode(): Int { return manga.id!!.hashCode() } }
apache-2.0
adrianswiatek/numbers-teacher
NumbersTeacher/app/src/main/java/pl/aswiatek/numbersteacher/businesslogic/numbergenerator/algorithm/AnyNumberGenerator.kt
1
723
package pl.aswiatek.numbersteacher.businesslogic.numbergenerator.algorithm import pl.aswiatek.numbersteacher.businesslogic.Settings import java.util.* class AnyNumberGenerator( private val random: Random, private val settings: Settings) : NumberGeneratorAlgorithm { override fun generate(previousNumber: Int): Int { var generatedNumber: Int do { generatedNumber = random.nextInt(settings.maxValue) } while (isInvalid(generatedNumber, previousNumber, settings.questionRadix)) return generatedNumber } private fun isInvalid(generatedNumber: Int, previousNumber: Int, radix: Int) = generatedNumber == previousNumber || generatedNumber < radix }
mit
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/imports/internal/conflicts/EnrollmentHasInvalidProgramConflict.kt
1
2585
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.imports.internal.conflicts import org.hisp.dhis.android.core.imports.internal.ImportConflict internal object EnrollmentHasInvalidProgramConflict : TrackerImportConflictItem { private val regex: Regex = Regex("ProgramInstance '(\\w{11})' has invalid Program.") private fun description(enrollmentUid: String) = "Your enrollment $enrollmentUid has an invalid program" override val errorCode: String = "E1069" override fun matches(conflict: ImportConflict): Boolean { return regex.matches(conflict.value()) } override fun getEnrollment(conflict: ImportConflict): String? { return regex.find(conflict.value())?.groupValues?.get(1) } override fun getDisplayDescription( conflict: ImportConflict, context: TrackerImportConflictItemContext ): String { return getEnrollment(conflict)?.let { enrollmentUid -> description(enrollmentUid) } ?: conflict.value() } }
bsd-3-clause
Talentica/AndroidWithKotlin
o_notifications/src/main/java/com/talentica/androidkotlin/onotifications/notifications/NotificationPresenter.kt
1
3686
/******************************************************************************* * Copyright 2017 Talentica Software Pvt. Ltd. * * 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.talentica.androidkotlin.onotifications.notifications import android.app.Activity import android.app.NotificationManager import android.content.Context import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import com.enrico.colorpicker.colorDialog import com.talentica.androidkotlin.onotifications.R import com.talentica.androidkotlin.onotifications.utils.NotificationHelper class NotificationPresenter(context: Activity, view: NotificationContract.View) : NotificationContract.Presenter { private val view: NotificationContract.View = view private val mNotificationHelper: NotificationHelper private val context: Context init { this.view.setPresenter(this) this.mNotificationHelper = NotificationHelper(context) this.context = context } override fun start() { // start mNotificationHelper.createNotificationChannelGroups() } override fun destroy() { // destroy mNotificationHelper.clearAll() } override fun createChannel(id: String, name: CharSequence, importance: Int, showBadge: Boolean, group: String, vibrationPattern: LongArray) { if (id.trim().isEmpty() || name.trim().isEmpty()) { view.displayMessage(R.string.empty_params_msg) return } if (mNotificationHelper.getAllNotificationChannels().contains(id)) { view.displayMessage(R.string.channel_already_exists_msg) return } var channelImportance = 0 when (importance) { in 0..5 -> channelImportance = importance else -> channelImportance = NotificationManager.IMPORTANCE_UNSPECIFIED } mNotificationHelper.createChannel(id, name, channelImportance, showBadge, group, Color.CYAN, vibrationPattern) // end this with notifying the view view.displayMessage(R.string.channel_created_msg) view.clearNotificationFields() } override fun createNotification(channel: String, title: String, body: String, onGoing: Boolean, color: Int) { if (!mNotificationHelper.getAllNotificationChannels().contains(channel)) { view.displayMessage(R.string.channel_doesnt_exist_msg) return } val notifTitle = if (title.trim().isEmpty()) context.getString(R.string .default_noification_title) else title val notifBody = if (body.trim().isEmpty()) context.getString(R.string .default_noification_body) else body mNotificationHelper.createNotification(channel, notifTitle, notifBody, notifTitle, onGoing, color) // end this with notifying the view // view.displayMessage(/*Some message*/) } override fun launchColorPicker(tag: Int) { colorDialog.showColorPicker(context as AppCompatActivity?, tag) } }
apache-2.0
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/localanalytics/tests/LocalAnalyticsTrackerLargeMockIntegrationShould.kt
1
2515
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.localanalytics.tests import org.hisp.dhis.android.core.utils.integration.mock.MockIntegrationTestDatabaseContent import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.hisp.dhis.android.localanalytics.dbgeneration.LocalAnalyticsDataParams import org.junit.BeforeClass import org.junit.Ignore import org.junit.runner.RunWith @Ignore("Tests for local analytics. Only to be executed on demand") @RunWith(D2JunitRunner::class) internal class LocalAnalyticsTrackerLargeMockIntegrationShould : BaseLocalAnalyticsTrackerMockIntegrationShould() { companion object LocalAnalyticsAggregatedLargeDataMockIntegrationShould { @BeforeClass @JvmStatic fun setUpClass() { setUpClass( LocalAnalyticsDataParams.LargeFactor, MockIntegrationTestDatabaseContent.LocalAnalyticsLargeDispatcher ) } } }
bsd-3-clause
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsFragment.kt
1
29586
package org.thoughtcrime.securesms.components.settings.conversation import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.Rect import android.os.Bundle import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.view.doOnPreDraw import androidx.fragment.app.viewModels import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import app.cash.exhaustive.Exhaustive import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import org.thoughtcrime.securesms.AvatarPreviewActivity import org.thoughtcrime.securesms.BlockUnblockDialog import org.thoughtcrime.securesms.InviteActivity import org.thoughtcrime.securesms.MediaPreviewActivity import org.thoughtcrime.securesms.MuteDialog import org.thoughtcrime.securesms.PushContactSelectionActivity import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.VerifyIdentityActivity import org.thoughtcrime.securesms.components.AvatarImageView import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.NO_TINT import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.components.settings.conversation.preferences.AvatarPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.BioTextPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.ButtonStripPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.GroupDescriptionPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.InternalPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.LargeIconClickPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.LegacyGroupPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.RecipientPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.SharedMediaPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.Utils.formatMutedUntil import org.thoughtcrime.securesms.contacts.ContactsCursorLoader import org.thoughtcrime.securesms.conversation.ConversationIntents import org.thoughtcrime.securesms.groups.ParcelableGroupId import org.thoughtcrime.securesms.groups.ui.GroupErrors import org.thoughtcrime.securesms.groups.ui.GroupLimitDialog import org.thoughtcrime.securesms.groups.ui.LeaveGroupDialog import org.thoughtcrime.securesms.groups.ui.addmembers.AddMembersActivity import org.thoughtcrime.securesms.groups.ui.addtogroup.AddToGroupsActivity import org.thoughtcrime.securesms.groups.ui.invitesandrequests.ManagePendingAndRequestingMembersActivity import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupDescriptionDialog import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupInviteSentDialog import org.thoughtcrime.securesms.groups.ui.managegroup.dialogs.GroupsLearnMoreBottomSheetDialogFragment import org.thoughtcrime.securesms.groups.ui.migration.GroupsV1MigrationInitiationBottomSheetDialogFragment import org.thoughtcrime.securesms.mediaoverview.MediaOverviewActivity import org.thoughtcrime.securesms.profiles.edit.EditProfileActivity import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientExporter import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.recipients.ui.bottomsheet.RecipientBottomSheetDialogFragment import org.thoughtcrime.securesms.recipients.ui.sharablegrouplink.ShareableGroupLinkDialogFragment import org.thoughtcrime.securesms.util.CommunicationActions import org.thoughtcrime.securesms.util.ContextUtil import org.thoughtcrime.securesms.util.ExpirationUtil import org.thoughtcrime.securesms.util.ThemeUtil import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.util.views.SimpleProgressDialog import org.thoughtcrime.securesms.wallpaper.ChatWallpaperActivity private const val REQUEST_CODE_VIEW_CONTACT = 1 private const val REQUEST_CODE_ADD_CONTACT = 2 private const val REQUEST_CODE_ADD_MEMBERS_TO_GROUP = 3 private const val REQUEST_CODE_RETURN_FROM_MEDIA = 4 class ConversationSettingsFragment : DSLSettingsFragment( layoutId = R.layout.conversation_settings_fragment, menuId = R.menu.conversation_settings ) { private val alertTint by lazy { ContextCompat.getColor(requireContext(), R.color.signal_alert_primary) } private val blockIcon by lazy { ContextUtil.requireDrawable(requireContext(), R.drawable.ic_block_tinted_24).apply { colorFilter = PorterDuffColorFilter(alertTint, PorterDuff.Mode.SRC_IN) } } private val unblockIcon by lazy { ContextUtil.requireDrawable(requireContext(), R.drawable.ic_block_tinted_24) } private val leaveIcon by lazy { ContextUtil.requireDrawable(requireContext(), R.drawable.ic_leave_tinted_24).apply { colorFilter = PorterDuffColorFilter(alertTint, PorterDuff.Mode.SRC_IN) } } private val viewModel by viewModels<ConversationSettingsViewModel>( factoryProducer = { val args = ConversationSettingsFragmentArgs.fromBundle(requireArguments()) val groupId = args.groupId as? ParcelableGroupId ConversationSettingsViewModel.Factory( recipientId = args.recipientId, groupId = ParcelableGroupId.get(groupId), repository = ConversationSettingsRepository(requireContext()) ) } ) private lateinit var callback: Callback private lateinit var toolbar: Toolbar private lateinit var toolbarAvatar: AvatarImageView private lateinit var toolbarTitle: TextView private lateinit var toolbarBackground: View private val navController get() = Navigation.findNavController(requireView()) override fun onAttach(context: Context) { super.onAttach(context) callback = context as Callback } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { toolbar = view.findViewById(R.id.toolbar) toolbarAvatar = view.findViewById(R.id.toolbar_avatar) toolbarTitle = view.findViewById(R.id.toolbar_title) toolbarBackground = view.findViewById(R.id.toolbar_background) super.onViewCreated(view, savedInstanceState) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_CODE_ADD_MEMBERS_TO_GROUP -> if (data != null) { val selected: List<RecipientId> = requireNotNull(data.getParcelableArrayListExtra(PushContactSelectionActivity.KEY_SELECTED_RECIPIENTS)) val progress: SimpleProgressDialog.DismissibleDialog = SimpleProgressDialog.showDelayed(requireContext()) viewModel.onAddToGroupComplete(selected) { progress.dismiss() } } REQUEST_CODE_RETURN_FROM_MEDIA -> viewModel.refreshSharedMedia() REQUEST_CODE_ADD_CONTACT -> viewModel.refreshRecipient() REQUEST_CODE_VIEW_CONTACT -> viewModel.refreshRecipient() } } override fun getOnScrollAnimationHelper(toolbarShadow: View): OnScrollAnimationHelper { return ConversationSettingsOnUserScrolledAnimationHelper(toolbarAvatar, toolbarTitle, toolbarBackground, toolbarShadow) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.action_edit) { val args = ConversationSettingsFragmentArgs.fromBundle(requireArguments()) val groupId = args.groupId as ParcelableGroupId startActivity(EditProfileActivity.getIntentForGroupProfile(requireActivity(), requireNotNull(ParcelableGroupId.get(groupId)))) true } else { super.onOptionsItemSelected(item) } } override fun bindAdapter(adapter: DSLSettingsAdapter) { BioTextPreference.register(adapter) AvatarPreference.register(adapter) ButtonStripPreference.register(adapter) LargeIconClickPreference.register(adapter) SharedMediaPreference.register(adapter) RecipientPreference.register(adapter) InternalPreference.register(adapter) GroupDescriptionPreference.register(adapter) LegacyGroupPreference.register(adapter) viewModel.state.observe(viewLifecycleOwner) { state -> if (state.recipient != Recipient.UNKNOWN) { toolbarAvatar.buildOptions() .withQuickContactEnabled(false) .withUseSelfProfileAvatar(false) .withFixedSize(ViewUtil.dpToPx(80)) .load(state.recipient) state.withRecipientSettingsState { toolbarTitle.text = state.recipient.getDisplayName(requireContext()) } state.withGroupSettingsState { toolbarTitle.text = it.groupTitle toolbar.menu.findItem(R.id.action_edit).isVisible = it.canEditGroupAttributes } } adapter.submitList(getConfiguration(state).toMappingModelList()) { if (state.isLoaded) { (view?.parent as? ViewGroup)?.doOnPreDraw { callback.onContentWillRender() } } } } viewModel.events.observe(viewLifecycleOwner) { event -> @Exhaustive when (event) { is ConversationSettingsEvent.AddToAGroup -> handleAddToAGroup(event) is ConversationSettingsEvent.AddMembersToGroup -> handleAddMembersToGroup(event) ConversationSettingsEvent.ShowGroupHardLimitDialog -> showGroupHardLimitDialog() is ConversationSettingsEvent.ShowAddMembersToGroupError -> showAddMembersToGroupError(event) is ConversationSettingsEvent.ShowGroupInvitesSentDialog -> showGroupInvitesSentDialog(event) is ConversationSettingsEvent.ShowMembersAdded -> showMembersAdded(event) is ConversationSettingsEvent.InitiateGroupMigration -> GroupsV1MigrationInitiationBottomSheetDialogFragment.showForInitiation(parentFragmentManager, event.recipientId) } } } private fun getConfiguration(state: ConversationSettingsState): DSLConfiguration { return configure { if (state.recipient == Recipient.UNKNOWN) { return@configure } customPref( AvatarPreference.Model( recipient = state.recipient, onAvatarClick = { avatar -> requireActivity().apply { startActivity( AvatarPreviewActivity.intentFromRecipientId(this, state.recipient.id), AvatarPreviewActivity.createTransitionBundle(this, avatar) ) } } ) ) state.withRecipientSettingsState { customPref(BioTextPreference.RecipientModel(recipient = state.recipient)) } state.withGroupSettingsState { groupState -> val groupMembershipDescription = if (groupState.groupId.isV1) { String.format("%s · %s", groupState.membershipCountDescription, getString(R.string.ManageGroupActivity_legacy_group)) } else if (!groupState.canEditGroupAttributes && groupState.groupDescription.isNullOrEmpty()) { groupState.membershipCountDescription } else { null } customPref( BioTextPreference.GroupModel( groupTitle = groupState.groupTitle, groupMembershipDescription = groupMembershipDescription ) ) if (groupState.groupId.isV2) { customPref( GroupDescriptionPreference.Model( groupId = groupState.groupId, groupDescription = groupState.groupDescription, descriptionShouldLinkify = groupState.groupDescriptionShouldLinkify, canEditGroupAttributes = groupState.canEditGroupAttributes, onEditGroupDescription = { startActivity(EditProfileActivity.getIntentForGroupProfile(requireActivity(), groupState.groupId)) }, onViewGroupDescription = { GroupDescriptionDialog.show(childFragmentManager, groupState.groupId, null, groupState.groupDescriptionShouldLinkify) } ) ) } else if (groupState.legacyGroupState != LegacyGroupPreference.State.NONE) { customPref( LegacyGroupPreference.Model( state = groupState.legacyGroupState, onLearnMoreClick = { GroupsLearnMoreBottomSheetDialogFragment.show(parentFragmentManager) }, onUpgradeClick = { viewModel.initiateGroupUpgrade() }, onMmsWarningClick = { startActivity(Intent(requireContext(), InviteActivity::class.java)) } ) ) } } state.withRecipientSettingsState { recipientState -> if (recipientState.displayInternalRecipientDetails) { customPref( InternalPreference.Model( recipient = state.recipient, onDisableProfileSharingClick = { viewModel.disableProfileSharing() } ) ) } } customPref( ButtonStripPreference.Model( state = state.buttonStripState, onVideoClick = { CommunicationActions.startVideoCall(requireActivity(), state.recipient) }, onAudioClick = { CommunicationActions.startVoiceCall(requireActivity(), state.recipient) }, onMuteClick = { if (!state.buttonStripState.isMuted) { MuteDialog.show(requireContext(), viewModel::setMuteUntil) } else { MaterialAlertDialogBuilder(requireContext()) .setMessage(state.recipient.muteUntil.formatMutedUntil(requireContext())) .setPositiveButton(R.string.ConversationSettingsFragment__unmute) { dialog, _ -> viewModel.unmute() dialog.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() } }, onSearchClick = { val intent = ConversationIntents.createBuilder(requireContext(), state.recipient.id, state.threadId) .withSearchOpen(true) .build() startActivity(intent) requireActivity().finish() } ) ) dividerPref() val summary = DSLSettingsText.from(formatDisappearingMessagesLifespan(state.disappearingMessagesLifespan)) val icon = if (state.disappearingMessagesLifespan <= 0) { R.drawable.ic_update_timer_disabled_16 } else { R.drawable.ic_update_timer_16 } var enabled = true state.withGroupSettingsState { enabled = it.canEditGroupAttributes } clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__disappearing_messages), summary = summary, icon = DSLSettingsIcon.from(icon), isEnabled = enabled, onClick = { val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToAppSettingsExpireTimer() .setInitialValue(state.disappearingMessagesLifespan) .setRecipientId(state.recipient.id) .setForResultMode(false) navController.navigate(action) } ) clickPref( title = DSLSettingsText.from(R.string.preferences__chat_color_and_wallpaper), icon = DSLSettingsIcon.from(R.drawable.ic_color_24), onClick = { startActivity(ChatWallpaperActivity.createIntent(requireContext(), state.recipient.id)) } ) if (!state.recipient.isSelf) { clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__sounds_and_notifications), icon = DSLSettingsIcon.from(R.drawable.ic_speaker_24), onClick = { val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToSoundsAndNotificationsSettingsFragment(state.recipient.id) navController.navigate(action) } ) } state.withRecipientSettingsState { recipientState -> when (recipientState.contactLinkState) { ContactLinkState.OPEN -> { clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__contact_details), icon = DSLSettingsIcon.from(R.drawable.ic_profile_circle_24), onClick = { startActivityForResult(Intent(Intent.ACTION_VIEW, state.recipient.contactUri), REQUEST_CODE_VIEW_CONTACT) } ) } ContactLinkState.ADD -> { clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_as_a_contact), icon = DSLSettingsIcon.from(R.drawable.ic_plus_24), onClick = { startActivityForResult(RecipientExporter.export(state.recipient).asAddContactIntent(), REQUEST_CODE_ADD_CONTACT) } ) } ContactLinkState.NONE -> { } } if (recipientState.identityRecord != null) { clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__view_safety_number), icon = DSLSettingsIcon.from(R.drawable.ic_safety_number_24), onClick = { startActivity(VerifyIdentityActivity.newIntent(requireActivity(), recipientState.identityRecord)) } ) } } if (state.sharedMedia != null && state.sharedMedia.count > 0) { dividerPref() sectionHeaderPref(R.string.recipient_preference_activity__shared_media) customPref( SharedMediaPreference.Model( mediaCursor = state.sharedMedia, mediaIds = state.sharedMediaIds, onMediaRecordClick = { mediaRecord, isLtr -> startActivityForResult( MediaPreviewActivity.intentFromMediaRecord(requireContext(), mediaRecord, isLtr), REQUEST_CODE_RETURN_FROM_MEDIA ) } ) ) clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all), onClick = { startActivity(MediaOverviewActivity.forThread(requireContext(), state.threadId)) } ) } state.withRecipientSettingsState { groupState -> if (groupState.selfHasGroups) { dividerPref() val groupsInCommonCount = groupState.allGroupsInCommon.size sectionHeaderPref( DSLSettingsText.from( if (groupsInCommonCount == 0) { getString(R.string.ManageRecipientActivity_no_groups_in_common) } else { resources.getQuantityString( R.plurals.ManageRecipientActivity_d_groups_in_common, groupsInCommonCount, groupsInCommonCount ) } ) ) customPref( LargeIconClickPreference.Model( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_to_a_group), icon = DSLSettingsIcon.from(R.drawable.add_to_a_group, NO_TINT), onClick = { viewModel.onAddToGroup() } ) ) for (group in groupState.groupsInCommon) { customPref( RecipientPreference.Model( recipient = group, onClick = { CommunicationActions.startConversation(requireActivity(), group, null) requireActivity().finish() } ) ) } if (groupState.canShowMoreGroupsInCommon) { customPref( LargeIconClickPreference.Model( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all), icon = DSLSettingsIcon.from(R.drawable.show_more, NO_TINT), onClick = { viewModel.revealAllMembers() } ) ) } } } state.withGroupSettingsState { groupState -> val memberCount = groupState.allMembers.size if (groupState.canAddToGroup || memberCount > 0) { dividerPref() sectionHeaderPref(DSLSettingsText.from(resources.getQuantityString(R.plurals.ContactSelectionListFragment_d_members, memberCount, memberCount))) } if (groupState.canAddToGroup) { customPref( LargeIconClickPreference.Model( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__add_members), icon = DSLSettingsIcon.from(R.drawable.add_to_a_group, NO_TINT), onClick = { viewModel.onAddToGroup() } ) ) } for (member in groupState.members) { customPref( RecipientPreference.Model( recipient = member.member, isAdmin = member.isAdmin, onClick = { RecipientBottomSheetDialogFragment.create(member.member.id, groupState.groupId).show(parentFragmentManager, "BOTTOM") } ) ) } if (groupState.canShowMoreGroupMembers) { customPref( LargeIconClickPreference.Model( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__see_all), icon = DSLSettingsIcon.from(R.drawable.show_more, NO_TINT), onClick = { viewModel.revealAllMembers() } ) ) } if (state.recipient.isPushV2Group) { dividerPref() clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__group_link), summary = DSLSettingsText.from(if (groupState.groupLinkEnabled) R.string.preferences_on else R.string.preferences_off), icon = DSLSettingsIcon.from(R.drawable.ic_link_16), onClick = { ShareableGroupLinkDialogFragment.create(groupState.groupId.requireV2()).show(parentFragmentManager, "DIALOG") } ) clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__requests_and_invites), icon = DSLSettingsIcon.from(R.drawable.ic_update_group_add_16), onClick = { startActivity(ManagePendingAndRequestingMembersActivity.newIntent(requireContext(), groupState.groupId.requireV2())) } ) if (groupState.isSelfAdmin) { clickPref( title = DSLSettingsText.from(R.string.ConversationSettingsFragment__permissions), icon = DSLSettingsIcon.from(R.drawable.ic_lock_24), onClick = { val action = ConversationSettingsFragmentDirections.actionConversationSettingsFragmentToPermissionsSettingsFragment(ParcelableGroupId.from(groupState.groupId)) navController.navigate(action) } ) } } if (groupState.canLeave) { dividerPref() clickPref( title = DSLSettingsText.from(R.string.conversation__menu_leave_group, alertTint), icon = DSLSettingsIcon.from(leaveIcon), onClick = { LeaveGroupDialog.handleLeavePushGroup(requireActivity(), groupState.groupId.requirePush(), null) } ) } } if (state.canModifyBlockedState) { state.withRecipientSettingsState { dividerPref() } state.withGroupSettingsState { if (!it.canLeave) { dividerPref() } } val isBlocked = state.recipient.isBlocked val isGroup = state.recipient.isPushGroup val title = when { isBlocked && isGroup -> R.string.ConversationSettingsFragment__unblock_group isBlocked -> R.string.ConversationSettingsFragment__unblock isGroup -> R.string.ConversationSettingsFragment__block_group else -> R.string.ConversationSettingsFragment__block } val titleTint = if (isBlocked) null else alertTint val blockUnblockIcon = if (isBlocked) unblockIcon else blockIcon clickPref( title = DSLSettingsText.from(title, titleTint), icon = DSLSettingsIcon.from(blockUnblockIcon), onClick = { if (state.recipient.isBlocked) { BlockUnblockDialog.showUnblockFor(requireContext(), viewLifecycleOwner.lifecycle, state.recipient) { viewModel.unblock() } } else { BlockUnblockDialog.showBlockFor(requireContext(), viewLifecycleOwner.lifecycle, state.recipient) { viewModel.block() } } } ) } } } private fun formatDisappearingMessagesLifespan(disappearingMessagesLifespan: Int): String { return if (disappearingMessagesLifespan <= 0) { getString(R.string.preferences_off) } else { ExpirationUtil.getExpirationDisplayValue(requireContext(), disappearingMessagesLifespan) } } private fun handleAddToAGroup(addToAGroup: ConversationSettingsEvent.AddToAGroup) { startActivity(AddToGroupsActivity.newIntent(requireContext(), addToAGroup.recipientId, addToAGroup.groupMembership)) } private fun handleAddMembersToGroup(addMembersToGroup: ConversationSettingsEvent.AddMembersToGroup) { startActivityForResult( AddMembersActivity.createIntent( requireContext(), addMembersToGroup.groupId, ContactsCursorLoader.DisplayMode.FLAG_PUSH, addMembersToGroup.selectionWarning, addMembersToGroup.selectionLimit, addMembersToGroup.groupMembersWithoutSelf ), REQUEST_CODE_ADD_MEMBERS_TO_GROUP ) } private fun showGroupHardLimitDialog() { GroupLimitDialog.showHardLimitMessage(requireContext()) } private fun showAddMembersToGroupError(showAddMembersToGroupError: ConversationSettingsEvent.ShowAddMembersToGroupError) { Toast.makeText(requireContext(), GroupErrors.getUserDisplayMessage(showAddMembersToGroupError.failureReason), Toast.LENGTH_LONG).show() } private fun showGroupInvitesSentDialog(showGroupInvitesSentDialog: ConversationSettingsEvent.ShowGroupInvitesSentDialog) { GroupInviteSentDialog.showInvitesSent(requireContext(), showGroupInvitesSentDialog.invitesSentTo) } private fun showMembersAdded(showMembersAdded: ConversationSettingsEvent.ShowMembersAdded) { val string = resources.getQuantityString( R.plurals.ManageGroupActivity_added, showMembersAdded.membersAddedCount, showMembersAdded.membersAddedCount ) Snackbar.make(requireView(), string, Snackbar.LENGTH_SHORT).setTextColor(Color.WHITE).show() } private class ConversationSettingsOnUserScrolledAnimationHelper( private val toolbarAvatar: View, private val toolbarTitle: View, private val toolbarBackground: View, toolbarShadow: View ) : ToolbarShadowAnimationHelper(toolbarShadow) { override val duration: Long = 200L private val actionBarSize = ThemeUtil.getThemedDimen(toolbarShadow.context, R.attr.actionBarSize) private val rect = Rect() override fun getAnimationState(recyclerView: RecyclerView): AnimationState { val layoutManager = recyclerView.layoutManager as LinearLayoutManager return if (layoutManager.findFirstVisibleItemPosition() == 0) { val firstChild = requireNotNull(layoutManager.getChildAt(0)) firstChild.getLocalVisibleRect(rect) if (rect.height() <= actionBarSize) { AnimationState.SHOW } else { AnimationState.HIDE } } else { AnimationState.SHOW } } override fun show(duration: Long) { super.show(duration) toolbarAvatar .animate() .setDuration(duration) .translationY(0f) .alpha(1f) toolbarTitle .animate() .setDuration(duration) .translationY(0f) .alpha(1f) toolbarBackground .animate() .setDuration(duration) .alpha(1f) } override fun hide(duration: Long) { super.hide(duration) toolbarAvatar .animate() .setDuration(duration) .translationY(ViewUtil.dpToPx(56).toFloat()) .alpha(0f) toolbarTitle .animate() .setDuration(duration) .translationY(ViewUtil.dpToPx(56).toFloat()) .alpha(0f) toolbarBackground .animate() .setDuration(duration) .alpha(0f) } } interface Callback { fun onContentWillRender() } }
gpl-3.0
google/ground-android
ground/src/main/java/com/google/android/ground/persistence/remote/RemoteStorageModule.kt
1
2805
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.remote import com.google.android.ground.Config import com.google.android.ground.persistence.remote.firestore.FirestoreDataStore import com.google.android.ground.persistence.remote.firestore.FirestoreStorageManager import com.google.android.ground.persistence.remote.firestore.FirestoreUuidGenerator import com.google.android.ground.persistence.uuid.OfflineUuidGenerator import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreSettings import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module abstract class RemoteStorageModule { /** Provides the Firestore implementation of remote data store. */ @Binds @Singleton abstract fun remoteDataStore(ds: FirestoreDataStore): RemoteDataStore /** Provides the Firestore implementation of offline unique id generation. */ @Binds @Singleton abstract fun offlineUuidGenerator(uuidGenerator: FirestoreUuidGenerator): OfflineUuidGenerator /** Provides the Firestore implementation of remote storage manager. */ @Binds @Singleton abstract fun remoteStorageManager(fsm: FirestoreStorageManager): RemoteStorageManager companion object { @Provides fun firebaseFirestoreSettings(): FirebaseFirestoreSettings { return FirebaseFirestoreSettings.Builder() .setPersistenceEnabled(Config.FIRESTORE_PERSISTENCE_ENABLED) .build() } @Provides @Singleton fun firebaseFirestore(settings: FirebaseFirestoreSettings): FirebaseFirestore { val firestore = FirebaseFirestore.getInstance() firestore.firestoreSettings = settings FirebaseFirestore.setLoggingEnabled(Config.FIRESTORE_LOGGING_ENABLED) return firestore } /** Returns a reference to the default Storage bucket. */ @Provides @Singleton fun firebaseStorageReference(): StorageReference { return FirebaseStorage.getInstance().reference } } }
apache-2.0
mdanielwork/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/ext/logback/LogbackDelegateMemberContributor.kt
1
5539
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.ext.logback import com.intellij.openapi.util.Key import com.intellij.psi.* import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.NameHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTreeUtil import groovy.lang.Closure.DELEGATE_FIRST import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrMethodWrapper import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods import org.jetbrains.plugins.groovy.lang.resolve.wrapClassType class LogbackDelegateMemberContributor : NonCodeMembersContributor() { override fun getParentClassName(): String = componentDelegateFqn override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) { if (!processor.shouldProcessMethods()) { return } val name = processor.getHint(NameHint.KEY)?.getName(state) val componentClass = getComponentClass(place) ?: return val componentProcessor = ComponentProcessor(processor, place, name) if (name == null) { componentClass.processDeclarations(componentProcessor, state, null, place) } else { for (prefix in arrayOf("add", "set")) { for (method in componentClass.findMethodsByName(prefix + name.capitalize(), true)) { if (!componentProcessor.execute(method, state)) return } } } } private fun getComponentClass(place: PsiElement): PsiClass? { val reference = place as? GrReferenceExpression ?: return null if (reference.isQualified) return null val closure = PsiTreeUtil.getParentOfType(reference, GrClosableBlock::class.java) ?: return null val call = getContainingCall(closure) ?: return null val arguments = PsiUtil.getAllArguments(call) if (arguments.isEmpty()) return null val lastIsClosure = (arguments.last().type as? PsiClassType)?.resolve()?.qualifiedName == GROOVY_LANG_CLOSURE val componentArgumentIndex = (if (lastIsClosure) arguments.size - 1 else arguments.size) - 1 val componentArgument = arguments.getOrNull(componentArgumentIndex) val componentType = ResolveUtil.unwrapClassType(componentArgument?.type) as? PsiClassType return componentType?.resolve() } class ComponentProcessor(val delegate: PsiScopeProcessor, val place: PsiElement, val name: String?) : PsiScopeProcessor { override fun execute(method: PsiElement, state: ResolveState): Boolean { if (method !is PsiMethod) return true @Suppress("CascadeIf") val prefix = if (GroovyPropertyUtils.isSetterLike(method, "set")) { if (!delegate.execute(method, state)) return false "set" } else if (GroovyPropertyUtils.isSetterLike(method, "add")) { val newName = method.name.replaceFirst("add", "set") val wrapper = GrMethodWrapper.wrap(method, newName) if (!delegate.execute(wrapper, state)) return false "add" } else { return true } val propertyName = method.name.removePrefix(prefix).decapitalize() if (name != null && name != propertyName) return true val parameter = method.parameterList.parameters.singleOrNull() ?: return true val classType = wrapClassType(parameter.type, place) ?: return true val wrappedBase = GrLightMethodBuilder(place.manager, propertyName).apply { returnType = PsiType.VOID navigationElement = method } // (name, clazz) // (name, clazz, configuration) wrappedBase.copy().apply { addParameter("name", JAVA_LANG_STRING) addParameter("clazz", classType) addParameter("configuration", GROOVY_LANG_CLOSURE, true) }.let { if (!delegate.execute(it, state)) return false } // (clazz) // (clazz, configuration) wrappedBase.copy().apply { addParameter("clazz", classType) addAndGetParameter("configuration", GROOVY_LANG_CLOSURE, true).apply { putUserData(DELEGATES_TO_KEY, componentDelegateFqn) putUserData(DELEGATES_TO_STRATEGY_KEY, DELEGATE_FIRST) } }.let { if (!delegate.execute(it, state)) return false } return true } override fun <T : Any?> getHint(hintKey: Key<T>): T? = if (hintKey == ElementClassHint.KEY) { @Suppress("UNCHECKED_CAST") ElementClassHint { it == ElementClassHint.DeclarationKind.METHOD } as T } else { null } } }
apache-2.0
mdanielwork/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/driver/ExtendedJTreeDriver.kt
1
10942
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.driver import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader import com.intellij.testGuiFramework.cellReader.ProjectTreeCellReader import com.intellij.testGuiFramework.cellReader.SettingsTreeCellReader import com.intellij.testGuiFramework.impl.GuiRobotHolder import com.intellij.testGuiFramework.impl.GuiTestUtilKt import com.intellij.testGuiFramework.util.FinderPredicate import com.intellij.testGuiFramework.util.Predicate import com.intellij.ui.treeStructure.SimpleTree import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.tree.TreeUtil import org.fest.assertions.Assertions import org.fest.reflect.core.Reflection import org.fest.swing.core.MouseButton import org.fest.swing.core.Robot import org.fest.swing.driver.ComponentPreconditions import org.fest.swing.driver.JTreeDriver import org.fest.swing.exception.ActionFailedException import org.fest.swing.exception.LocationUnavailableException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Timeout import java.awt.Point import java.awt.Rectangle import javax.swing.JTree import javax.swing.plaf.basic.BasicTreeUI import javax.swing.tree.TreePath open class ExtendedJTreeDriver(robot: Robot = GuiRobotHolder.robot) : JTreeDriver(robot) { private val DEFAULT_FIND_PATH_ATTEMPTS: Int = 3 protected data class PathInfo(val expandPoint: Point, val clickPoint: Point, val toggleClickCount: Int, val bounds: Rectangle) init { val resultReader = when (javaClass.name) { "com.intellij.openapi.options.newEditor.SettingsTreeView\$MyTree" -> SettingsTreeCellReader() "com.intellij.ide.projectView.impl.ProjectViewPane\$1" -> ProjectTreeCellReader() else -> ExtendedJTreeCellReader() } this.replaceCellReader(resultReader) } fun clickPath(tree: JTree, treePath: TreePath, button: MouseButton = MouseButton.LEFT_BUTTON, times: Int = 1, attempts: Int = DEFAULT_FIND_PATH_ATTEMPTS) { val pathInfo = tree.scrollToPath(treePath) robot.click(tree, pathInfo.clickPoint, button, times) //check that path is selected or click it again if (!tree.checkPathIsSelected(treePath)) { if (attempts == 0) throw ExtendedJTreeException("Unable to click path in $DEFAULT_FIND_PATH_ATTEMPTS " + "attempts due to it high mutability. Maybe this path is loading async.") clickPath(tree, treePath, button, times, attempts - 1) } } protected fun JTree.scrollToPath(path: TreePath) : PathInfo { robot.waitForIdle() val result = GuiTestUtilKt.computeOnEdt { ComponentPreconditions.checkEnabledAndShowing(this) val pathInfo = this.getPathInfo(path) scrollRectToVisible(pathInfo.bounds) pathInfo }!! robot.waitForIdle() return result } private fun JTree.isInnerExpandControl(): Boolean = this is SimpleTree || this is TreeTable private fun JTree.getExpandCoord(path: TreePath): Int { val bounds = this.getPathBounds(path) return if (isInnerExpandControl()) { // expand/collapse symbol is located inside path bounds bounds.x + 1 } else { // in other trees the expand/collapse symbol is located out of the path bounds // so we have to expand the bounds to the left val expandControlRange = TreeUtil.getExpandControlRange(this, path) when { expandControlRange != null -> expandControlRange.from + (expandControlRange.to - expandControlRange.from) / 2 bounds.x < bounds.height / 2 -> x + 8 else -> bounds.x - bounds.height / 2 } } } private fun JTree.refineToggleClickCount(): Int = if (isInnerExpandControl()) { // expand/collapse symbol is located inside path bounds // so the way how to expand/collapse node is controlled by the tree toggleClickCount } else { // in other trees the expand/collapse symbol is located out of the path bounds // we manually expand/collapse the node 1 } // to be overridden by CheckboxTree to take into account size of the checkbox control protected open fun getLabelXCoord(jTree: JTree, path: TreePath): Int = jTree.getPathBounds(path).x + 1 private fun JTree.getScrollBounds(path: TreePath): Rectangle { val bounds = this.getPathBounds(path) return if (isInnerExpandControl()) { bounds } else { val expandControlRange = TreeUtil.getExpandControlRange(this, path) Rectangle(expandControlRange?.from ?: x, bounds.y, bounds.width, bounds.height) } } private fun JTree.getPathInfo(path: TreePath): PathInfo { val bounds = this.getPathBounds(path) val clickY = bounds.y + bounds.height / 2 return PathInfo( expandPoint = Point(getExpandCoord(path), clickY), clickPoint = Point(getLabelXCoord(this, path), clickY), toggleClickCount = refineToggleClickCount(), bounds = getScrollBounds(path) ) } private fun JTree.makeVisible(path: TreePath, expandWhenFound: Boolean): Boolean { var changed = false if (path.pathCount > 1) { changed = makeParentVisible(path) } return if (!expandWhenFound) { changed } else { expandTreePath(path) waitForChildrenToShowUp(path) true } } private fun JTree.makeParentVisible(path: TreePath): Boolean { val changed = this.makeVisible(path.parentPath, true) if (changed) robot.waitForIdle() return changed } private fun JTree.expandTreePath(path: TreePath) { GuiTestUtilKt.runOnEdt { if (!isExpanded(path)) expandPath(path) } } private fun JTree.waitForChildrenToShowUp(path: TreePath) { try { GuiTestUtilKt.waitUntil("Waiting for children are shown up", Timeout.timeout(robot.settings().timeoutToBeVisible().toLong())) { this.childCount(path) != 0 } } catch (waitTimedOutError: WaitTimedOutError) { throw LocationUnavailableException(waitTimedOutError.message!!) } } /** * @return true if the required path is selected * @return false if the incorrect path is selected * @throws ExtendedJTreeException if no one row or several ones are selected * */ private fun JTree.checkPathIsSelected(treePath: TreePath): Boolean { val selectedPaths = selectionPaths if (selectedPaths.isEmpty()) throw ExtendedJTreeException("No one row has been selected at all") if (selectedPaths.size > 1) throw ExtendedJTreeException("More than one row has been selected") val selectedPath = selectedPaths.first() return treePath.lastPathComponent == selectedPath.lastPathComponent } /** * node that has as child LoadingNode */ class LoadingNodeException(val node: Any, var treePath: TreePath?) : Exception("Meet loading node: $node (${treePath?.path?.joinToString()}") private fun JTree.childCount(path: TreePath): Int { return GuiTestUtilKt.computeOnEdt { val lastPathComponent = path.lastPathComponent model.getChildCount(lastPathComponent) }!! } fun expandPath(tree: JTree, treePath: TreePath) { // do not try to expand leaf if (GuiTestUtilKt.computeOnEdt { tree.model.isLeaf(treePath.lastPathComponent) } != false) return val info = tree.scrollToPath(treePath) if (tree.isExpanded(treePath).not()) tree.toggleCell(info.expandPoint, info.toggleClickCount) } fun collapsePath(tree: JTree, treePath: TreePath) { // do not try to collapse leaf if (GuiTestUtilKt.computeOnEdt { tree.model.isLeaf(treePath.lastPathComponent) } != false) return val info = tree.scrollToPath(treePath) if (tree.isExpanded(treePath)) tree.toggleCell(info.expandPoint, info.toggleClickCount) } fun selectPath(tree: JTree, treePath: TreePath) { val pathInfo = tree.scrollToPath(treePath) val isSelected = GuiTestUtilKt.computeOnEdt { tree.selectionCount == 1 && tree.isPathSelected(treePath) } ?: false robot.waitForIdle() if (isSelected.not()) robot.click(tree, pathInfo.clickPoint) } private fun JTree.toggleCell(p: Point, toggleClickCount: Int) { if (toggleClickCount == 0) { toggleRowThroughTreeUIExt(p) robot.waitForIdle() } else { robot.click(this, p, MouseButton.LEFT_BUTTON, toggleClickCount) } } private fun JTree.toggleRowThroughTreeUIExt(p: Point) { GuiTestUtilKt.runOnEdt { if (ui !is BasicTreeUI) throw ActionFailedException.actionFailure("Can't toggle row for $ui") else this.toggleExpandState(p) } } private fun JTree.toggleExpandState(pathLocation: Point) { val path = getPathForLocation(pathLocation.x, pathLocation.y) val treeUI = ui Assertions.assertThat(treeUI).isInstanceOf(BasicTreeUI::class.java) Reflection.method("toggleExpandState").withParameterTypes(TreePath::class.java).`in`(treeUI).invoke(path) } fun findPath(tree: JTree, stringPath: List<String>, predicate: FinderPredicate = Predicate.equality): TreePath { fun <T> List<T>.list2tree() = map { subList(0, indexOf(it) + 1) } lateinit var path: TreePath stringPath .list2tree() .forEach { path = ExtendedJTreePathFinder(tree).findMatchingPathByPredicate(predicate, it) expandPath(tree, path) } return path } fun findPathToNode(tree: JTree, node: String, predicate: FinderPredicate = Predicate.equality): TreePath { fun JTree.iterateChildren(root: Any, node: String, rootPath: TreePath, predicate: FinderPredicate): TreePath? { for (index in 0 until (GuiTestUtilKt.computeOnEdt { this.model.getChildCount(root) } ?: 0)) { val child = GuiTestUtilKt.computeOnEdt { this.model.getChild(root, index) }!! val childPath = TreePath(arrayOf(*rootPath.path, child)) if (predicate(child.toString(), node)) { return childPath } if (GuiTestUtilKt.computeOnEdt { this.model.isLeaf(child) } == false) { makeVisible(childPath, true) val found = this.iterateChildren(child, node, childPath, predicate) if (found != null) return found } } return null } val root = GuiTestUtilKt.computeOnEdt { tree.model.root } ?: throw IllegalStateException("root is null") return tree.iterateChildren(root, node, TreePath(root), predicate) ?: throw LocationUnavailableException("Node `$node` not found") } fun exists(tree: JTree, pathStrings: List<String>, predicate: FinderPredicate = Predicate.equality): Boolean { return try { findPath(tree, pathStrings, predicate) true } catch (e: LocationUnavailableException) { false } } } // end of class class ExtendedJTreeException(message: String) : Exception(message)
apache-2.0
aerisweather/AerisAndroidSDK
Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/di/RoomModule.kt
1
1087
package com.example.demoaerisproject.di import android.content.Context import androidx.room.Room import com.example.demoaerisproject.data.room.MyPlaceDao import com.example.demoaerisproject.data.room.MyPlaceDatabase import com.example.demoaerisproject.data.room.MyPlaceRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RoomModule { @Provides fun provideMyPlaceRepository(myPlaceDao: MyPlaceDao): MyPlaceRepository { return MyPlaceRepository(myPlaceDao = myPlaceDao) } @Provides fun provideMyPlaceDao(myPlaceDatabase: MyPlaceDatabase): MyPlaceDao { return myPlaceDatabase.myPlaceDao() } @Provides @Singleton fun providesMyPlaceDatabase(@ApplicationContext appContext: Context):MyPlaceDatabase { return Room.databaseBuilder(appContext, MyPlaceDatabase::class.java, "my_place_database").build() } }
mit
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/Node.kt
9
2010
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.analysis.problemsView.toolWindow import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.PresentableNodeDescriptor import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.ui.tree.LeafState import com.intellij.ui.tree.TreePathUtil.pathToCustomNode abstract class Node : PresentableNodeDescriptor<Node?>, LeafState.Supplier { protected constructor(project: Project) : super(project, null) protected constructor(parent: Node) : super(parent.project, parent) open val descriptor: OpenFileDescriptor? get() = null protected abstract fun update(project: Project, presentation: PresentationData) abstract override fun getName(): String override fun toString() = name open fun getChildren(): Collection<Node> = emptyList() open fun getVirtualFile(): VirtualFile? = null open fun getNavigatable(): Navigatable? = descriptor override fun getElement() = this override fun update(presentation: PresentationData) { if (myProject == null || myProject.isDisposed) return update(myProject, presentation) } fun getPath() = pathToCustomNode(this) { node: Node? -> node?.getParent(Node::class.java) }!! fun <T> getParent(type: Class<T>): T? { val parent = parentDescriptor ?: return null @Suppress("UNCHECKED_CAST") if (type.isInstance(parent)) return parent as T throw IllegalStateException("unexpected node " + parent.javaClass) } fun <T> findAncestor(type: Class<T>): T? { var parent = parentDescriptor while (parent != null) { @Suppress("UNCHECKED_CAST") if (type.isInstance(parent)) return parent as T parent = parent.parentDescriptor } return null } }
apache-2.0
burntcookie90/redditbot
bot/src/main/kotlin/io/dwak/reddit/bot/network/reddit/RedditService.kt
1
1620
package io.dwak.reddit.bot.network.reddit import io.dwak.reddit.bot.model.reddit.RedditCommentResponse import io.dwak.reddit.bot.model.reddit.RedditFlairResponse import io.dwak.reddit.bot.model.reddit.RedditListing import retrofit2.http.* import rx.Observable interface RedditService { @GET("{subreddit}/about/unmoderated") fun unmoderated(@Path("subreddit") subreddit : String) : Observable<RedditListing> @FormUrlEncoded @POST("/api/remove") fun removePost(@Field("id") id : String, @Field("spam") spam : Boolean) : Observable<Unit> @FormUrlEncoded @POST("/api/comment") fun postComment(@Field("api_type") apiType : String = "json", @Field("thing_id") thingId : String, @Field("text") text : String) : Observable<RedditCommentResponse> @FormUrlEncoded @POST("/api/distinguish") fun distinguish(@Field("api_type") apiType : String = "json", @Field("id") id : String, @Field("how") how : String = "yes") : Observable<Unit> @FormUrlEncoded @POST("{subreddit}/api/flairselector") fun flairSelector(@Path("subreddit") subreddit : String, @Field("link") fullname : String) : Observable<RedditFlairResponse> @FormUrlEncoded @POST("{subreddit}/api/selectflair") fun selectFlair(@Path("subreddit") subreddit : String, @Field("api_type") apiType : String = "json", @Field("flair_template_id") flairTemplateId : String, @Field("link") fullname: String, @Field("name") username : String) : Observable<Unit> }
mit
android/location-samples
ForegroundLocationUpdates/app/src/main/java/com/google/android/gms/location/sample/foregroundlocation/ui/ServiceUnvailableScreen.kt
1
2451
/* * Copyright (C) 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.android.gms.location.sample.foregroundlocation.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons.Filled import androidx.compose.material.icons.filled.Warning import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.android.gms.location.sample.foregroundlocation.R import com.google.android.gms.location.sample.foregroundlocation.ui.theme.ForegroundLocationTheme @Composable fun ServiceUnavailableScreen() { Column( verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Text( text = stringResource(id = R.string.play_services_unavailable), style = MaterialTheme.typography.h6, textAlign = TextAlign.Center ) Icon( Filled.Warning, tint = MaterialTheme.colors.primary, contentDescription = null, modifier = Modifier.size(48.dp) ) } } @Preview(showBackground = true) @Composable fun ServiceUnavailableScreenPreview() { ForegroundLocationTheme { ServiceUnavailableScreen() } }
apache-2.0
google-developer-training/basic-android-kotlin-compose-training-reply-app
app/src/androidTest/java/com/example/reply/test/ComposeTestRuleExtensions.kt
1
3061
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.test import androidx.activity.ComponentActivity import androidx.annotation.StringRes import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.rules.ActivityScenarioRule /** * Finds a semantics node with the given string resource id. * * The [onNodeWithText] finder provided by compose ui test API, doesn't support usage of * string resource id to find the semantics node. This extension function accesses string resource * using underlying activity property and passes it to [onNodeWithText] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.onNodeWithStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithText(activity.getString(id)) /** * Finds a semantics node from the content description with the given string resource id. * * The [onNodeWithContentDescription] finder provided by compose ui test API, doesn't support usage * of string resource id to find the semantics node from the node's content description. * This extension function accesses string resource using underlying activity property * and passes it to [onNodeWithContentDescription] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A> .onNodeWithContentDescriptionForStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithContentDescription(activity.getString(id)) /** * Finds a semantics node from the content description with the given string resource id. * * The [onNodeWithTag] finder provided by compose ui test API, doesn't support usage of * string resource id to find the semantics node from the node's test tag. * This extension function accesses string resource using underlying activity property * and passes it to [onNodeWithTag] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A> .onNodeWithTagForStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithTag(activity.getString(id))
apache-2.0
Piasy/OkBuck
libraries/kotlinandroidlibrary/src/main/java/com/uber/okbuck/java/KotlinLibActivity.kt
2
698
package com.uber.okbuck.java import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar import com.uber.okbuck.kotlin.android.R import kotlinx.android.synthetic.main.activity_kotlin_lib.* class KotlinLibActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotlin_lib) setSupportActionBar(toolbar) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } }
mit
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignDatumTypeServiceImpl.kt
1
853
package top.zbeboy.isy.service.graduate.design import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import top.zbeboy.isy.domain.tables.daos.GraduationDesignDatumTypeDao import top.zbeboy.isy.domain.tables.pojos.GraduationDesignDatumType import javax.annotation.Resource /** * Created by zbeboy 2018-01-29 . **/ @Service("graduationDesignDatumTypeService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class GraduationDesignDatumTypeServiceImpl : GraduationDesignDatumTypeService { @Resource open lateinit var graduationDesignDatumTypeDao: GraduationDesignDatumTypeDao override fun findAll(): List<GraduationDesignDatumType> { return graduationDesignDatumTypeDao.findAll() } }
mit
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/identity/apis/organizations/AppSettings.kt
2
795
package co.smartreceipts.android.identity.apis.organizations import co.smartreceipts.android.model.Category import co.smartreceipts.android.model.Column import co.smartreceipts.android.model.PaymentMethod import co.smartreceipts.android.model.Receipt import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class AppSettings( @Json(name = "Configurations") val configurations: Configurations, @Json(name = "Settings") val preferences: Map<String, Any?>, @Json(name = "Categories") val categories: List<Category>, @Json(name = "PaymentMethods") val paymentMethods: List<PaymentMethod>, @Json(name = "CSVColumns") val csvColumns: List<Column<Receipt>>, @Json(name = "PDFColumns") val pdfColumns: List<Column<Receipt>> )
agpl-3.0
flesire/ontrack
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/service/GitServiceImpl.kt
1
40304
package net.nemerosa.ontrack.extension.git.service import net.nemerosa.ontrack.common.FutureUtils import net.nemerosa.ontrack.common.asOptional import net.nemerosa.ontrack.extension.api.model.BuildDiffRequest import net.nemerosa.ontrack.extension.api.model.BuildDiffRequestDifferenceProjectException import net.nemerosa.ontrack.extension.git.branching.BranchingModelService import net.nemerosa.ontrack.extension.git.model.* import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationProperty import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationPropertyType import net.nemerosa.ontrack.extension.git.repository.GitRepositoryHelper import net.nemerosa.ontrack.extension.git.support.NoGitCommitPropertyException import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService import net.nemerosa.ontrack.extension.issues.model.Issue import net.nemerosa.ontrack.extension.issues.model.IssueServiceNotConfiguredException import net.nemerosa.ontrack.extension.scm.model.SCMBuildView import net.nemerosa.ontrack.extension.scm.model.SCMChangeLogFileChangeType import net.nemerosa.ontrack.extension.scm.model.SCMPathInfo import net.nemerosa.ontrack.extension.scm.service.AbstractSCMChangeLogService import net.nemerosa.ontrack.extension.scm.service.SCMUtilsService import net.nemerosa.ontrack.git.GitRepositoryClient import net.nemerosa.ontrack.git.GitRepositoryClientFactory import net.nemerosa.ontrack.git.exceptions.GitRepositorySyncException import net.nemerosa.ontrack.git.model.* import net.nemerosa.ontrack.job.* import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.security.ProjectConfig import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.model.support.* import net.nemerosa.ontrack.tx.TransactionService import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.PlatformTransactionManager import org.springframework.transaction.annotation.Transactional import org.springframework.transaction.support.TransactionTemplate import java.lang.String.format import java.util.* import java.util.concurrent.Future import java.util.function.BiConsumer import java.util.function.Predicate import java.util.stream.Stream @Service @Transactional class GitServiceImpl( structureService: StructureService, propertyService: PropertyService, private val jobScheduler: JobScheduler, private val securityService: SecurityService, private val transactionService: TransactionService, private val applicationLogService: ApplicationLogService, private val gitRepositoryClientFactory: GitRepositoryClientFactory, private val buildGitCommitLinkService: BuildGitCommitLinkService, private val gitConfigurators: Collection<GitConfigurator>, private val scmService: SCMUtilsService, private val gitRepositoryHelper: GitRepositoryHelper, private val branchingModelService: BranchingModelService, private val entityDataService: EntityDataService, transactionManager: PlatformTransactionManager ) : AbstractSCMChangeLogService<GitConfiguration, GitBuildInfo, GitChangeLogIssue>(structureService, propertyService), GitService, JobOrchestratorSupplier { private val logger = LoggerFactory.getLogger(GitService::class.java) private val transactionTemplate = TransactionTemplate(transactionManager) override fun forEachConfiguredProject(consumer: BiConsumer<Project, GitConfiguration>) { structureService.projectList .forEach { project -> val configuration = getProjectConfiguration(project) if (configuration != null) { consumer.accept(project, configuration) } } } override fun forEachConfiguredBranch(consumer: BiConsumer<Branch, GitBranchConfiguration>) { for (project in structureService.projectList) { forEachConfiguredBranchInProject(project, consumer::accept) } } override fun forEachConfiguredBranchInProject(project: Project, consumer: (Branch, GitBranchConfiguration) -> Unit) { structureService.getBranchesForProject(project.id) .filter { branch -> branch.type != BranchType.TEMPLATE_DEFINITION } .forEach { branch -> val configuration = getBranchConfiguration(branch) if (configuration != null) { consumer(branch, configuration) } } } override fun collectJobRegistrations(): Stream<JobRegistration> { val jobs = ArrayList<JobRegistration>() // Indexation of repositories, based on projects actually linked forEachConfiguredProject(BiConsumer { _, configuration -> jobs.add(getGitIndexationJobRegistration(configuration)) }) // Synchronisation of branch builds with tags when applicable forEachConfiguredBranch(BiConsumer { branch, branchConfiguration -> // Build/tag sync job if (branchConfiguration.buildTagInterval > 0 && branchConfiguration.buildCommitLink?.link is IndexableBuildGitCommitLink<*>) { jobs.add( JobRegistration.of(createBuildSyncJob(branch)) .everyMinutes(branchConfiguration.buildTagInterval.toLong()) ) } }) // OK return jobs.stream() } override fun isBranchConfiguredForGit(branch: Branch): Boolean { return getBranchConfiguration(branch) != null } override fun launchBuildSync(branchId: ID, synchronous: Boolean): Future<*>? { // Gets the branch val branch = structureService.getBranch(branchId) // Gets its configuration val branchConfiguration = getBranchConfiguration(branch) // If valid, launches a job return if (branchConfiguration != null && branchConfiguration.buildCommitLink?.link is IndexableBuildGitCommitLink<*>) { if (synchronous) { buildSync<Any>(branch, branchConfiguration, JobRunListener.logger(logger)) null } else { jobScheduler.fireImmediately(getGitBranchSyncJobKey(branch)).orElse(null) } } else { null } } @Transactional override fun changeLog(request: BuildDiffRequest): GitChangeLog { transactionService.start().use { ignored -> // Gets the two builds var buildFrom = structureService.getBuild(request.from) var buildTo = structureService.getBuild(request.to) // Ordering of builds if (buildFrom.id() > buildTo.id()) { val t = buildFrom buildFrom = buildTo buildTo = t } // Gets the two associated projects val project = buildFrom.branch.project val otherProject = buildTo.branch.project // Checks the project if (project.id() != otherProject.id()) { throw BuildDiffRequestDifferenceProjectException() } // Project Git configuration val oProjectConfiguration = getProjectConfiguration(project) if (oProjectConfiguration != null) { // Forces Git sync before var syncError: Boolean try { syncAndWait(oProjectConfiguration) syncError = false } catch (ex: GitRepositorySyncException) { applicationLogService.log( ApplicationLogEntry.error( ex, NameDescription.nd( "git-sync", "Git synchronisation issue" ), oProjectConfiguration.remote ).withDetail("project", project.name) .withDetail("git-name", oProjectConfiguration.name) .withDetail("git-remote", oProjectConfiguration.remote) ) syncError = true } // Change log computation return GitChangeLog( UUID.randomUUID().toString(), project, getSCMBuildView(buildFrom.id), getSCMBuildView(buildTo.id), syncError ) } else { throw GitProjectNotConfiguredException(project.id) } } } protected fun syncAndWait(gitConfiguration: GitConfiguration): Any? { return FutureUtils.wait("Synchronisation for " + gitConfiguration.name, sync(gitConfiguration, GitSynchronisationRequest.SYNC)) } protected fun getRequiredProjectConfiguration(project: Project): GitConfiguration { return getProjectConfiguration(project) ?: throw GitProjectNotConfiguredException(project.id) } protected fun getGitRepositoryClient(project: Project): GitRepositoryClient { return getProjectConfiguration(project)?.gitRepository ?.let { gitRepositoryClientFactory.getClient(it) } ?: throw GitProjectNotConfiguredException(project.id) } override fun getChangeLogCommits(changeLog: GitChangeLog): GitChangeLogCommits { // Gets the client val client = getGitRepositoryClient(changeLog.project) // Gets the build boundaries val buildFrom = changeLog.from.build val buildTo = changeLog.to.build // Commit boundaries var commitFrom = getCommitFromBuild(buildFrom) var commitTo = getCommitFromBuild(buildTo) // Gets the commits var log = client.graph(commitFrom, commitTo) // If log empty, inverts the boundaries if (log.commits.isEmpty()) { val t = commitFrom commitFrom = commitTo commitTo = t log = client.graph(commitFrom, commitTo) } // Consolidation to UI val commits = log.commits val uiCommits = toUICommits(getRequiredProjectConfiguration(changeLog.project), commits) return GitChangeLogCommits( GitUILog( log.plot, uiCommits ) ) } protected fun getCommitFromBuild(build: Build): String { return getBranchConfiguration(build.branch) ?.buildCommitLink ?.getCommitFromBuild(build) ?: throw GitBranchNotConfiguredException(build.branch.id) } override fun getChangeLogIssues(changeLog: GitChangeLog): GitChangeLogIssues { // Commits must have been loaded first val commits: GitChangeLogCommits = changeLog.loadCommits { getChangeLogCommits(it) } // In a transaction transactionService.start().use { _ -> // Configuration val configuration = getRequiredProjectConfiguration(changeLog.project) // Issue service val configuredIssueService = configuration.configuredIssueService.orElse(null) ?: throw IssueServiceNotConfiguredException() // Index of issues, sorted by keys val issues = TreeMap<String, GitChangeLogIssue>() // For all commits in this commit log for (gitUICommit in commits.log.commits) { val keys = configuredIssueService.extractIssueKeysFromMessage(gitUICommit.commit.fullMessage) for (key in keys) { var existingIssue: GitChangeLogIssue? = issues[key] if (existingIssue != null) { existingIssue.add(gitUICommit) } else { val issue = configuredIssueService.getIssue(key) if (issue != null) { existingIssue = GitChangeLogIssue.of(issue, gitUICommit) issues[key] = existingIssue } } } } // List of issues val issuesList = ArrayList(issues.values) // Issues link val issueServiceConfiguration = configuredIssueService.issueServiceConfigurationRepresentation // OK return GitChangeLogIssues(issueServiceConfiguration, issuesList) } } override fun getChangeLogFiles(changeLog: GitChangeLog): GitChangeLogFiles { // Gets the configuration val configuration = getRequiredProjectConfiguration(changeLog.project) // Gets the client for this project val client = gitRepositoryClientFactory.getClient(configuration.gitRepository) // Gets the build boundaries val buildFrom = changeLog.from.build val buildTo = changeLog.to.build // Commit boundaries val commitFrom = getCommitFromBuild(buildFrom) val commitTo = getCommitFromBuild(buildTo) // Diff val diff = client.diff(commitFrom, commitTo) // File change links val fileChangeLinkFormat = configuration.fileAtCommitLink // OK return GitChangeLogFiles( diff.entries.map { entry -> toChangeLogFile(entry).withUrl( getDiffUrl(diff, entry, fileChangeLinkFormat) ) } ) } override fun isPatternFound(gitConfiguration: GitConfiguration, token: String): Boolean { // Gets the client val client = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository) // Scanning return client.isPatternFound(token) } override fun lookupCommit(configuration: GitConfiguration, id: String): GitCommit? { // Gets the client client for this configuration val gitClient = gitRepositoryClientFactory.getClient(configuration.gitRepository) // Gets the commit return gitClient.getCommitFor(id) } override fun getCommitProjectInfo(projectId: ID, commit: String): OntrackGitCommitInfo { return getOntrackGitCommitInfo(structureService.getProject(projectId), commit) } override fun getRemoteBranches(gitConfiguration: GitConfiguration): List<String> { val gitClient = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository) return gitClient.remoteBranches } override fun diff(changeLog: GitChangeLog, patterns: List<String>): String { // Gets the client client for this configuration` val gitClient = getGitRepositoryClient(changeLog.project) // Path predicate val pathFilter = scmService.getPathFilter(patterns) // Gets the build boundaries val buildFrom = changeLog.from.build val buildTo = changeLog.to.build // Commit boundaries val commitFrom = getCommitFromBuild(buildFrom) val commitTo = getCommitFromBuild(buildTo) // Gets the diff return gitClient.unifiedDiff( commitFrom, commitTo, pathFilter ) } override fun download(branch: Branch, path: String): Optional<String> { securityService.checkProjectFunction(branch, ProjectConfig::class.java) return transactionService.doInTransaction { val branchConfiguration = getRequiredBranchConfiguration(branch) val client = gitRepositoryClientFactory.getClient( branchConfiguration.configuration.gitRepository ) client.download(branchConfiguration.branch, path).asOptional() } } override fun projectSync(project: Project, request: GitSynchronisationRequest): Ack { securityService.checkProjectFunction(project, ProjectConfig::class.java) val projectConfiguration = getProjectConfiguration(project) if (projectConfiguration != null) { val sync = sync(projectConfiguration, request) return Ack.validate(sync != null) } else { return Ack.NOK } } override fun sync(gitConfiguration: GitConfiguration, request: GitSynchronisationRequest): Future<*>? { // Reset the repository? if (request.isReset) { gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository).reset() } // Schedules the job return jobScheduler.fireImmediately(getGitIndexationJobKey(gitConfiguration)).orElse(null) } override fun getProjectGitSyncInfo(project: Project): GitSynchronisationInfo { securityService.checkProjectFunction(project, ProjectConfig::class.java) return getProjectConfiguration(project) ?.let { getGitSynchronisationInfo(it) } ?: throw GitProjectNotConfiguredException(project.id) } private fun getGitSynchronisationInfo(gitConfiguration: GitConfiguration): GitSynchronisationInfo { // Gets the client for this configuration val client = gitRepositoryClientFactory.getClient(gitConfiguration.gitRepository) // Gets the status val status = client.synchronisationStatus // Collects the branch info val branches: List<GitBranchInfo> = if (status == GitSynchronisationStatus.IDLE) { client.branches.branches } else { emptyList() } // OK return GitSynchronisationInfo( gitConfiguration.type, gitConfiguration.name, gitConfiguration.remote, gitConfiguration.indexationInterval, status, branches ) } override fun getIssueProjectInfo(projectId: ID, key: String): OntrackGitIssueInfo? { // Gets the project val project = structureService.getProject(projectId) // Gets the project configuration val projectConfiguration = getRequiredProjectConfiguration(project) // Issue service val configuredIssueService: ConfiguredIssueService? = projectConfiguration.configuredIssueService.orElse(null) // Gets the details about the issue val issue: Issue? = logTime("issue-object") { configuredIssueService?.getIssue(key) } // If no issue, no info if (issue == null || configuredIssueService == null) { return null } else { // Gets a client for this project val repositoryClient: GitRepositoryClient = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository) // Regular expression for the issue val regex = configuredIssueService.getMessageRegex(issue) // Now, get the last commit for this issue val commit = logTime("issue-commit") { repositoryClient.getLastCommitForExpression(regex) } // If commit is found, we collect the commit info return if (commit != null) { val commitInfo = getOntrackGitCommitInfo(project, commit) // We now return the commit info together with the issue OntrackGitIssueInfo( configuredIssueService.issueServiceConfigurationRepresentation, issue, commitInfo ) } // If not found, no commit info else { OntrackGitIssueInfo( configuredIssueService.issueServiceConfigurationRepresentation, issue, null ) } } } private fun getOntrackGitCommitInfo(project: Project, commit: String): OntrackGitCommitInfo { // Gets the project configuration val projectConfiguration = getRequiredProjectConfiguration(project) // Gets a client for this configuration val repositoryClient = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository) // Gets the commit val commitObject = logTime("commit-object") { repositoryClient.getCommitFor(commit) ?: throw GitCommitNotFoundException(commit) } // Gets the annotated commit val messageAnnotators = getMessageAnnotators(projectConfiguration) val uiCommit = toUICommit( projectConfiguration.commitLink, messageAnnotators, commitObject ) // Looks for all Git branches for this commit val gitBranches = logTime("branches-for-commit") { repositoryClient.getBranchesForCommit(commit) } // Sorts the branches according to the branching model val indexedBranches = logTime("branch-index") { branchingModelService.getBranchingModel(project) .groupBranches(gitBranches) .mapValues { (_, gitBranches) -> gitBranches.mapNotNull { findBranchWithGitBranch(project, it) } } .filterValues { !it.isEmpty() } } // Logging of the index indexedBranches.forEach { type, branches: List<Branch> -> logger.debug("git-search-branch-index,type=$type,branches=${branches.joinToString { it.name }}") } // For every indexation group of branches val branchInfos = indexedBranches.mapValues { (_, branches) -> branches.map { branch -> // Gets its Git configuration val branchConfiguration = getRequiredBranchConfiguration(branch) // Gets the earliest build on this branch that contains this commit val firstBuildOnThisBranch = logTime("earliest-build", listOf("branch" to branch.name)) { getEarliestBuildAfterCommit(commitObject, branch, branchConfiguration, repositoryClient) } // Promotions val promotions: List<PromotionRun> = logTime("earliest-promotion", listOf("branch" to branch.name)) { firstBuildOnThisBranch?.let { build -> structureService.getPromotionLevelListForBranch(branch.id) .mapNotNull { promotionLevel -> structureService.getEarliestPromotionRunAfterBuild(promotionLevel, build).orElse(null) } } ?: emptyList() } // Complete branch info BranchInfo( branch, firstBuildOnThisBranch, promotions ) } }.mapValues { (_, infos) -> infos.filter { !it.isEmpty } }.filterValues { !it.isEmpty() } // Result return OntrackGitCommitInfo( uiCommit, branchInfos ) } internal fun getEarliestBuildAfterCommit(commit: GitCommit, branch: Branch, branchConfiguration: GitBranchConfiguration, client: GitRepositoryClient): Build? { return gitRepositoryHelper.getEarliestBuildAfterCommit( branch, IndexableGitCommit(commit) )?.let { structureService.getBuild(ID.of(it)) } } private fun getDiffUrl(diff: GitDiff, entry: GitDiffEntry, fileChangeLinkFormat: String): String { return if (StringUtils.isNotBlank(fileChangeLinkFormat)) { fileChangeLinkFormat .replace("{commit}", entry.getReferenceId(diff.from, diff.to)) .replace("{path}", entry.referencePath) } else { "" } } private fun toChangeLogFile(entry: GitDiffEntry): GitChangeLogFile { return when (entry.changeType) { GitChangeType.ADD -> GitChangeLogFile.of(SCMChangeLogFileChangeType.ADDED, entry.newPath) GitChangeType.COPY -> GitChangeLogFile.of(SCMChangeLogFileChangeType.COPIED, entry.oldPath, entry.newPath) GitChangeType.DELETE -> GitChangeLogFile.of(SCMChangeLogFileChangeType.DELETED, entry.oldPath) GitChangeType.MODIFY -> GitChangeLogFile.of(SCMChangeLogFileChangeType.MODIFIED, entry.oldPath) GitChangeType.RENAME -> GitChangeLogFile.of(SCMChangeLogFileChangeType.RENAMED, entry.oldPath, entry.newPath) else -> GitChangeLogFile.of(SCMChangeLogFileChangeType.UNDEFINED, entry.oldPath, entry.newPath) } } private fun toUICommits(gitConfiguration: GitConfiguration, commits: List<GitCommit>): List<GitUICommit> { // Link? val commitLink = gitConfiguration.commitLink // Issue-based annotations val messageAnnotators = getMessageAnnotators(gitConfiguration) // OK return commits.map { commit -> toUICommit(commitLink, messageAnnotators, commit) } } private fun toUICommit(commitLink: String, messageAnnotators: List<MessageAnnotator>, commit: GitCommit): GitUICommit { return GitUICommit( commit, MessageAnnotationUtils.annotate(commit.shortMessage, messageAnnotators), MessageAnnotationUtils.annotate(commit.fullMessage, messageAnnotators), StringUtils.replace(commitLink, "{commit}", commit.id) ) } private fun getMessageAnnotators(gitConfiguration: GitConfiguration): List<MessageAnnotator> { val configuredIssueService = gitConfiguration.configuredIssueService.orElse(null) return if (configuredIssueService != null) { // Gets the message annotator val messageAnnotator = configuredIssueService.messageAnnotator // If present annotate the messages messageAnnotator.map { listOf(it) }.orElseGet { emptyList<MessageAnnotator?>() } } else { emptyList() } } private fun getSCMBuildView(buildId: ID): SCMBuildView<GitBuildInfo> { return SCMBuildView(getBuildView(buildId), GitBuildInfo()) } override fun getProjectConfiguration(project: Project): GitConfiguration? { return gitConfigurators .map { c -> c.getConfiguration(project) } .filter { it.isPresent } .map { it.get() } .firstOrNull() } protected fun getRequiredBranchConfiguration(branch: Branch): GitBranchConfiguration { return getBranchConfiguration(branch) ?: throw GitBranchNotConfiguredException(branch.id) } override fun getBranchConfiguration(branch: Branch): GitBranchConfiguration? { // Get the configuration for the project val configuration = getProjectConfiguration(branch.project) if (configuration != null) { // Gets the configuration for a branch val gitBranch: String val buildCommitLink: ConfiguredBuildGitCommitLink<*>? val override: Boolean val buildTagInterval: Int val branchConfig = propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java) if (!branchConfig.isEmpty) { gitBranch = branchConfig.value.branch buildCommitLink = branchConfig.value.buildCommitLink?.let { toConfiguredBuildGitCommitLink<Any>(it) } override = branchConfig.value.isOverride buildTagInterval = branchConfig.value.buildTagInterval } else { return null } // OK return GitBranchConfiguration( configuration, gitBranch, buildCommitLink, override, buildTagInterval ) } else { return null } } override fun findBranchWithGitBranch(project: Project, branchName: String): Branch? { return gitRepositoryHelper.findBranchWithProjectAndGitBranch(project, branchName) ?.let { structureService.getBranch(ID.of(it)) } ?.takeIf { it.type != BranchType.TEMPLATE_DEFINITION } } private fun <T> toConfiguredBuildGitCommitLink(serviceConfiguration: ServiceConfiguration): ConfiguredBuildGitCommitLink<T> { @Suppress("UNCHECKED_CAST") val link = buildGitCommitLinkService.getLink(serviceConfiguration.id) as BuildGitCommitLink<T> val linkData = link.parseData(serviceConfiguration.data) return ConfiguredBuildGitCommitLink( link, linkData ) } private fun createBuildSyncJob(branch: Branch): Job { val configuration = getRequiredBranchConfiguration(branch) return object : AbstractBranchJob(structureService, branch) { override fun getKey(): JobKey { return getGitBranchSyncJobKey(branch) } override fun getTask(): JobRun { return JobRun { listener -> buildSync<Any>(branch, configuration, listener) } } override fun getDescription(): String { return format( "Branch %s @ %s", branch.name, branch.project.name ) } override fun isDisabled(): Boolean { return super.isDisabled() && isBranchConfiguredForGit(branch) } } } protected fun getGitBranchSyncJobKey(branch: Branch): JobKey { return GIT_BUILD_SYNC_JOB.getKey(branch.id.toString()) } private fun getGitIndexationJobKey(config: GitConfiguration): JobKey { return GIT_INDEXATION_JOB.getKey(config.gitRepository.id) } private fun createIndexationJob(config: GitConfiguration): Job { return object : Job { override fun getKey(): JobKey { return getGitIndexationJobKey(config) } override fun getTask(): JobRun { return JobRun { runListener -> index(config, runListener) } } override fun getDescription(): String { return format( "%s (%s @ %s)", config.remote, config.name, config.type ) } override fun isDisabled(): Boolean { return false } } } protected fun <T> buildSync(branch: Branch, branchConfiguration: GitBranchConfiguration, listener: JobRunListener) { listener.message("Git build/tag sync for %s/%s", branch.project.name, branch.name) val configuration = branchConfiguration.configuration // Gets the branch Git client val gitClient = gitRepositoryClientFactory.getClient(configuration.gitRepository) // Link @Suppress("UNCHECKED_CAST") val link = branchConfiguration.buildCommitLink?.link as IndexableBuildGitCommitLink<T>? @Suppress("UNCHECKED_CAST") val linkData = branchConfiguration.buildCommitLink?.data as T? // Check for configuration if (link == null || linkData == null) { listener.message("No commit link configuration on the branch - no synchronization.") return } // Configuration for the sync val confProperty = propertyService.getProperty(branch, GitBranchConfigurationPropertyType::class.java) val override = !confProperty.isEmpty && confProperty.value.isOverride // Makes sure of synchronization listener.message("Synchronizing before importing") syncAndWait(configuration) // Gets the list of tags listener.message("Getting list of tags") val tags = gitClient.tags // Creates the builds listener.message("Creating builds from tags") for (tag in tags) { val tagName = tag.name // Filters the tags according to the branch tag pattern link.getBuildNameFromTagName(tagName, linkData).ifPresent { buildNameCandidate -> val buildName = NameDescription.escapeName(buildNameCandidate) listener.message(format("Build %s from tag %s", buildName, tagName)) // Existing build? val build = structureService.findBuildByName(branch.project.name, branch.name, buildName) val createBuild: Boolean = if (build.isPresent) { if (override) { // Deletes the build listener.message("Deleting existing build %s", buildName) structureService.deleteBuild(build.get().id) true } else { // Keeps the build listener.message("Build %s already exists", buildName) false } } else { true } // Actual creation if (createBuild) { listener.message("Creating build %s from tag %s", buildName, tagName) structureService.newBuild( Build.of( branch, NameDescription( buildName, "Imported from Git tag $tagName" ), securityService.currentSignature.withTime( tag.time ) ) ) } } } } private fun index(config: GitConfiguration, listener: JobRunListener) { listener.message("Git sync for %s", config.name) // Gets the client for this configuration val client = gitRepositoryClientFactory.getClient(config.gitRepository) // Launches the synchronisation client.sync(listener.logger()) } private fun getGitIndexationJobRegistration(configuration: GitConfiguration): JobRegistration { return JobRegistration .of(createIndexationJob(configuration)) .everyMinutes(configuration.indexationInterval.toLong()) } override fun scheduleGitBuildSync(branch: Branch, property: GitBranchConfigurationProperty) { if (property.buildTagInterval > 0) { jobScheduler.schedule( createBuildSyncJob(branch), Schedule.everyMinutes(property.buildTagInterval.toLong()) ) } else { unscheduleGitBuildSync(branch, property) } } override fun unscheduleGitBuildSync(branch: Branch, property: GitBranchConfigurationProperty) { jobScheduler.unschedule(getGitBranchSyncJobKey(branch)) } override fun getSCMPathInfo(branch: Branch): Optional<SCMPathInfo> { return getBranchConfiguration(branch) ?.let { SCMPathInfo( "git", it.configuration.remote, it.branch, null ) } .asOptional() } override fun getCommitForBuild(build: Build): IndexableGitCommit? = entityDataService.retrieve( build, "git-commit", IndexableGitCommit::class.java ) override fun setCommitForBuild(build: Build, commit: IndexableGitCommit) { entityDataService.store( build, "git-commit", commit ) } override fun collectIndexableGitCommitForBranch(branch: Branch, overrides: Boolean) { val project = branch.project val projectConfiguration = getProjectConfiguration(project) if (projectConfiguration != null) { val client = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository) val branchConfiguration = getBranchConfiguration(branch) if (branchConfiguration != null) { collectIndexableGitCommitForBranch( branch, client, branchConfiguration, overrides, JobRunListener.logger(logger) ) } } } override fun collectIndexableGitCommitForBranch( branch: Branch, client: GitRepositoryClient, config: GitBranchConfiguration, overrides: Boolean, listener: JobRunListener ) { val buildCommitLink = config.buildCommitLink if (buildCommitLink != null) { structureService.findBuild( branch.id, Predicate { build -> collectIndexableGitCommitForBuild(build, client, buildCommitLink, overrides, listener) }, BuildSortDirection.FROM_NEWEST ) } } override fun collectIndexableGitCommitForBuild(build: Build) { val project = build.project val projectConfiguration = getProjectConfiguration(project) if (projectConfiguration != null) { val client = gitRepositoryClientFactory.getClient(projectConfiguration.gitRepository) val branchConfiguration = getBranchConfiguration(build.branch) val buildCommitLink = branchConfiguration?.buildCommitLink if (buildCommitLink != null) { collectIndexableGitCommitForBuild( build, client, buildCommitLink, true, JobRunListener.logger(logger) ) } } } private fun collectIndexableGitCommitForBuild( build: Build, client: GitRepositoryClient, buildCommitLink: ConfiguredBuildGitCommitLink<*>, overrides: Boolean, listener: JobRunListener ): Boolean = transactionTemplate.execute { val commit = try { buildCommitLink.getCommitFromBuild(build) } catch (ex: NoGitCommitPropertyException) { null } if (commit != null) { listener.message("Indexing $commit for build ${build.entityDisplayName}") // Gets the Git information for the commit val toSet: Boolean = overrides || getCommitForBuild(build) == null if (toSet) { val commitFor = client.getCommitFor(commit) if (commitFor != null) { setCommitForBuild(build, IndexableGitCommit(commitFor)) } } } // Going on false } private fun <T> logTime(key: String, tags: List<Pair<String, *>> = emptyList(), code: () -> T): T { val start = System.currentTimeMillis() val result = code() val end = System.currentTimeMillis() val time = end - start val tagsString = tags.joinToString("") { ",${it.first}=${it.second.toString()}" } logger.debug("git-search-time,key=$key,time-ms=$time$tagsString") return result } companion object { private val GIT_INDEXATION_JOB = GIT_JOB_CATEGORY.getType("git-indexation").withName("Git indexation") private val GIT_BUILD_SYNC_JOB = GIT_JOB_CATEGORY.getType("git-build-sync").withName("Git build synchronisation") } }
mit
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/domain/ClientVersion.kt
1
106
package hamburg.remme.tinygit.domain class ClientVersion(val major: Int, val minor: Int, val patch: Int)
bsd-3-clause
paplorinc/intellij-community
plugins/gradle/java/testSources/execution/test/runner/ExternalTestsModelCompatibilityTestCase.kt
3
3865
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.test.runner import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestRunConfigurationProducer.findAllTestsTaskToRun import org.jetbrains.plugins.gradle.importing.GradleBuildScriptBuilderEx import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Assert import org.junit.Test class ExternalTestsModelCompatibilityTestCase : GradleImportingTestCase() { @Test fun `test simple tests finding`() { val buildScript = GradleBuildScriptBuilderEx() .withJavaPlugin() .withJUnit("4.12") importProject(buildScript.generate()) assertTestTasks(createProjectSubFile("src/test/java/package/TestCase.java", "class TestCase"), listOf(":cleanTest", ":test")) } @Test @TargetVersions("2.4 <=> 4.10.3") fun `test intellij tests finding`() { val buildScript = GradleBuildScriptBuilderEx() .withJavaPlugin() .withJUnit("4.12") .addPrefix(""" sourceSets { foo.java.srcDirs = ["foo-src", "foo-other-src"] foo.compileClasspath += sourceSets.test.runtimeClasspath } """.trimIndent()) .addPrefix(""" task 'foo test task'(type: Test) { testClassesDir = sourceSets.foo.output.classesDir classpath += sourceSets.foo.runtimeClasspath } task 'super foo test task'(type: Test) { testClassesDir = sourceSets.foo.output.classesDir classpath += sourceSets.foo.runtimeClasspath } """.trimIndent()) importProject(buildScript.generate()) assertTestTasks(createProjectSubFile("foo-src/package/TestCase.java", "class TestCase"), listOf(":cleanFoo test task", ":foo test task"), listOf(":cleanSuper foo test task", ":super foo test task")) assertTestTasks(createProjectSubFile("foo-other-src/package/TestCase.java", "class TestCase"), listOf(":cleanFoo test task", ":foo test task"), listOf(":cleanSuper foo test task", ":super foo test task")) } @Test @TargetVersions("4.0+") fun `test intellij tests finding new interface`() { val buildScript = GradleBuildScriptBuilderEx() .withJavaPlugin() .withJUnit("4.12") .addPrefix(""" sourceSets { foo.java.srcDirs = ["foo-src", "foo-other-src"] foo.compileClasspath += sourceSets.test.runtimeClasspath } """.trimIndent()) .addPrefix(""" task 'foo test task'(type: Test) { testClassesDirs = sourceSets.foo.output.classesDirs classpath += sourceSets.foo.runtimeClasspath } task 'super foo test task'(type: Test) { testClassesDirs = sourceSets.foo.output.classesDirs classpath += sourceSets.foo.runtimeClasspath } """.trimIndent()) importProject(buildScript.generate()) assertTestTasks(createProjectSubFile("foo-src/package/TestCase.java", "class TestCase"), listOf(":cleanFoo test task", ":foo test task"), listOf(":cleanSuper foo test task", ":super foo test task")) assertTestTasks(createProjectSubFile("foo-other-src/package/TestCase.java", "class TestCase"), listOf(":cleanFoo test task", ":foo test task"), listOf(":cleanSuper foo test task", ":super foo test task")) } private fun assertTestTasks(source: VirtualFile, vararg expected: List<String>) { val tasks = findAllTestsTaskToRun(source, myProject) Assert.assertEquals(expected.toList(), tasks) } }
apache-2.0
eugenkiss/kotlinfx
kotlinfx-demos/src/main/kotlin/Main.kt
2
330
// I want this file to be a GUI app that shows a tree of all the demos // in kotlin-demos. The demos should be found dynamically i.e. i don't // have to explicitly list them here. // There should be a gradle task to run this project that runs this // file. package demos.main fun main(args: Array<String>) { println("TODO") }
mit
google/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/db/KnownPlugins.kt
1
2000
// 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.customize.transferSettings.db import com.intellij.ide.customize.transferSettings.models.BuiltInFeature import com.intellij.ide.customize.transferSettings.models.PluginFeature object KnownPlugins { val Git = BuiltInFeature("Git") val editorconfig = BuiltInFeature("editorconfig") @Suppress("HardCodedStringLiteral") val WebSupport = BuiltInFeature("Web support", "HTML, CSS, JS") val Docker = BuiltInFeature("Docker") val CSharp = BuiltInFeature("C#") val NuGet = BuiltInFeature("NuGet") val TestExplorer = BuiltInFeature("TestExplorer") val RunConfigurations = BuiltInFeature("Run Configurations") val Unity = BuiltInFeature("Unity") val LiveTemplates = BuiltInFeature("Live Templates") val SpellChecker = BuiltInFeature("Spell Checker") val LanguageSupport = BuiltInFeature("Language Support") val DotNetDecompiler = BuiltInFeature(".NET Decompiler") val DatabaseSupport = BuiltInFeature("Database Support") val TSLint = BuiltInFeature("TSLint") // Plugins val XAMLStyler = PluginFeature("xamlstyler.rider", "XAML Styler") val Ideolog = PluginFeature("com.intellij.ideolog", "Ideolog (logging)") val IdeaVim = PluginFeature("IdeaVIM", "IdeaVIM") val TeamCity = PluginFeature("Jetbrains TeamCity Plugin", "TeamCity") val NodeJSSupport = PluginFeature("NodeJS", "NodeJS support") val Monokai = PluginFeature("monokai-pro", "Monokai") val Solarized = PluginFeature("com.tylerthrailkill.intellij.solarized", "Solarized") val XcodeKeymap = PluginFeature("com.intellij.plugins.xcodekeymap", "Xcode keymap") val VSCodeKeymap = PluginFeature("com.intellij.plugins.vscodekeymap", "VSCode keymap") val VSMacKeymap = PluginFeature("com.intellij.plugins.visualstudioformackeymap", "Visual Studio for Mac keymap") val DummyBuiltInFeature = BuiltInFeature("") val DummyPlugin = PluginFeature("", "") }
apache-2.0
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/client/ClientAwareComponentManager.kt
1
3577
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.client import com.intellij.codeWithMe.ClientId import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.openapi.application.Application import com.intellij.openapi.components.ServiceDescriptor import com.intellij.openapi.extensions.PluginId import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.serviceContainer.PrecomputedExtensionModel import com.intellij.serviceContainer.throwAlreadyDisposedError import kotlinx.coroutines.CoroutineScope import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal abstract class ClientAwareComponentManager constructor( internal val parent: ComponentManagerImpl?, setExtensionsRootArea: Boolean = parent == null ) : ComponentManagerImpl(parent, setExtensionsRootArea) { override fun <T : Any> getServices(serviceClass: Class<T>, includeLocal: Boolean): List<T> { val sessionsManager = super.getService(ClientSessionsManager::class.java)!! return sessionsManager.getSessions(includeLocal).mapNotNull { (it as? ClientSessionImpl)?.doGetService(serviceClass = serviceClass, createIfNeeded = true, fallbackToShared = false) } } override fun <T : Any> postGetService(serviceClass: Class<T>, createIfNeeded: Boolean): T? { val sessionsManager = if (containerState.get() == ContainerState.DISPOSE_COMPLETED) { if (createIfNeeded) { throwAlreadyDisposedError(serviceClass.name, this) } super.doGetService(ClientSessionsManager::class.java, false) } else { super.doGetService(ClientSessionsManager::class.java, true) } val session = sessionsManager?.getSession(ClientId.current) as? ClientSessionImpl return session?.doGetService(serviceClass, createIfNeeded, false) } override fun registerComponents(modules: List<IdeaPluginDescriptorImpl>, app: Application?, precomputedExtensionModel: PrecomputedExtensionModel?, listenerCallbacks: MutableList<in Runnable>?) { super.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks) val sessionsManager = super.getService(ClientSessionsManager::class.java)!! for (session in sessionsManager.getSessions(true)) { (session as? ClientSessionImpl)?.registerComponents(modules, app, precomputedExtensionModel, listenerCallbacks) } } override fun unloadServices(services: List<ServiceDescriptor>, pluginId: PluginId) { super.unloadServices(services, pluginId) val sessionsManager = super.getService(ClientSessionsManager::class.java)!! for (session in sessionsManager.getSessions(true)) { (session as? ClientSessionImpl)?.unloadServices(services, pluginId) } } override fun postPreloadServices(modules: List<IdeaPluginDescriptorImpl>, activityPrefix: String, syncScope: CoroutineScope, onlyIfAwait: Boolean) { val sessionsManager = super.getService(ClientSessionsManager::class.java)!! for (session in sessionsManager.getSessions(true)) { session as? ClientSessionImpl ?: continue session.preloadServices(modules, activityPrefix, syncScope, onlyIfAwait) } } override fun isPreInitialized(component: Any): Boolean { return super.isPreInitialized(component) || component is ClientSessionsManager<*> } }
apache-2.0
google/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.kt
1
8036
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.data import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.diagnostic.telemetry.TraceManager import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor import org.jetbrains.annotations.CalledInAny import java.awt.EventQueue /** * Provides capabilities to asynchronously calculate "contained in branches" information. */ class ContainingBranchesGetter internal constructor(private val logData: VcsLogData, parentDisposable: Disposable) { private val taskExecutor: SequentialLimitedLifoExecutor<CachingTask> // other fields accessed only from EDT private val loadingFinishedListeners: MutableList<Runnable> = ArrayList() private val cache = Caffeine.newBuilder() .maximumSize(2000) .build<CommitId, List<String>>() private val conditionsCache: CurrentBranchConditionCache private var currentBranchesChecksum = 0 init { conditionsCache = CurrentBranchConditionCache(logData, parentDisposable) taskExecutor = SequentialLimitedLifoExecutor(parentDisposable, 10, CachingTask::run) logData.addDataPackChangeListener { dataPack: DataPack -> val checksum = dataPack.refsModel.branches.hashCode() if (currentBranchesChecksum != checksum) { // clear cache if branches set changed after refresh clearCache() } currentBranchesChecksum = checksum } } @RequiresEdt private fun cache(commitId: CommitId, branches: List<String>, branchesChecksum: Int) { if (branchesChecksum == currentBranchesChecksum) { cache.put(commitId, branches) notifyListeners() } } @RequiresEdt private fun clearCache() { cache.invalidateAll() taskExecutor.clear() conditionsCache.clear() // re-request containing branches information for the commit user (possibly) currently stays on ApplicationManager.getApplication().invokeLater { notifyListeners() } } /** * This task will be executed each time the calculating process completes. */ fun addTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.add(runnable) } fun removeTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.remove(runnable) } private fun notifyListeners() { LOG.assertTrue(EventQueue.isDispatchThread()) for (listener in loadingFinishedListeners) { listener.run() } } /** * Returns the alphabetically sorted list of branches containing the specified node, if this information is ready; * if it is not available, starts calculating in the background and returns null. */ fun requestContainingBranches(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) val refs = getContainingBranchesFromCache(root, hash) if (refs == null) { taskExecutor.queue(CachingTask(createTask(root, hash, logData.dataPack), currentBranchesChecksum)) } return refs } fun getContainingBranchesFromCache(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) return cache.getIfPresent(CommitId(hash, root)) } @CalledInAny fun getContainingBranchesQuickly(root: VirtualFile, hash: Hash): List<String>? { val cachedBranches = cache.getIfPresent(CommitId(hash, root)) if (cachedBranches != null) return cachedBranches val dataPack = logData.dataPack val commitIndex = logData.getCommitIndex(hash, root) val pg = dataPack.permanentGraph if (pg is PermanentGraphImpl<Int>) { val nodeId = pg.permanentCommitsInfo.getNodeId(commitIndex) if (nodeId < 10000 && canUseGraphForComputation(logData.getLogProvider(root))) { return getContainingBranchesSynchronously(dataPack, root, hash) } } return BackgroundTaskUtil.tryComputeFast({ return@tryComputeFast getContainingBranchesSynchronously(dataPack, root, hash) }, 100) } @CalledInAny fun getContainedInCurrentBranchCondition(root: VirtualFile) = conditionsCache.getContainedInCurrentBranchCondition(root) @CalledInAny fun getContainingBranchesSynchronously(root: VirtualFile, hash: Hash): List<String> { return getContainingBranchesSynchronously(logData.dataPack, root, hash) } @CalledInAny private fun getContainingBranchesSynchronously(dataPack: DataPack, root: VirtualFile, hash: Hash): List<String> { return CachingTask(createTask(root, hash, dataPack), dataPack.refsModel.branches.hashCode()).run() } private fun createTask(root: VirtualFile, hash: Hash, dataPack: DataPack): Task { val provider = logData.getLogProvider(root) return if (canUseGraphForComputation(provider)) { GraphTask(provider, root, hash, dataPack) } else ProviderTask(provider, root, hash) } private abstract class Task(private val myProvider: VcsLogProvider, val myRoot: VirtualFile, val myHash: Hash) { @Throws(VcsException::class) fun getContainingBranches(): List<String> { TraceManager.getTracer("vcs").spanBuilder("get containing branches").useWithScope { return try { getContainingBranches(myProvider, myRoot, myHash) } catch (e: VcsException) { LOG.warn(e) emptyList() } } } @Throws(VcsException::class) protected abstract fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> } private inner class GraphTask constructor(provider: VcsLogProvider, root: VirtualFile, hash: Hash, dataPack: DataPack) : Task(provider, root, hash) { private val graph = dataPack.permanentGraph private val refs = dataPack.refsModel override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> { val commitIndex = logData.getCommitIndex(hash, root) return graph.getContainingBranches(commitIndex) .map(::getBranchesRefs) .flatten() .sortedWith(provider.referenceManager.labelsOrderComparator) .map(VcsRef::getName) } private fun getBranchesRefs(branchIndex: Int) = refs.refsToCommit(branchIndex).filter { it.type.isBranch } } private class ProviderTask(provider: VcsLogProvider, root: VirtualFile, hash: Hash) : Task(provider, root, hash) { @Throws(VcsException::class) override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash) = provider.getContainingBranches(root, hash).sorted() } private inner class CachingTask(private val delegate: Task, private val branchesChecksum: Int) { fun run(): List<String> { val branches = delegate.getContainingBranches() val commitId = CommitId(delegate.myHash, delegate.myRoot) UIUtil.invokeLaterIfNeeded { cache(commitId, branches, branchesChecksum) } return branches } } companion object { private val LOG = Logger.getInstance(ContainingBranchesGetter::class.java) private fun canUseGraphForComputation(logProvider: VcsLogProvider) = VcsLogProperties.LIGHTWEIGHT_BRANCHES.getOrDefault(logProvider) } }
apache-2.0
google/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownHeader.kt
3
6849
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.lang.ASTNode import com.intellij.navigation.ColoredItemPresentation import com.intellij.navigation.ItemPresentation import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.elementType import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.lang.psi.MarkdownElementVisitor import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.childrenOfType import org.intellij.plugins.markdown.lang.psi.util.hasType import org.intellij.plugins.markdown.lang.stubs.impl.MarkdownHeaderStubElement import org.intellij.plugins.markdown.lang.stubs.impl.MarkdownHeaderStubElementType import org.intellij.plugins.markdown.structureView.MarkdownStructureColors import org.jetbrains.annotations.ApiStatus import javax.swing.Icon /** * Corresponds to both ATX and SETEXT headers. * * Use [contentElement] to agnostically obtain a content element for current header. */ @Suppress("DEPRECATION") class MarkdownHeader: MarkdownHeaderImpl { constructor(node: ASTNode): super(node) constructor(stub: MarkdownHeaderStubElement, type: MarkdownHeaderStubElementType): super(stub, type) val level get() = calculateHeaderLevel() /** * Anchor reference to this header. * Should be compatible with anchors generated by GitHub. * * ```markdown * # Some header text -> #some-header-text * ``` * Exception: multiple headers with same text won't be adjusted with it's occurence number. */ val anchorText: String? get() = obtainAnchorText(this) val contentElement: MarkdownHeaderContent? get() = childrenOfType(MarkdownTokenTypeSets.HEADER_CONTENT).filterIsInstance<MarkdownHeaderContent>().firstOrNull() override fun accept(visitor: PsiElementVisitor) { when (visitor) { is MarkdownElementVisitor -> visitor.visitHeader(this) else -> super.accept(visitor) } } override fun getReferences(): Array<PsiReference?> { return ReferenceProvidersRegistry.getReferencesFromProviders(this) } override fun getPresentation(): ItemPresentation { val headerText = getHeaderText() val text = headerText ?: "Invalid header: $text" return object: ColoredItemPresentation { override fun getPresentableText(): String { val prevSibling = prevSibling if (Registry.`is`("markdown.structure.view.list.visibility") && MarkdownTokenTypeSets.LIST_MARKERS.contains(prevSibling.elementType)) { return prevSibling.text + text } return text } override fun getIcon(open: Boolean): Icon? = null override fun getTextAttributesKey(): TextAttributesKey? { return when (level) { 1 -> MarkdownStructureColors.MARKDOWN_HEADER_BOLD else -> MarkdownStructureColors.MARKDOWN_HEADER } } } } override fun getName(): String? { return getHeaderText() } private fun findContentHolder(): PsiElement? { return findChildByType(MarkdownTokenTypeSets.INLINE_HOLDING_ELEMENT_TYPES) } private fun getHeaderText(): String? { if (!isValid) { return null } val contentHolder = findContentHolder() ?: return null return StringUtil.trim(contentHolder.text) } /** * Builds visible text for this header. * Visible text includes text content of all children without starting hash and a whitespace after hash. * * For a child inline link this method will only take it's visible part ([MarkdownLink.linkText]). * * @param hideImages - if true, all child images will be ignored, * otherwise images will be included as is, with it's visible and invisible parts * (so rendered result will show actual image). */ @ApiStatus.Experimental fun buildVisibleText(hideImages: Boolean = true): String? { val contentHolder = findContentHolder() ?: return null val builder = StringBuilder() val children = contentHolder.children().dropWhile { it.hasType(MarkdownTokenTypeSets.WHITE_SPACES) } traverseNameText(builder, children, hideImages) return builder.toString().trim(' ') } private fun traverseNameText(builder: StringBuilder, elements: Sequence<PsiElement>, hideImages: Boolean) { for (child in elements) { when (child) { is LeafPsiElement -> builder.append(child.text) is MarkdownInlineLink -> traverseNameText(builder, child.linkText?.contentElements.orEmpty(), hideImages) is MarkdownImage -> { if (!hideImages) { builder.append(child.text) } } else -> traverseNameText(builder, child.children(), hideImages) } } } private fun buildAnchorText(includeStartingHash: Boolean = false): String? { val contentHolder = findContentHolder() ?: return null val children = contentHolder.children().filter { !it.hasType(MarkdownTokenTypeSets.WHITE_SPACES) } val text = buildString { if (includeStartingHash) { append("#") } var count = 0 for (child in children) { if (count >= 1) { append(" ") } when (child) { is MarkdownImage -> append("") is MarkdownInlineLink -> processInlineLink(child) else -> append(child.text) } count += 1 } } val replaced = text.lowercase().replace(garbageRegex, "").replace(additionalSymbolsRegex, "") return replaced.replace(" ", "-") } private fun StringBuilder.processInlineLink(element: MarkdownInlineLink) { val contentElements = element.linkText?.contentElements.orEmpty() val withoutWhitespaces = contentElements.filterNot { it.hasType(MarkdownTokenTypeSets.WHITE_SPACES) } withoutWhitespaces.joinTo(this, separator = " ") { when (it) { is MarkdownImage -> "" else -> it.text } } } companion object { internal val garbageRegex = Regex("[^\\w\\- ]") internal val additionalSymbolsRegex = Regex("[^-_a-z0-9\\s]") fun obtainAnchorText(header: MarkdownHeader): String? { return CachedValuesManager.getCachedValue(header) { CachedValueProvider.Result.create(header.buildAnchorText(false), PsiModificationTracker.MODIFICATION_COUNT) } } } }
apache-2.0
StephaneBg/ScoreIt
core/src/main/kotlin/com/sbgapps/scoreit/core/widget/ItemAdapter.kt
1
901
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.core.widget import android.view.View import androidx.annotation.LayoutRes abstract class ItemAdapter(@LayoutRes open val layoutId: Int) { fun onCreateViewHolder(itemView: View) = BaseViewHolder(itemView) abstract fun onBindViewHolder(viewHolder: BaseViewHolder) }
apache-2.0
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/util/StatusBarScrimBehavior.kt
3
2335
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.util import android.content.Context import android.util.AttributeSet import android.view.View import androidx.annotation.Keep import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.WindowInsetsCompat import com.google.android.material.appbar.AppBarLayout @Keep @Suppress("UNUSED") class StatusBarScrimBehavior( context: Context, attrs: AttributeSet ) : CoordinatorLayout.Behavior<View>(context, attrs) { override fun onLayoutChild( parent: CoordinatorLayout, child: View, layoutDirection: Int ): Boolean { child.setOnApplyWindowInsetsListener(NoopWindowInsetsListener) // Return false so that the child is laid out by the parent return false } override fun layoutDependsOn( parent: CoordinatorLayout, child: View, dependency: View ): Boolean { if (dependency is AppBarLayout) { // Jump the drawable state in case the elevation is animating dependency.jumpDrawablesToCurrentState() // Copy over the elevation value child.elevation = dependency.elevation return true } return false } override fun onDependentViewChanged( parent: CoordinatorLayout, child: View, dependency: View ): Boolean { child.elevation = dependency.elevation return false } override fun onApplyWindowInsets( parent: CoordinatorLayout, child: View, insets: WindowInsetsCompat ): WindowInsetsCompat { child.layoutParams.height = insets.systemWindowInsetTop child.requestLayout() return insets } }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InitializePropertyQuickFixFactory.kt
1
13318
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.impl.FinishMarkAction import com.intellij.openapi.command.impl.StartMarkAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.search.searches.MethodReferencesSearch import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.shorten.runRefactoringAndKeepDelayedRequests import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.appendElement import org.jetbrains.kotlin.idea.core.getOrCreateBody import org.jetbrains.kotlin.idea.refactoring.CompositeRefactoringRunner import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.util.getDefaultInitializer import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.descriptorUtil.secondaryConstructors import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.safeAs object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { class AddInitializerFix(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) { override fun getText() = KotlinBundle.message("add.initializer") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val descriptor = element.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val initializerText = descriptor.type.getDefaultInitializer() ?: "TODO()" val initializer = element.setInitializer(KtPsiFactory(project).createExpression(initializerText))!! if (editor != null) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) editor.selectionModel.setSelection(initializer.startOffset, initializer.endOffset) editor.caretModel.moveToOffset(initializer.endOffset) } } } class MoveToConstructorParameters(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) { override fun getText() = KotlinBundle.message("move.to.constructor.parameters") override fun getFamilyName() = text override fun startInWriteAction(): Boolean = false private fun configureChangeSignature( property: KtProperty, propertyDescriptor: PropertyDescriptor ): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { val initializerText = propertyDescriptor.type.getDefaultInitializer() ?: "null" val newParam = KotlinParameterInfo( callableDescriptor = originalDescriptor.baseDescriptor, name = propertyDescriptor.name.asString(), originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), valOrVar = property.valOrVarKeyword.toValVar(), modifierList = property.modifierList, defaultValueForCall = KtPsiFactory(property.project).createExpression(initializerText) ) it.addParameter(newParam) } } override fun performSilently(affectedFunctions: Collection<PsiElement>) = noUsagesExist(affectedFunctions) } } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val klass = element.containingClassOrObject ?: return val propertyDescriptor = element.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return StartMarkAction.canStart(editor)?.let { return } val startMarkAction = StartMarkAction.start(editor, project, text) try { val parameterToInsert = KtPsiFactory(project).createParameter(element.text) runWriteAction { element.delete() } val classDescriptor = klass.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes ?: return val constructorDescriptor = classDescriptor.unsubstitutedPrimaryConstructor ?: return val contextElement = constructorDescriptor.source.getPsi() ?: return val constructorPointer = contextElement.createSmartPointer() val config = configureChangeSignature(element, propertyDescriptor) object : CompositeRefactoringRunner(project, "refactoring.changeSignature") { override fun runRefactoring() { runChangeSignature(project, editor, constructorDescriptor, config, contextElement, text) } override fun onRefactoringDone() { val constructorOrClass = constructorPointer.element val constructor = constructorOrClass as? KtConstructor<*> ?: (constructorOrClass as? KtClass)?.primaryConstructor constructor?.valueParameters?.lastOrNull()?.replace(parameterToInsert) } }.run() } finally { FinishMarkAction.finish(project, editor, startMarkAction) } } } class InitializeWithConstructorParameter(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) { override fun getText() = KotlinBundle.message("initialize.with.constructor.parameter") override fun getFamilyName() = text override fun startInWriteAction(): Boolean = false private fun configureChangeSignature(propertyDescriptor: PropertyDescriptor): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { methodDescriptor -> val classDescriptor = propertyDescriptor.containingDeclaration as ClassDescriptorWithResolutionScopes val constructorScope = classDescriptor.scopeForClassHeaderResolution val validator = CollectingNameValidator(originalDescriptor.parameters.map { it.name }) { name -> constructorScope.getContributedDescriptors(DescriptorKindFilter.VARIABLES).all { it !is VariableDescriptor || it.name.asString() != name } } val initializerText = propertyDescriptor.type.getDefaultInitializer() ?: "null" val newParam = KotlinParameterInfo( callableDescriptor = originalDescriptor.baseDescriptor, name = Fe10KotlinNameSuggester.suggestNameByName(propertyDescriptor.name.asString(), validator), originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), defaultValueForCall = KtPsiFactory(element!!.project).createExpression(initializerText) ) methodDescriptor.addParameter(newParam) } } override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean = noUsagesExist(affectedFunctions) } } // TODO: Allow processing of multiple functions in Change Signature so that Start/Finish Mark can be used here private fun processConstructors( project: Project, editor: Editor?, configuration: KotlinChangeSignatureConfiguration, constructorDescriptor: ConstructorDescriptor, visitedElements: MutableSet<PsiElement> ) { val element = element!! val constructorPointer = constructorDescriptor.source.getPsi()?.createSmartPointer() object : CompositeRefactoringRunner(project, "refactoring.changeSignature") { override fun runRefactoring() { val containingClassOrObject = element.containingClassOrObject ?: return runChangeSignature(project, editor, constructorDescriptor, configuration, containingClassOrObject, text) } override fun onRefactoringDone() { val constructorOrClass = constructorPointer?.element val constructor = constructorOrClass as? KtConstructor<*> ?: (constructorOrClass as? KtClass)?.primaryConstructor ?: return if (!visitedElements.add(constructor)) return constructor.valueParameters.lastOrNull()?.let { newParam -> val psiFactory = KtPsiFactory(project) val name = newParam.name ?: return constructor.safeAs<KtSecondaryConstructor>()?.getOrCreateBody() ?.appendElement(psiFactory.createExpression("this.${element.name} = $name")) ?: element.setInitializer(psiFactory.createExpression(name)) } } }.run() } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val propertyDescriptor = element.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val classDescriptor = propertyDescriptor.containingDeclaration as? ClassDescriptorWithResolutionScopes ?: return val klass = element.containingClassOrObject ?: return val constructorDescriptors = if (klass.hasExplicitPrimaryConstructor() || klass.secondaryConstructors.isEmpty()) { listOf(classDescriptor.unsubstitutedPrimaryConstructor!!) } else { classDescriptor.secondaryConstructors.filter { val constructor = it.source.getPsi() as? KtSecondaryConstructor constructor != null && !constructor.getDelegationCall().isCallToThis } } val config = configureChangeSignature(propertyDescriptor) val visitedElements = mutableSetOf<PsiElement>() project.runRefactoringAndKeepDelayedRequests { for (constructorDescriptor in constructorDescriptors) { processConstructors(project, editor, config, constructorDescriptor, visitedElements) } } } } private fun noUsagesExist(affectedFunctions: Collection<PsiElement>): Boolean = affectedFunctions.flatMap { it.toLightMethods() }.all { MethodReferencesSearch.search(it).findFirst() == null } override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val property = diagnostic.psiElement as? KtProperty ?: return emptyList() if (property.receiverTypeReference != null) return emptyList() val actions = ArrayList<IntentionAction>(2) actions.add(AddInitializerFix(property)) property.containingClassOrObject.safeAs<KtClass>()?.let { klass -> if (klass.isAnnotation() || klass.isInterface()) return@let if (klass.primaryConstructor?.hasActualModifier() == true) return@let val secondaryConstructors by lazy { klass.secondaryConstructors.filter { it.getDelegationCallOrNull()?.isCallToThis != true } } if (property.accessors.isNotEmpty() || secondaryConstructors.isNotEmpty()) { if (secondaryConstructors.none { it.hasActualModifier() }) { actions.add(InitializeWithConstructorParameter(property)) } } else { actions.add(MoveToConstructorParameters(property)) } } return actions } }
apache-2.0
sheaam30/setlist
app/src/main/java/setlist/shea/setlist/songlist/adapter/SongViewHolder.kt
1
991
package setlist.shea.setlist.songlist.adapter import android.graphics.Paint import android.support.v7.widget.RecyclerView import android.view.View import android.widget.CheckBox import android.widget.ImageView import android.widget.TextView import setlist.shea.domain.model.Song import setlist.shea.setlist.R /** * Created by Adam on 8/28/2017. */ class SongViewHolder(view : View): RecyclerView.ViewHolder(view), SongViewHolderInterface<Song> { val songName = view.findViewById<TextView>(R.id.song_name) val songArtist = view.findViewById<TextView>(R.id.song_artist) val songPlayed = view.findViewById<CheckBox>(R.id.played_checkbox) val moveItem = view.findViewById<ImageView>(R.id.reorder)!! override fun bind(data: Song) { songName.text = data.name songArtist.text = data.artist songPlayed.isChecked = data.played songName.strikeThrough(songPlayed.isChecked) songArtist.strikeThrough(songPlayed.isChecked) } }
apache-2.0
exercism/xkotlin
exercises/practice/space-age/.meta/src/reference/kotlin/SpaceAge.kt
1
1192
import java.math.BigDecimal import java.math.RoundingMode class SpaceAge(private val seconds: Long) { companion object { const val EARTH_ORBITAL_PERIOD_IN_SECONDS = 31557600.0 const val PRECISION = 2 private enum class Planet(val relativeOrbitalPeriod: Double) { EARTH(1.0), MERCURY(0.2408467), VENUS(0.61519726), MARS(1.8808158), JUPITER(11.862615), SATURN(29.447498), URANUS(84.016846), NEPTUNE(164.79132) } } fun onEarth() = calculateAge(Planet.EARTH) fun onMercury() = calculateAge(Planet.MERCURY) fun onVenus() = calculateAge(Planet.VENUS) fun onMars() = calculateAge(Planet.MARS) fun onJupiter() = calculateAge(Planet.JUPITER) fun onSaturn() = calculateAge(Planet.SATURN) fun onUranus() = calculateAge(Planet.URANUS) fun onNeptune() = calculateAge(Planet.NEPTUNE) private fun calculateAge(planet: Planet): Double { val age: Double = seconds / (EARTH_ORBITAL_PERIOD_IN_SECONDS * planet.relativeOrbitalPeriod) return BigDecimal(age).setScale(PRECISION, RoundingMode.HALF_UP).toDouble() } }
mit
exercism/xkotlin
exercises/practice/scrabble-score/.meta/src/reference/kotlin/ScrabbleScore.kt
1
479
object ScrabbleScore { private val scoreToLetters = mapOf(1 to "AEIOULNRST", 2 to "DG", 3 to "BCMP", 4 to "FHVWY", 5 to "K", 8 to "JX", 10 to "QZ").mapValues { it.value.toCharArray() } private val letterToScore = scoreToLetters.flatMap { entry -> entry.value.map { char -> Pair(char, entry.key) } }.toMap() fun scoreLetter(c: Char) = letterToScore[c.uppercaseChar()] ?: 0 fun scoreWord(word: String) = word.fold(0) { score, char -> score + scoreLetter(char) } }
mit
allotria/intellij-community
python/src/com/jetbrains/python/sdk/pipenv/pipenv.kt
2
20016
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.pipenv import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.annotations.SerializedName import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.util.IntentionName import com.intellij.execution.ExecutionException import com.intellij.execution.RunCanceledByUserException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.PathEnvironmentVariableUtil import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts.ProgressTitle import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import com.jetbrains.python.PyBundle import com.jetbrains.python.inspections.PyPackageRequirementsInspection import com.jetbrains.python.packaging.* import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import icons.PythonIcons import org.jetbrains.annotations.SystemDependent import org.jetbrains.annotations.TestOnly import java.io.File import javax.swing.Icon const val PIP_FILE: String = "Pipfile" const val PIP_FILE_LOCK: String = "Pipfile.lock" const val PIPENV_DEFAULT_SOURCE_URL: String = "https://pypi.org/simple" const val PIPENV_PATH_SETTING: String = "PyCharm.Pipenv.Path" // TODO: Provide a special icon for pipenv val PIPENV_ICON: Icon = PythonIcons.Python.PythonClosed /** * The Pipfile found in the main content root of the module. */ val Module.pipFile: VirtualFile? get() = baseDir?.findChild(PIP_FILE) /** * Tells if the SDK was added as a pipenv. */ var Sdk.isPipEnv: Boolean get() = sdkAdditionalData is PyPipEnvSdkAdditionalData set(value) { val oldData = sdkAdditionalData val newData = if (value) { when (oldData) { is PythonSdkAdditionalData -> PyPipEnvSdkAdditionalData(oldData) else -> PyPipEnvSdkAdditionalData() } } else { when (oldData) { is PyPipEnvSdkAdditionalData -> PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(this)) else -> oldData } } val modificator = sdkModificator modificator.sdkAdditionalData = newData ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() } } /** * The user-set persisted path to the pipenv executable. */ var PropertiesComponent.pipEnvPath: @SystemDependent String? get() = getValue(PIPENV_PATH_SETTING) set(value) { setValue(PIPENV_PATH_SETTING, value) } /** * Detects the pipenv executable in `$PATH`. */ fun detectPipEnvExecutable(): File? { val name = when { SystemInfo.isWindows -> "pipenv.exe" else -> "pipenv" } return PathEnvironmentVariableUtil.findInPath(name) } /** * Returns the configured pipenv executable or detects it automatically. */ fun getPipEnvExecutable(): File? = PropertiesComponent.getInstance().pipEnvPath?.let { File(it) } ?: detectPipEnvExecutable() fun validatePipEnvExecutable(pipEnvExecutable: @SystemDependent String?): ValidationInfo? { val message = if (pipEnvExecutable.isNullOrBlank()) { PyBundle.message("python.sdk.pipenv.executable.not.found") } else { val file = File(pipEnvExecutable) when { !file.exists() -> PyBundle.message("python.sdk.file.not.found", file.absolutePath) !file.canExecute() || !file.isFile -> PyBundle.message("python.sdk.cannot.execute", file.absolutePath) else -> null } } return message?.let { ValidationInfo(it) } } fun suggestedSdkName(basePath: @NlsSafe String): @NlsSafe String = "Pipenv (${PathUtil.getFileName(basePath)})" /** * Sets up the pipenv environment under the modal progress window. * * The pipenv is associated with the first valid object from this list: * * 1. New project specified by [newProjectPath] * 2. Existing module specified by [module] * 3. Existing project specified by [project] * * @return the SDK for pipenv, not stored in the SDK table yet. */ fun setupPipEnvSdkUnderProgress(project: Project?, module: Module?, existingSdks: List<Sdk>, newProjectPath: String?, python: String?, installPackages: Boolean): Sdk? { val projectPath = newProjectPath ?: module?.basePath ?: project?.basePath ?: return null val task = object : Task.WithResult<String, ExecutionException>(project, PyBundle.message("python.sdk.setting.up.pipenv.title"), true) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true val pipEnv = setupPipEnv(FileUtil.toSystemDependentName(projectPath), python, installPackages) return PythonSdkUtil.getPythonExecutable(pipEnv) ?: FileUtil.join(pipEnv, "bin", "python") } } return createSdkByGenerateTask(task, existingSdks, null, projectPath, suggestedSdkName(projectPath))?.apply { isPipEnv = true associateWithModule(module, newProjectPath) } } /** * Sets up the pipenv environment for the specified project path. * * @return the path to the pipenv environment. */ fun setupPipEnv(projectPath: @SystemDependent String, python: String?, installPackages: Boolean): @SystemDependent String { when { installPackages -> { val pythonArgs = if (python != null) listOf("--python", python) else emptyList() val command = pythonArgs + listOf("install", "--dev") runPipEnv(projectPath, *command.toTypedArray()) } python != null -> runPipEnv(projectPath, "--python", python) else -> runPipEnv(projectPath, "run", "python", "-V") } return runPipEnv(projectPath, "--venv").trim() } /** * Runs the configured pipenv for the specified Pipenv SDK with the associated project path. */ fun runPipEnv(sdk: Sdk, vararg args: String): String { val projectPath = sdk.associatedModulePath ?: throw PyExecutionException( PyBundle.message("python.sdk.pipenv.execution.exception.no.project.message"), "Pipenv", emptyList(), ProcessOutput()) return runPipEnv(projectPath, *args) } /** * Runs the configured pipenv for the specified project path. */ fun runPipEnv(projectPath: @SystemDependent String, vararg args: String): String { val executable = getPipEnvExecutable()?.path ?: throw PyExecutionException( PyBundle.message("python.sdk.pipenv.execution.exception.no.pipenv.message"), "pipenv", emptyList(), ProcessOutput()) val command = listOf(executable) + args val commandLine = GeneralCommandLine(command).withWorkDirectory(projectPath) val handler = CapturingProcessHandler(commandLine) val indicator = ProgressManager.getInstance().progressIndicator val result = with(handler) { when { indicator != null -> { addProcessListener(IndicatedProcessOutputListener(indicator)) runProcessWithProgressIndicator(indicator) } else -> runProcess() } } return with(result) { when { isCancelled -> throw RunCanceledByUserException() exitCode != 0 -> throw PyExecutionException(PyBundle.message("python.sdk.pipenv.execution.exception.error.running.pipenv.message"), executable, args.asList(), stdout, stderr, exitCode, emptyList()) else -> stdout } } } /** * The URLs of package sources configured in the Pipfile.lock of the module associated with this SDK. */ val Sdk.pipFileLockSources: List<String> get() = parsePipFileLock()?.meta?.sources?.mapNotNull { it.url } ?: listOf(PIPENV_DEFAULT_SOURCE_URL) /** * The list of requirements defined in the Pipfile.lock of the module associated with this SDK. */ val Sdk.pipFileLockRequirements: List<PyRequirement>? get() { return pipFileLock?.let { getPipFileLockRequirements(it, packageManager) } } /** * A quick-fix for setting up the pipenv for the module of the current PSI element. */ class UsePipEnvQuickFix(sdk: Sdk?, module: Module) : LocalQuickFix { @IntentionName private val quickFixName = when { sdk != null && sdk.isAssociatedWithAnotherModule(module) -> PyBundle.message("python.sdk.pipenv.quickfix.fix.pipenv.name") else -> PyBundle.message("python.sdk.pipenv.quickfix.use.pipenv.name") } companion object { fun isApplicable(module: Module): Boolean = module.pipFile != null fun setUpPipEnv(project: Project, module: Module) { val sdksModel = ProjectSdksModel().apply { reset(project) } val existingSdks = sdksModel.sdks.filter { it.sdkType is PythonSdkType } // XXX: Should we show an error message on exceptions and on null? val newSdk = setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false) ?: return val existingSdk = existingSdks.find { it.isPipEnv && it.homePath == newSdk.homePath } val sdk = existingSdk ?: newSdk if (sdk == newSdk) { SdkConfigurationUtil.addSdk(newSdk) } else { sdk.associateWithModule(module, null) } project.pythonSdk = sdk module.pythonSdk = sdk } } override fun getFamilyName() = quickFixName override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return // Invoke the setup later to escape the write action of the quick fix in order to show the modal progress dialog ApplicationManager.getApplication().invokeLater { if (project.isDisposed || module.isDisposed) return@invokeLater setUpPipEnv(project, module) } } } /** * A quick-fix for installing packages specified in Pipfile.lock. */ class PipEnvInstallQuickFix : LocalQuickFix { companion object { fun pipEnvInstall(project: Project, module: Module) { val sdk = module.pythonSdk ?: return if (!sdk.isPipEnv) return val listener = PyPackageRequirementsInspection.RunningPackagingTasksListener(module) val ui = PyPackageManagerUI(project, sdk, listener) ui.install(null, listOf("--dev")) } } override fun getFamilyName() = PyBundle.message("python.sdk.install.requirements.from.pipenv.lock") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return pipEnvInstall(project, module) } } /** * Watches for edits in Pipfiles inside modules with a pipenv SDK set. */ class PipEnvPipFileWatcher : EditorFactoryListener { private val changeListenerKey = Key.create<DocumentListener>("Pipfile.change.listener") private val notificationActive = Key.create<Boolean>("Pipfile.notification.active") override fun editorCreated(event: EditorFactoryEvent) { val project = event.editor.project if (project == null || !isPipFileEditor(event.editor)) return val listener = object : DocumentListener { override fun documentChanged(event: DocumentEvent) { val document = event.document val module = document.virtualFile?.getModule(project) ?: return if (FileDocumentManager.getInstance().isDocumentUnsaved(document)) { notifyPipFileChanged(module) } } } with(event.editor.document) { addDocumentListener(listener) putUserData(changeListenerKey, listener) } } override fun editorReleased(event: EditorFactoryEvent) { val listener = event.editor.getUserData(changeListenerKey) ?: return event.editor.document.removeDocumentListener(listener) } private fun notifyPipFileChanged(module: Module) { if (module.getUserData(notificationActive) == true) return val title = when { module.pipFileLock == null -> PyBundle.message("python.sdk.pipenv.pip.file.lock.not.found") else -> PyBundle.message("python.sdk.pipenv.pip.file.lock.out.of.date") } val content = PyBundle.message("python.sdk.pipenv.pip.file.notification.content") val notification = LOCK_NOTIFICATION_GROUP.createNotification(title = title, content = content, listener = NotificationListener { notification, event -> notification.expire() module.putUserData(notificationActive, null) FileDocumentManager.getInstance().saveAllDocuments() when (event.description) { "#lock" -> runPipEnvInBackground(module, listOf("lock"), PyBundle.message( "python.sdk.pipenv.pip.file.notification.locking", PIP_FILE)) "#update" -> runPipEnvInBackground(module, listOf("update", "--dev"), PyBundle.message( "python.sdk.pipenv.pip.file.notification.updating")) } }) module.putUserData(notificationActive, true) notification.whenExpired { module.putUserData(notificationActive, null) } notification.notify(module.project) } private fun runPipEnvInBackground(module: Module, args: List<String>, @ProgressTitle description: String) { val task = object : Task.Backgroundable(module.project, description, true) { override fun run(indicator: ProgressIndicator) { val sdk = module.pythonSdk ?: return indicator.text = "$description..." try { runPipEnv(sdk, *args.toTypedArray()) } catch (e: RunCanceledByUserException) { } catch (e: ExecutionException) { showSdkExecutionException(sdk, e, PyBundle.message("python.sdk.pipenv.execution.exception.error.running.pipenv.message")) } finally { PythonSdkUtil.getSitePackagesDirectory(sdk)?.refresh(true, true) sdk.associatedModuleDir?.refresh(true, false) } } } ProgressManager.getInstance().run(task) } private fun isPipFileEditor(editor: Editor): Boolean { val file = editor.document.virtualFile ?: return false if (file.name != PIP_FILE) return false val project = editor.project ?: return false val module = file.getModule(project) ?: return false if (module.pipFile != file) return false return module.pythonSdk?.isPipEnv == true } } private val Document.virtualFile: VirtualFile? get() = FileDocumentManager.getInstance().getFile(this) private fun VirtualFile.getModule(project: Project): Module? = ModuleUtil.findModuleForFile(this, project) private val LOCK_NOTIFICATION_GROUP = NotificationGroup(PyBundle.message("python.sdk.pipenv.pip.file.watcher"), NotificationDisplayType.STICKY_BALLOON, false) private val Sdk.packageManager: PyPackageManager get() = PyPackageManagers.getInstance().forSdk(this) @TestOnly fun getPipFileLockRequirements(virtualFile: VirtualFile, packageManager: PyPackageManager): List<PyRequirement>? { fun toRequirements(packages: Map<String, PipFileLockPackage>): List<PyRequirement> = packages .asSequence() .filterNot { (_, pkg) -> pkg.editable ?: false } // TODO: Support requirements markers (PEP 496), currently any packages with markers are ignored due to PY-30803 .filter { (_, pkg) -> pkg.markers == null } .flatMap { (name, pkg) -> packageManager.parseRequirements("$name${pkg.version ?: ""}").asSequence() } .toList() val pipFileLock = parsePipFileLock(virtualFile) ?: return null val packages = pipFileLock.packages?.let { toRequirements(it) } ?: emptyList() val devPackages = pipFileLock.devPackages?.let { toRequirements(it) } ?: emptyList() return packages + devPackages } private fun Sdk.parsePipFileLock(): PipFileLock? { // TODO: Log errors if Pipfile.lock is not found val file = pipFileLock ?: return null return parsePipFileLock(file) } private fun parsePipFileLock(virtualFile: VirtualFile): PipFileLock? { val text = ReadAction.compute<String, Throwable> { FileDocumentManager.getInstance().getDocument(virtualFile)?.text } return try { Gson().fromJson(text, PipFileLock::class.java) } catch (e: JsonSyntaxException) { // TODO: Log errors return null } } val Sdk.pipFileLock: VirtualFile? get() = associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it)?.findChild(PIP_FILE_LOCK) } private val Module.pipFileLock: VirtualFile? get() = baseDir?.findChild(PIP_FILE_LOCK) private data class PipFileLock(@SerializedName("_meta") var meta: PipFileLockMeta?, @SerializedName("default") var packages: Map<String, PipFileLockPackage>?, @SerializedName("develop") var devPackages: Map<String, PipFileLockPackage>?) private data class PipFileLockMeta(@SerializedName("sources") var sources: List<PipFileLockSource>?) private data class PipFileLockSource(@SerializedName("url") var url: String?) private data class PipFileLockPackage(@SerializedName("version") var version: String?, @SerializedName("editable") var editable: Boolean?, @SerializedName("hashes") var hashes: List<String>?, @SerializedName("markers") var markers: String?)
apache-2.0
allotria/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogger.kt
2
4576
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog import com.intellij.internal.statistic.eventLog.logger.StatisticsEventLogThrottleWriter import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.Disposer import org.jetbrains.annotations.ApiStatus import java.nio.file.Path import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit interface StatisticsEventLogger { @Deprecated("Use StatisticsEventLogger.logAsync()", ReplaceWith("logAsync(group, eventId, isState)")) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun log(group: EventLogGroup, eventId: String, isState: Boolean) { logAsync(group, eventId, isState) } @Deprecated("Use StatisticsEventLogger.logAsync", ReplaceWith("logAsync(group, eventId, data, isState)")) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun log(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean) { logAsync(group, eventId, data, isState) } fun logAsync(group: EventLogGroup, eventId: String, isState: Boolean): CompletableFuture<Void> = logAsync(group, eventId, Collections.emptyMap(), isState) fun logAsync(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean): CompletableFuture<Void> fun getActiveLogFile(): EventLogFile? fun getLogFilesProvider(): EventLogFilesProvider fun cleanup() fun rollOver() } abstract class StatisticsEventLoggerProvider(val recorderId: String, val version: Int, val sendFrequencyMs: Long = TimeUnit.HOURS.toMillis(1), private val maxFileSize: String = "200KB") { open val logger: StatisticsEventLogger by lazy { createLogger() } abstract fun isRecordEnabled() : Boolean abstract fun isSendEnabled() : Boolean fun getActiveLogFile(): EventLogFile? { return logger.getActiveLogFile() } fun getLogFilesProvider(): EventLogFilesProvider { return logger.getLogFilesProvider() } private fun createLogger(): StatisticsEventLogger { if (!isRecordEnabled()) { return EmptyStatisticsEventLogger() } val app = ApplicationManager.getApplication() val isEap = app != null && app.isEAP val isHeadless = app != null && app.isHeadlessEnvironment val config = EventLogConfiguration.getOrCreate(recorderId) val writer = StatisticsEventLogFileWriter(recorderId, maxFileSize, isEap, EventLogConfiguration.build) val configService = EventLogConfigOptionsService.getInstance() val throttledWriter = StatisticsEventLogThrottleWriter( configService, recorderId, version.toString(), EventLogNotificationProxy(writer, recorderId) ) val logger = StatisticsFileEventLogger( recorderId, config.sessionId, isHeadless, EventLogConfiguration.build, config.bucket.toString(), version.toString(), throttledWriter, UsageStatisticsPersistenceComponent.getInstance() ) Disposer.register(ApplicationManager.getApplication(), logger) return logger } } internal class EmptyStatisticsEventLoggerProvider(recorderId: String): StatisticsEventLoggerProvider(recorderId, 0, -1) { override val logger: StatisticsEventLogger = EmptyStatisticsEventLogger() override fun isRecordEnabled() = false override fun isSendEnabled() = false } internal class EmptyStatisticsEventLogger : StatisticsEventLogger { override fun getActiveLogFile(): EventLogFile? = null override fun getLogFilesProvider(): EventLogFilesProvider = EmptyEventLogFilesProvider override fun cleanup() = Unit override fun rollOver() = Unit override fun logAsync(group: EventLogGroup, eventId: String, data: Map<String, Any>, isState: Boolean): CompletableFuture<Void> = CompletableFuture.completedFuture(null) } object EmptyEventLogFilesProvider: EventLogFilesProvider { override fun getLogFilesDir(): Path? = null override fun getLogFiles(): List<EventLogFile> = emptyList() } @Deprecated("Use StatisticsEventLogProviderUtil.getEventLogProvider(String)", ReplaceWith("StatisticsEventLogProviderUtil.getEventLogProvider(recorderId)")) fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider { return StatisticsEventLogProviderUtil.getEventLogProvider(recorderId) }
apache-2.0
allotria/intellij-community
community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/createProject/CreateJavaProjectWithKotlinGuiTest.kt
6
1028
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard.kotlin.createProject import com.intellij.ide.projectWizard.kotlin.model.* import com.intellij.testGuiFramework.util.scenarios.NewProjectDialogModel import com.intellij.testGuiFramework.util.scenarios.projectStructureDialogScenarios import org.junit.Test class CreateJavaProjectWithKotlinGuiTest : KotlinGuiTestCase() { private val testedJdk = "1.8" @Test @JvmName("java_with_jvm") fun createJavaWithKotlinJvmProject() { createJavaProject(projectFolder, testedJdk, setOf(NewProjectDialogModel.LibraryOrFramework(kotlinProjects.getValue(Projects.JavaProject).frameworkName))) projectStructureDialogScenarios.checkKotlinLibsInStructureFromPlugin( project = kotlinProjects.getValue(Projects.JavaProject), kotlinVersion = KotlinTestProperties.kotlin_artifact_version ) } }
apache-2.0
allotria/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/scheme/EventsTestSchemeGroupConfiguration.kt
3
15257
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.actions.scheme import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonObject import com.google.gson.JsonSyntaxException import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.internal.statistic.StatisticsBundle import com.intellij.internal.statistic.actions.TestParseEventsSchemeDialog import com.intellij.internal.statistic.eventLog.validator.storage.GroupValidationTestRule import com.intellij.internal.statistic.eventLog.validator.storage.GroupValidationTestRule.Companion.EMPTY_RULES import com.intellij.internal.statistic.eventLog.events.EventsSchemeBuilder import com.intellij.internal.statistic.eventLog.connection.metadata.EventGroupRemoteDescriptors import com.intellij.json.JsonLanguage import com.intellij.openapi.Disposable import com.intellij.openapi.application.WriteAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.psi.SyntaxTraverser import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.ContextHelpLabel import com.intellij.ui.components.JBRadioButton import com.intellij.ui.layout.* import com.intellij.util.IncorrectOperationException import com.intellij.util.TextFieldCompletionProviderDumbAware import com.intellij.util.ThrowableRunnable import com.intellij.util.textCompletion.TextFieldWithCompletion import com.intellij.util.ui.JBUI import com.jetbrains.jsonSchema.impl.inspections.JsonSchemaComplianceInspection import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class EventsTestSchemeGroupConfiguration(private val project: Project, productionGroups: EventGroupRemoteDescriptors, initialGroup: GroupValidationTestRule, generatedScheme: List<EventsSchemeBuilder.GroupDescriptor>, groupIdChangeListener: ((GroupValidationTestRule) -> Unit)? = null) : Disposable { val panel: JPanel val groupIdTextField: TextFieldWithCompletion private val log = logger<EventsTestSchemeGroupConfiguration>() private var currentGroup: GroupValidationTestRule = initialGroup private lateinit var allowAllEventsRadioButton: JBRadioButton private lateinit var customRulesRadioButton: JBRadioButton private lateinit var generateSchemeButton: JComponent private val validationRulesEditorComponent: JComponent private val validationRulesDescription: JLabel private val tempFile: PsiFile private val validationRulesEditor: EditorEx private val eventsScheme: Map<String, String> = createEventsScheme(generatedScheme) init { groupIdTextField = TextFieldWithCompletion(project, createCompletionProvider(productionGroups), initialGroup.groupId, true, true, false) groupIdTextField.addDocumentListener(object : DocumentListener { override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) { currentGroup.groupId = groupIdTextField.text if (groupIdChangeListener != null) { groupIdChangeListener(currentGroup) } updateGenerateSchemeButton() } }) tempFile = TestParseEventsSchemeDialog.createTempFile(project, "event-log-validation-rules", currentGroup.customRules)!! tempFile.virtualFile.putUserData(EventsSchemeJsonSchemaProviderFactory.EVENTS_TEST_SCHEME_VALIDATION_RULES_KEY, true) tempFile.putUserData(FUS_TEST_SCHEME_COMMON_RULES_KEY, ProductionRules(productionGroups.rules)) validationRulesEditor = createEditor(project, tempFile) validationRulesEditor.document.addDocumentListener(object : DocumentListener { override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) { currentGroup.customRules = validationRulesEditor.document.text } }) validationRulesEditorComponent = validationRulesEditor.component validationRulesEditorComponent.minimumSize = JBUI.size(200, 100) validationRulesDescription = ComponentPanelBuilder.createCommentComponent( StatisticsBundle.message("stats.validation.rules.format"), true) panel = panel { row { cell { label(StatisticsBundle.message("stats.group.id")) groupIdTextField(growX) } } buttonGroup { row { allowAllEventsRadioButton = radioButton(StatisticsBundle.message("stats.allow.all.events")).component allowAllEventsRadioButton.isSelected = !initialGroup.useCustomRules allowAllEventsRadioButton.addChangeListener { updateRulesOption() } } row { cell { customRulesRadioButton = radioButton(StatisticsBundle.message("stats.use.custom.validation.rules")).component customRulesRadioButton.isSelected = initialGroup.useCustomRules customRulesRadioButton.addChangeListener { updateRulesOption() } ContextHelpLabel.create(StatisticsBundle.message("stats.test.scheme.custom.rules.help"))() } } } row { validationRulesEditorComponent(growX) } row { generateSchemeButton = button("Generate scheme") { val scheme = eventsScheme[groupIdTextField.text] if (scheme != null) { WriteAction.run<Throwable> { validationRulesEditor.document.setText(scheme) } } }.component } row { validationRulesDescription() } } .withBorder(JBUI.Borders.empty(2)) updateRulesOption() } private fun updateGenerateSchemeButton() { val useCustomRules = customRulesRadioButton.isSelected generateSchemeButton.isVisible = useCustomRules generateSchemeButton.isEnabled = useCustomRules && eventsScheme[groupIdTextField.text] != null if (!generateSchemeButton.isEnabled) { generateSchemeButton.toolTipText = StatisticsBundle.message("stats.scheme.generation.available.only.for.new.api") } else { generateSchemeButton.toolTipText = null } } private fun createCompletionProvider(productionGroups: EventGroupRemoteDescriptors): TextFieldCompletionProviderDumbAware { return object : TextFieldCompletionProviderDumbAware() { override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) { val generatedSchemeVariants = eventsScheme.keys.map { LookupElementBuilder.create(it).withInsertHandler(InsertHandler { _, item -> val scheme = eventsScheme[item.lookupString] if (scheme != null) { customRulesRadioButton.isSelected = true WriteAction.run<Throwable> { validationRulesEditor.document.setText(scheme) } } }) } result.addAllElements(generatedSchemeVariants) val productionGroupsVariants = productionGroups.groups.asSequence() .mapNotNull { it.id } .filterNot { eventsScheme.keys.contains(it) } .map { LookupElementBuilder.create(it).withInsertHandler(InsertHandler { _, _ -> allowAllEventsRadioButton.isSelected = true WriteAction.run<Throwable> { validationRulesEditor.document.setText(EMPTY_RULES) } }) }.toList() result.addAllElements(productionGroupsVariants) } } } private fun createEditor(project: Project, file: PsiFile): EditorEx { var document = PsiDocumentManager.getInstance(project).getDocument(file) if (document == null) { document = EditorFactory.getInstance().createDocument(currentGroup.customRules) } val editor = EditorFactory.getInstance().createEditor(document, project, file.virtualFile, false) as EditorEx editor.setFile(file.virtualFile) editor.settings.isLineMarkerAreaShown = false editor.settings.isFoldingOutlineShown = false val fileType = FileTypeManager.getInstance().findFileTypeByName("JSON") val lightFile = LightVirtualFile("Dummy.json", fileType, "") val highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, lightFile) try { editor.highlighter = highlighter } catch (e: Throwable) { log.warn(e) } return editor } fun updatePanel(newGroup: GroupValidationTestRule?) { if (newGroup == null) return currentGroup = newGroup groupIdTextField.text = newGroup.groupId groupIdTextField.requestFocusInWindow() if (newGroup.useCustomRules) { customRulesRadioButton.isSelected = true } else { allowAllEventsRadioButton.isSelected = true } WriteAction.run<Throwable> { validationRulesEditor.document.setText(newGroup.customRules) } } private fun updateRulesOption() { val useCustomRules = customRulesRadioButton.isSelected validationRulesEditorComponent.isVisible = useCustomRules validationRulesDescription.isVisible = useCustomRules updateGenerateSchemeButton() currentGroup.useCustomRules = useCustomRules } fun getFocusedComponent(): JComponent = groupIdTextField override fun dispose() { WriteCommandAction.writeCommandAction(project).run( ThrowableRunnable<RuntimeException> { try { tempFile.delete() } catch (e: IncorrectOperationException) { log.warn(e) } }) if (!validationRulesEditor.isDisposed) { EditorFactory.getInstance().releaseEditor(validationRulesEditor) } } fun validate(): List<ValidationInfo> { return validateTestSchemeGroup(project, currentGroup, groupIdTextField, tempFile) } private fun createEventsScheme(generatedScheme: List<EventsSchemeBuilder.GroupDescriptor>): HashMap<String, String> { val eventsScheme = HashMap<String, String>() val gson = GsonBuilder().setPrettyPrinting().create() for (group in generatedScheme) { val validationRules = createValidationRules(group) if (validationRules != null) { eventsScheme[group.id] = gson.toJson(validationRules) } } return eventsScheme } private fun createValidationRules(group: EventsSchemeBuilder.GroupDescriptor): EventGroupRemoteDescriptors.GroupRemoteRule? { val eventIds = hashSetOf<String>() val eventData = hashMapOf<String, MutableSet<String>>() val events = group.schema for (event in events) { eventIds.add(event.event) for (dataField in event.fields) { val validationRule = dataField.value val validationRules = eventData[dataField.path] if (validationRules == null) { eventData[dataField.path] = validationRule.toHashSet() } else { validationRules.addAll(validationRule) } } } if (eventIds.isEmpty() && eventData.isEmpty()) return null val rules = EventGroupRemoteDescriptors.GroupRemoteRule() rules.event_id = eventIds rules.event_data = eventData return rules } companion object { internal val FUS_TEST_SCHEME_COMMON_RULES_KEY = Key.create<ProductionRules>("statistics.test.scheme.validation.rules.file") fun validateTestSchemeGroup(project: Project, testSchemeGroup: GroupValidationTestRule, groupIdTextField: JComponent): List<ValidationInfo> { return validateTestSchemeGroup(project, testSchemeGroup, groupIdTextField, null) } private fun validateTestSchemeGroup(project: Project, testSchemeGroup: GroupValidationTestRule, groupIdTextField: JComponent, customRulesFile: PsiFile?): List<ValidationInfo> { val groupId: String = testSchemeGroup.groupId val validationInfo = mutableListOf<ValidationInfo>() if (groupId.isEmpty()) { validationInfo.add(ValidationInfo(StatisticsBundle.message("stats.specify.group.id"), groupIdTextField)) } if (testSchemeGroup.useCustomRules) { validationInfo.addAll(validateCustomValidationRules(project, testSchemeGroup.customRules, customRulesFile)) } return validationInfo } internal fun validateCustomValidationRules(project: Project, customRules: String, customRulesFile: PsiFile?): List<ValidationInfo> { if (customRules.isBlank()) return listOf(ValidationInfo(StatisticsBundle.message("stats.unable.to.parse.validation.rules"))) val file = if (customRulesFile != null) { customRulesFile } else { val psiFile = PsiFileFactory.getInstance(project).createFileFromText(JsonLanguage.INSTANCE, customRules) psiFile.virtualFile.putUserData(EventsSchemeJsonSchemaProviderFactory.EVENTS_TEST_SCHEME_VALIDATION_RULES_KEY, true) psiFile } if (!isValidJson(customRules)) return listOf(ValidationInfo(StatisticsBundle.message("stats.unable.to.parse.validation.rules"))) val problemHolder = ProblemsHolder(InspectionManager.getInstance(project), file, true) val inspectionSession = LocalInspectionToolSession(file, file.textRange.startOffset, file.textRange.endOffset) val inspectionVisitor = JsonSchemaComplianceInspection() .buildVisitor(problemHolder, problemHolder.isOnTheFly, inspectionSession) val traverser = SyntaxTraverser.psiTraverser(file) for (element in traverser) { element.accept(inspectionVisitor) } return problemHolder.results.map { ValidationInfo("Line ${it.lineNumber + 1}: ${it.descriptionTemplate}") } } private fun isValidJson(customRules: String): Boolean { try { Gson().fromJson(customRules, JsonObject::class.java) return true } catch (e: JsonSyntaxException) { return false } } } internal class ProductionRules(val regexps: Set<String>, val enums: Set<String>) { constructor(rules: EventGroupRemoteDescriptors.GroupRemoteRule?) : this(rules?.regexps?.keys ?: emptySet(), rules?.enums?.keys ?: emptySet()) } }
apache-2.0
pzhangleo/android-base
base/src/main/java/hope/base/initializer/ContextInitializer.kt
1
377
package hope.base.initializer import android.content.Context import androidx.startup.Initializer import hope.base.AppConstant class ContextInitializer: Initializer<Unit> { override fun create(context: Context): Unit { AppConstant.init(context) } override fun dependencies(): MutableList<Class<out Initializer<*>>> { return mutableListOf() } }
lgpl-3.0
leafclick/intellij-community
platform/workspaceModel-core-tests/test/com/intellij/workspace/api/SimplePropertiesInProxyBasedStorageTest.kt
1
7092
package com.intellij.workspace.api import org.junit.Assert.* import org.junit.Test internal interface SampleEntity : TypedEntity { val booleanProperty: Boolean val stringProperty: String val stringListProperty: List<String> val fileProperty: VirtualFileUrl } internal interface ModifiableSampleEntity : SampleEntity, ModifiableTypedEntity<SampleEntity> { override var booleanProperty: Boolean override var stringProperty: String override var stringListProperty: MutableList<String> override var fileProperty: VirtualFileUrl } internal interface SelfModifiableSampleEntity : ModifiableTypedEntity<SelfModifiableSampleEntity> { var intProperty: Int } internal fun TypedEntityStorageBuilder.addSampleEntity(stringProperty: String, source: EntitySource = SampleEntitySource("test"), booleanProperty: Boolean = false, stringListProperty: MutableList<String> = ArrayList(), fileProperty: VirtualFileUrl = VirtualFileUrlManager.fromUrl("file:///tmp")): SampleEntity { return addEntity<ModifiableSampleEntity, SampleEntity>(source) { this.booleanProperty = booleanProperty this.stringProperty = stringProperty this.stringListProperty = stringListProperty this.fileProperty = fileProperty } } internal fun TypedEntityStorage.singleSampleEntity() = entities(SampleEntity::class.java).single() internal data class SampleEntitySource(val name: String) : EntitySource class SimplePropertiesInProxyBasedStorageTest { @Test fun `add entity`() { val builder = TypedEntityStorageBuilder.create() val source = SampleEntitySource("test") val entity = builder.addSampleEntity("hello", source, true, mutableListOf("one", "two")) builder.checkConsistency() assertTrue(entity.booleanProperty) assertEquals("hello", entity.stringProperty) assertEquals(listOf("one", "two"), entity.stringListProperty) assertEquals(entity, builder.singleSampleEntity()) assertEquals(source, entity.entitySource) } @Test fun `remove entity`() { val builder = TypedEntityStorageBuilder.create() val entity = builder.addSampleEntity("hello") builder.removeEntity(entity) builder.checkConsistency() assertTrue(builder.entities(SampleEntity::class.java).toList().isEmpty()) } @Test fun `modify entity`() { val builder = TypedEntityStorageBuilder.create() val original = builder.addSampleEntity("hello") val modified = builder.modifyEntity(ModifiableSampleEntity::class.java, original) { stringProperty = "foo" stringListProperty.add("first") booleanProperty = true fileProperty = VirtualFileUrlManager.fromUrl("file:///xxx") } builder.checkConsistency() assertEquals("hello", original.stringProperty) assertEquals(emptyList<String>(), original.stringListProperty) assertEquals("foo", modified.stringProperty) assertEquals(listOf("first"), modified.stringListProperty) assertTrue(modified.booleanProperty) assertEquals("file:///xxx", modified.fileProperty.url) } @Test fun `edit self modifiable entity`() { val builder = TypedEntityStorageBuilder.create() val entity = builder.addEntity(SelfModifiableSampleEntity::class.java, SampleEntitySource("test")) { intProperty = 42 } assertEquals(42, entity.intProperty) val modified = builder.modifyEntity(SelfModifiableSampleEntity::class.java, entity) { intProperty = 239 } builder.checkConsistency() assertEquals(42, entity.intProperty) assertEquals(239, modified.intProperty) builder.removeEntity(modified) builder.checkConsistency() assertEquals(emptyList<SelfModifiableSampleEntity>(), builder.entities(SelfModifiableSampleEntity::class.java).toList()) } @Test fun `builder from storage`() { val storage = TypedEntityStorageBuilder.create().apply { addSampleEntity("hello") }.toStorage() storage.checkConsistency() assertEquals("hello", storage.singleSampleEntity().stringProperty) val builder = TypedEntityStorageBuilder.from(storage) builder.checkConsistency() assertEquals("hello", builder.singleSampleEntity().stringProperty) builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) { stringProperty = "good bye" } builder.checkConsistency() assertEquals("hello", storage.singleSampleEntity().stringProperty) assertEquals("good bye", builder.singleSampleEntity().stringProperty) } @Test fun `snapshot from builder`() { val builder = TypedEntityStorageBuilder.create() builder.addSampleEntity("hello") val snapshot = builder.toStorage() snapshot.checkConsistency() assertEquals("hello", builder.singleSampleEntity().stringProperty) assertEquals("hello", snapshot.singleSampleEntity().stringProperty) builder.modifyEntity(ModifiableSampleEntity::class.java, builder.singleSampleEntity()) { stringProperty = "good bye" } builder.checkConsistency() assertEquals("hello", snapshot.singleSampleEntity().stringProperty) assertEquals("good bye", builder.singleSampleEntity().stringProperty) } @Test(expected = IllegalStateException::class) fun `modifications are allowed inside special methods only`() { val entity = TypedEntityStorageBuilder.create().addEntity(SelfModifiableSampleEntity::class.java, SampleEntitySource("test")) { intProperty = 10 } entity.intProperty = 30 } @Test fun `different entities with same properties`() { val builder = TypedEntityStorageBuilder.create() val foo1 = builder.addSampleEntity("foo1") val foo2 = builder.addSampleEntity("foo1") val bar = builder.addSampleEntity("bar") builder.checkConsistency() assertFalse(foo1 == foo2) assertTrue(foo1.hasEqualProperties(foo1)) assertTrue(foo1.hasEqualProperties(foo2)) assertFalse(foo1.hasEqualProperties(bar)) val bar2 = builder.modifyEntity(ModifiableSampleEntity::class.java, bar) { stringProperty = "bar2" } assertTrue(bar == bar2) assertFalse(bar.hasEqualProperties(bar2)) val foo2a = builder.modifyEntity(ModifiableSampleEntity::class.java, foo2) { stringProperty = "foo2" } assertFalse(foo1.hasEqualProperties(foo2a)) } @Test fun `change source`() { val builder = TypedEntityStorageBuilder.create() val source1 = SampleEntitySource("1") val source2 = SampleEntitySource("2") val foo = builder.addSampleEntity("foo", source1) val foo2 = builder.changeSource(foo, source2) assertEquals(source1, foo.entitySource) assertEquals(source2, foo2.entitySource) assertEquals(source2, builder.singleSampleEntity().entitySource) assertEquals(foo2, builder.entitiesBySource { it == source2 }.values.flatMap { it.values.flatten() }.single()) assertTrue(builder.entitiesBySource { it == source1 }.values.all { it.isEmpty() }) } }
apache-2.0
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/GithubGitHelper.kt
1
4307
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import git4idea.GitUtil import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.api.GHRepositoryPath import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager /** * Utilities for Github-Git interactions * * accessible url - url that matches at least one registered account * possible url - accessible urls + urls that match github.com + urls that match server saved in old settings */ @Service class GithubGitHelper { fun getRemoteUrl(server: GithubServerPath, repoPath: GHRepositoryPath): String { return getRemoteUrl(server, repoPath.owner, repoPath.repository) } fun getRemoteUrl(server: GithubServerPath, user: String, repo: String): String { return if (GithubSettings.getInstance().isCloneGitUsingSsh) { "git@${server.host}:${server.suffix?.substring(1).orEmpty()}/$user/$repo.git" } else { "https://${server.host}${server.suffix.orEmpty()}/$user/$repo.git" } } fun getAccessibleRemoteUrls(repository: GitRepository): List<String> { return repository.getRemoteUrls().filter(::isRemoteUrlAccessible) } fun hasAccessibleRemotes(repository: GitRepository): Boolean { return repository.getRemoteUrls().any(::isRemoteUrlAccessible) } private fun isRemoteUrlAccessible(url: String) = GithubAuthenticationManager.getInstance().getAccounts().find { it.server.matches(url) } != null fun getPossibleRepositories(repository: GitRepository): Set<GHRepositoryCoordinates> { val knownServers = getKnownGithubServers() return repository.getRemoteUrls().mapNotNull { url -> knownServers.find { it.matches(url) } ?.let { server -> GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url)?.let { GHRepositoryCoordinates(server, it) } } }.toSet() } fun getPossibleRemoteUrlCoordinates(project: Project): Set<GitRemoteUrlCoordinates> { val repositories = project.service<GitRepositoryManager>().repositories if (repositories.isEmpty()) return emptySet() val knownServers = getKnownGithubServers() return repositories.flatMap { repo -> repo.remotes.flatMap { remote -> remote.urls.mapNotNull { url -> if (knownServers.any { it.matches(url) }) GitRemoteUrlCoordinates(url, remote, repo) else null } } }.toSet() } fun havePossibleRemotes(project: Project): Boolean { val repositories = project.service<GitRepositoryManager>().repositories if (repositories.isEmpty()) return false val knownServers = getKnownGithubServers() return repositories.any { repo -> repo.getRemoteUrls().any { url -> knownServers.any { it.matches(url) } } } } private fun getKnownGithubServers(): Set<GithubServerPath> { val registeredServers = mutableSetOf(GithubServerPath.DEFAULT_SERVER) GithubAccountsMigrationHelper.getInstance().getOldServer()?.run(registeredServers::add) GithubAuthenticationManager.getInstance().getAccounts().mapTo(registeredServers) { it.server } return registeredServers } private fun GitRepository.getRemoteUrls() = remotes.map { it.urls }.flatten() companion object { @JvmStatic fun findGitRepository(project: Project, file: VirtualFile? = null): GitRepository? { val manager = GitUtil.getRepositoryManager(project) val repositories = manager.repositories if (repositories.size == 0) { return null } if (repositories.size == 1) { return repositories[0] } if (file != null) { val repository = manager.getRepositoryForFileQuick(file) if (repository != null) { return repository } } return manager.getRepositoryForFileQuick(project.baseDir) } @JvmStatic fun getInstance(): GithubGitHelper { return service() } } }
apache-2.0
phxql/aleksa
src/main/kotlin/de/mkammerer/aleksa/SpeechletV2Base.kt
1
739
package de.mkammerer.aleksa import com.amazon.speech.json.SpeechletRequestEnvelope import com.amazon.speech.speechlet.* /** * Abstract class which a speechlet can use. * * Implenents [onSessionEnded] and [onSessionStarted] with empty methods. */ abstract class SpeechletV2Base : SpeechletV2 { override fun onSessionEnded(requestEnvelope: SpeechletRequestEnvelope<SessionEndedRequest>) { } override fun onSessionStarted(requestEnvelope: SpeechletRequestEnvelope<SessionStartedRequest>) { } abstract override fun onIntent(requestEnvelope: SpeechletRequestEnvelope<IntentRequest>): SpeechletResponse abstract override fun onLaunch(requestEnvelope: SpeechletRequestEnvelope<LaunchRequest>): SpeechletResponse }
lgpl-3.0
zdary/intellij-community
java/java-tests/testSrc/com/intellij/util/indexing/IndexInfrastructureExtensionTest.kt
2
2971
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing import com.intellij.ide.plugins.loadExtensionWithText import com.intellij.openapi.application.PathManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.psi.stubs.StubIndexKey import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import com.intellij.util.io.lastModified import org.junit.Assert import java.nio.file.Files import kotlin.streams.toList class IndexInfrastructureExtensionTest : LightJavaCodeInsightFixtureTestCase() { fun `test infrastructure extension drops all indexes when it requires invalidation`() { val text = "<fileBasedIndexInfrastructureExtension implementation=\"" + TestIndexInfrastructureExtension::class.java.name + "\"/>" Disposer.register(testRootDisposable, loadExtensionWithText(text, TestIndexInfrastructureExtension::class.java.classLoader)) val before = Files.list(PathManager.getIndexRoot()).use { it.toList().associate { p -> p.fileName.toString() to p.lastModified().toMillis() }.toSortedMap() } val switcher = FileBasedIndexSwitcher() switcher.turnOff() switcher.turnOn() val after = Files.list(PathManager.getIndexRoot()).use { it.toList().associate { p -> p.fileName.toString() to p.lastModified().toMillis() }.toSortedMap() } var containsExtensionCaches = false for ((b, a) in (before.entries zip after.entries)) { Assert.assertEquals(b.key, a.key) Assert.assertTrue(a.value > b.value) if (a.key.endsWith(testInfraExtensionFile)) { containsExtensionCaches = true } } Assert.assertTrue(containsExtensionCaches) } } const val testInfraExtensionFile = "_test_extension" class TestIndexInfrastructureExtension : FileBasedIndexInfrastructureExtension { override fun createFileIndexingStatusProcessor(project: Project): FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor? = null override fun <K : Any?, V : Any?> combineIndex(indexExtension: FileBasedIndexExtension<K, V>, baseIndex: UpdatableIndex<K, V, FileContent>): UpdatableIndex<K, V, FileContent>? { Files.createFile(PathManager.getIndexRoot().resolve(indexExtension.name.name + testInfraExtensionFile)) return null } override fun onFileBasedIndexVersionChanged(indexId: ID<*, *>) = Unit override fun onStubIndexVersionChanged(indexId: StubIndexKey<*, *>) = Unit override fun initialize(): FileBasedIndexInfrastructureExtension.InitializationResult = FileBasedIndexInfrastructureExtension.InitializationResult.INDEX_REBUILD_REQUIRED override fun resetPersistentState() = Unit override fun resetPersistentState(indexId: ID<*, *>) = Unit override fun shutdown() = Unit override fun getVersion(): Int = 0 }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/properties/classArtificialFieldInsideNested.kt
5
241
abstract class Your { abstract val your: String fun foo() = your } class My { val back = "O" val my: String get() = object : Your() { override val your = back }.foo() + "K" } fun box() = My().my
apache-2.0
KlubJagiellonski/pola-android
app/src/main/java/pl/pola_app/ui/activity/MainViewBinder.kt
1
630
package pl.pola_app.ui.activity import androidx.recyclerview.widget.RecyclerView import pl.pola_app.model.SearchResult internal interface MainViewBinder { fun setAdapter(adapter: RecyclerView.Adapter<*>) fun resumeScanning() fun turnOffTorch() fun openProductDetails(searchResult: SearchResult) fun showNoConnectionMessage() fun showErrorMessage(message: String?) fun dismissProductDetailsView() fun openWww(searchResult: SearchResult?, url: String?) fun setSupportPolaAppButtonVisibility(isVisible: Boolean, searchResult: SearchResult?) fun showNewRatePrompt() val deviceYear: Int }
gpl-2.0
Triple-T/gradle-play-publisher
common/utils/src/main/kotlin/com/github/triplet/gradle/common/utils/Constants.kt
1
232
package com.github.triplet.gradle.common.utils /** The plugin's non user-facing name. */ const val PLUGIN_NAME: String = "gradle-play-publisher" /** The plugin's Gradle task group. */ const val PLUGIN_GROUP: String = "Publishing"
mit
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/diagnostics/functions/tailRecursion/returnInTry.kt
2
410
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND_WITHOUT_CHECK: JS <!NO_TAIL_CALLS_FOUND!>tailrec fun test(counter : Int) : Int<!> { if (counter == 0) return 0 try { return <!TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED!>test<!>(counter - 1) } catch (any : Throwable) { return -1 } } fun box() : String = if (test(3) == 0) "OK" else "FAIL"
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/callableReference/bound/extensionReceiver.kt
3
244
// FILE: 1.kt package test inline fun foo(x: () -> String, z: String) = x() + z fun String.id() = this // FILE: 2.kt import test.* fun String.test() : String { return foo(this::id, "K") } fun box() : String { return "O".test() }
apache-2.0
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/utils/ScopedPermissionsRequester.kt
2
7198
package host.exp.exponent.utils import android.Manifest import host.exp.exponent.kernel.ExperienceKey import javax.inject.Inject import host.exp.exponent.kernel.services.ExpoKernelServiceRegistry import host.exp.exponent.experience.ReactNativeActivity import android.content.pm.PackageManager import android.app.AlertDialog import android.content.DialogInterface import android.os.Build import android.provider.Settings import com.facebook.react.modules.core.PermissionListener import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.expoview.Exponent import host.exp.expoview.R import java.util.* class ScopedPermissionsRequester(private val experienceKey: ExperienceKey) { @Inject lateinit var expoKernelServiceRegistry: ExpoKernelServiceRegistry private var permissionListener: PermissionListener? = null private var experienceName: String? = null private var permissionsResult = mutableMapOf<String, Int>() private val permissionsToRequestPerExperience = mutableListOf<String>() private val permissionsToRequestGlobally = mutableListOf<String>() private var permissionsAskedCount = 0 fun requestPermissions( currentActivity: ReactNativeActivity, experienceName: String?, permissions: Array<String>, listener: PermissionListener ) { permissionListener = listener this.experienceName = experienceName permissionsResult = mutableMapOf() for (permission in permissions) { val globalStatus = currentActivity.checkSelfPermission(permission) if (globalStatus == PackageManager.PERMISSION_DENIED) { permissionsToRequestGlobally.add(permission) } else if (!expoKernelServiceRegistry.permissionsKernelService.hasGrantedPermissions( permission, experienceKey ) ) { permissionsToRequestPerExperience.add(permission) } else { permissionsResult[permission] = PackageManager.PERMISSION_GRANTED } } if (permissionsToRequestPerExperience.isEmpty() && permissionsToRequestGlobally.isEmpty()) { callPermissionsListener() return } permissionsAskedCount = permissionsToRequestPerExperience.size if (permissionsToRequestPerExperience.isNotEmpty()) { requestExperienceAndGlobalPermissions(permissionsToRequestPerExperience[permissionsAskedCount - 1]) } else if (permissionsToRequestGlobally.isNotEmpty()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { currentActivity.requestPermissions( permissionsToRequestGlobally.toTypedArray(), EXPONENT_PERMISSIONS_REQUEST ) } else { val result = IntArray(permissionsToRequestGlobally.size) Arrays.fill(result, PackageManager.PERMISSION_DENIED) onRequestPermissionsResult(permissionsToRequestGlobally.toTypedArray(), result) } } } fun onRequestPermissionsResult(permissions: Array<String>, grantResults: IntArray): Boolean { if (permissionListener == null) { // sometimes onRequestPermissionsResult is called multiple times if the first permission // is rejected... return true } if (grantResults.isNotEmpty()) { for (i in grantResults.indices) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { expoKernelServiceRegistry.permissionsKernelService.grantScopedPermissions( permissions[i], experienceKey ) } permissionsResult[permissions[i]] = grantResults[i] } } return callPermissionsListener() } private fun callPermissionsListener(): Boolean { val permissions = permissionsResult.keys.toTypedArray() val result = IntArray(permissions.size) for (i in permissions.indices) { result[i] = permissionsResult[permissions[i]]!! } return permissionListener!!.onRequestPermissionsResult( EXPONENT_PERMISSIONS_REQUEST, permissions, result ) } private fun requestExperienceAndGlobalPermissions(permission: String) { val activity = Exponent.instance.currentActivity val builder = AlertDialog.Builder(activity) val onClickListener = PermissionsDialogOnClickListener(permission) builder .setMessage( activity!!.getString( R.string.experience_needs_permissions, experienceName, activity.getString(permissionToResId(permission)) ) ) .setPositiveButton(R.string.allow_experience_permissions, onClickListener) .setNegativeButton(R.string.deny_experience_permissions, onClickListener) .show() } private fun permissionToResId(permission: String): Int { return when (permission) { Manifest.permission.CAMERA -> R.string.perm_camera Manifest.permission.READ_CONTACTS -> R.string.perm_contacts_read Manifest.permission.WRITE_CONTACTS -> R.string.perm_contacts_write Manifest.permission.READ_EXTERNAL_STORAGE -> R.string.perm_camera_roll_read Manifest.permission.WRITE_EXTERNAL_STORAGE -> R.string.perm_camera_roll_write Manifest.permission.ACCESS_MEDIA_LOCATION -> R.string.perm_access_media_location Manifest.permission.RECORD_AUDIO -> R.string.perm_audio_recording Settings.ACTION_MANAGE_WRITE_SETTINGS -> R.string.perm_system_brightness Manifest.permission.READ_CALENDAR -> R.string.perm_calendar_read Manifest.permission.WRITE_CALENDAR -> R.string.perm_calendar_write Manifest.permission.ACCESS_FINE_LOCATION -> R.string.perm_fine_location Manifest.permission.ACCESS_COARSE_LOCATION -> R.string.perm_coarse_location Manifest.permission.ACCESS_BACKGROUND_LOCATION -> R.string.perm_background_location else -> -1 } } private inner class PermissionsDialogOnClickListener(private val permission: String) : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, which: Int) { permissionsAskedCount -= 1 when (which) { DialogInterface.BUTTON_POSITIVE -> { expoKernelServiceRegistry.permissionsKernelService.grantScopedPermissions( permission, [email protected] ) permissionsResult[permission] = PackageManager.PERMISSION_GRANTED } DialogInterface.BUTTON_NEGATIVE -> { expoKernelServiceRegistry.permissionsKernelService.revokeScopedPermissions( permission, experienceKey ) permissionsResult[permission] = PackageManager.PERMISSION_DENIED } } if (permissionsAskedCount > 0) { requestExperienceAndGlobalPermissions(permissionsToRequestPerExperience[permissionsAskedCount - 1]) } else if (permissionsToRequestGlobally.isNotEmpty() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Exponent.instance.currentActivity!!.requestPermissions( permissionsToRequestGlobally.toTypedArray(), EXPONENT_PERMISSIONS_REQUEST ) } else { callPermissionsListener() } } } companion object { const val EXPONENT_PERMISSIONS_REQUEST = 13 } init { NativeModuleDepsProvider.instance.inject(ScopedPermissionsRequester::class.java, this) } }
bsd-3-clause
snumr/logic-games-framework
src/logicgames/examples/GrundyGame.kt
1
767
/* * The MIT License * * Copyright 2014 Alexander Alexeev. * */ package org.mumidol.logicgames.examples import org.mumidol.logicgames.SequentialGame import org.mumidol.logicgames.Game class GrundyGame(val heaps: List<Int>, override val currPlayer: Int = 0) : SequentialGame() { override val playersCount = 2 override val isOver: Boolean = false override val winner: Int? = null fun split(heap: Int, count: Int) = object : Game.Turn<GrundyGame>((this : Game).TurnDefender()) { override fun move(): GrundyGame { val newHeaps = heaps.toArrayList() val n = newHeaps.remove(heap) newHeaps.add(count) newHeaps.add(n - count) return GrundyGame(newHeaps.toList()) } } }
mit
smmribeiro/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageSizeOptimizer.kt
12
3019
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import org.jetbrains.jps.model.module.JpsModule import java.awt.image.BufferedImage import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.atomic.AtomicLong import javax.imageio.ImageIO class ImageSizeOptimizer(private val projectHome: Path) { private val optimizedTotal = AtomicLong(0) private val totalFiles = AtomicLong(0) fun optimizeIcons(module: JpsModule, moduleConfig: IntellijIconClassGeneratorModuleConfig?) { val icons = ImageCollector(projectHome, moduleConfig = moduleConfig).collect(module) icons.parallelStream().forEach { icon -> icon.files.parallelStream().forEach { tryToReduceSize(it) } } } fun optimizeImages(file: Path): Int { if (Files.isDirectory(file)) { var count = 0 file.processChildren { count += optimizeImages(it) } return count } else { val success = tryToReduceSize(file) return if (success) 1 else 0 } } fun printStats() { println() println("PNG size optimization: ${optimizedTotal.get()} bytes in total in ${totalFiles.get()} files(s)") } private fun tryToReduceSize(file: Path): Boolean { val image = optimizeImage(file) ?: return false totalFiles.incrementAndGet() if (image.hasOptimumSize) return true try { Files.createDirectories(file.parent) Files.newOutputStream(file).use { out -> out.write(image.optimizedArray.internalBuffer, 0, image.optimizedArray.size()) } optimizedTotal.getAndAdd(image.sizeBefore - image.sizeAfter) } catch (e: IOException) { throw Exception("Cannot optimize $file") } println("$file ${image.compressionStats}") return true } companion object { fun optimizeImage(file: Path): OptimizedImage? { if (!file.fileName.toString().endsWith(".png")) { return null } val image = Files.newInputStream(file).buffered().use { ImageIO.read(it) } if (image == null) { println(file + " loading failed") return null } val byteArrayOutputStream = BufferExposingByteArrayOutputStream() ImageIO.write(image, "png", byteArrayOutputStream) return OptimizedImage(file, image, byteArrayOutputStream) } } class OptimizedImage(val file: Path, val image: BufferedImage, val optimizedArray: BufferExposingByteArrayOutputStream) { val sizeBefore: Long = Files.size(file) val sizeAfter: Int = optimizedArray.size() val compressionStats: String get() { val compression = (sizeBefore - sizeAfter) * 100 / sizeBefore return "$compression% optimized ($sizeBefore->$sizeAfter bytes)" } val hasOptimumSize: Boolean get() = sizeBefore <= sizeAfter } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/InlineFunctionHyperLinkInfo.kt
5
3573
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger import com.intellij.execution.filters.FileHyperlinkInfo import com.intellij.execution.filters.HyperlinkInfoBase import com.intellij.execution.filters.OpenFileHyperlinkInfo import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.awt.RelativePoint import org.jetbrains.annotations.Nls import java.awt.Component import javax.swing.JList import javax.swing.ListCellRenderer class InlineFunctionHyperLinkInfo( private val project: Project, private val inlineInfo: List<InlineInfo> ) : HyperlinkInfoBase(), FileHyperlinkInfo { override fun navigate(project: Project, hyperlinkLocationPoint: RelativePoint?) { if (inlineInfo.isEmpty()) return if (inlineInfo.size == 1) { OpenFileHyperlinkInfo(project, inlineInfo.first().file, inlineInfo.first().line).navigate(project) } else { val popup = JBPopupFactory.getInstance().createPopupChooserBuilder(inlineInfo) .setTitle(KotlinDebuggerCoreBundle.message("filters.title.navigate.to")) .setRenderer(InlineInfoCellRenderer()) .setItemChosenCallback { fileInfo -> fileInfo?.let { OpenFileHyperlinkInfo(project, fileInfo.file, fileInfo.line).navigate(project) } } .createPopup() if (hyperlinkLocationPoint != null) { popup.show(hyperlinkLocationPoint) } else { popup.showInFocusCenter() } } } override fun getDescriptor(): OpenFileDescriptor? { val file = inlineInfo.firstOrNull() return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) } } val callSiteDescriptor: OpenFileDescriptor? get() { val file = inlineInfo.firstOrNull { it is InlineInfo.CallSiteInfo } return file?.let { OpenFileDescriptor(project, file.file, file.line, 0) } } sealed class InlineInfo(@Nls val prefix: String, val file: VirtualFile, val line: Int) { class CallSiteInfo(file: VirtualFile, line: Int) : InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.call.site"), file, line) class InlineFunctionBodyInfo(file: VirtualFile, line: Int) : InlineInfo(KotlinDebuggerCoreBundle.message("filters.text.inline.function.body"), file, line) } private class InlineInfoCellRenderer : SimpleColoredComponent(), ListCellRenderer<InlineInfo> { init { isOpaque = true } override fun getListCellRendererComponent( list: JList<out InlineInfo>?, value: InlineInfo?, index: Int, isSelected: Boolean, cellHasFocus: Boolean ): Component { clear() if (value != null) { append(value.prefix) } if (isSelected) { background = list?.selectionBackground foreground = list?.selectionForeground } else { background = list?.background foreground = list?.foreground } return this } } }
apache-2.0
mglukhikh/intellij-community
python/src/com/jetbrains/python/sdk/PySdkSettings.kt
1
3681
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.sdk import com.intellij.application.options.ReplacePathToMacroMap import com.intellij.openapi.components.* import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.xmlb.XmlSerializerUtil import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import org.jetbrains.annotations.SystemIndependent import org.jetbrains.jps.model.serialization.PathMacroUtil /** * @author vlan */ @State(name = "PySdkSettings", storages = arrayOf(Storage(value = "py_sdk_settings.xml", roamingType = RoamingType.DISABLED))) class PySdkSettings : PersistentStateComponent<PySdkSettings.State> { companion object { @JvmStatic val instance: PySdkSettings get() = ServiceManager.getService(PySdkSettings::class.java) private const val VIRTUALENV_ROOT_DIR_MACRO_NAME = "VIRTUALENV_ROOT_DIR" } private val state: State = State() var useNewEnvironmentForNewProject: Boolean get() = state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT set(value) { state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT = value } var preferredEnvironmentType: String? get() = state.PREFERRED_ENVIRONMENT_TYPE set(value) { state.PREFERRED_ENVIRONMENT_TYPE = value } var preferredVirtualEnvBaseSdk: String? get() = state.PREFERRED_VIRTUALENV_BASE_SDK set(value) { state.PREFERRED_VIRTUALENV_BASE_SDK = value } fun setPreferredVirtualEnvBasePath(value: @SystemIndependent String, projectPath: @SystemIndependent String) { val pathMap = ReplacePathToMacroMap().apply { addMacroReplacement(projectPath, PathMacroUtil.PROJECT_DIR_MACRO_NAME) addMacroReplacement(defaultVirtualEnvRoot, VIRTUALENV_ROOT_DIR_MACRO_NAME) } val pathToSave = when { FileUtil.isAncestor(projectPath, value, true) -> value.trimEnd { !it.isLetter() } else -> PathUtil.getParentPath(value) } state.PREFERRED_VIRTUALENV_BASE_PATH = pathMap.substitute(pathToSave, true) } fun getPreferredVirtualEnvBasePath(projectPath: @SystemIndependent String): @SystemIndependent String { val pathMap = ExpandMacroToPathMap().apply { addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectPath) addMacroExpand(VIRTUALENV_ROOT_DIR_MACRO_NAME, defaultVirtualEnvRoot) } val defaultPath = when { defaultVirtualEnvRoot != userHome -> defaultVirtualEnvRoot else -> "$${PathMacroUtil.PROJECT_DIR_MACRO_NAME}$/venv" } val rawSavedPath = state.PREFERRED_VIRTUALENV_BASE_PATH ?: defaultPath val savedPath = pathMap.substitute(rawSavedPath, true) return when { FileUtil.isAncestor(projectPath, savedPath, true) -> savedPath else -> "$savedPath/${PathUtil.getFileName(projectPath)}" } } override fun getState() = state override fun loadState(state: PySdkSettings.State) { XmlSerializerUtil.copyBean(state, this.state) } @Suppress("PropertyName") class State { @JvmField var USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT: Boolean = true @JvmField var PREFERRED_ENVIRONMENT_TYPE: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_PATH: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_SDK: String? = null } private val defaultVirtualEnvRoot: @SystemIndependent String get() = VirtualEnvSdkFlavor.getDefaultLocation()?.path ?: userHome private val userHome: @SystemIndependent String get() = FileUtil.toSystemIndependentName(SystemProperties.getUserHome()) }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/fromLoadJava/kotlinSignature/propagation/return/InheritReadOnlinessSubclass.kt
10
291
package test public interface InheritReadOnlinessSubclass { public interface Super { public fun foo(): Collection<String> public fun dummy() // to avoid loading as SAM interface } public interface Sub: Super { override fun foo(): List<String> } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/branched/doubleBangToIfThen/topLevelVar.kt
9
187
// WITH_STDLIB // AFTER-WARNING: Parameter 'args' is never used // AFTER-WARNING: Variable 't' is never used var a: String? = "A" fun main(args: Array<String>) { val t = a<caret>!! }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/handlers/basic/override/AfterValKeywordInConstructorParameter.kt
13
135
interface I { val someVal: java.io.File? } class A(override val s<caret>) : I { } // ELEMENT_TEXT: "override val someVal: File?"
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinIfConditionFixer.kt
6
794
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor.fixers import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtIfExpression class KotlinIfConditionFixer : MissingConditionFixer<KtIfExpression>() { override val keyword = "if" override fun getElement(element: PsiElement?) = element as? KtIfExpression override fun getCondition(element: KtIfExpression) = element.condition override fun getLeftParenthesis(element: KtIfExpression) = element.leftParenthesis override fun getRightParenthesis(element: KtIfExpression) = element.rightParenthesis override fun getBody(element: KtIfExpression) = element.then }
apache-2.0
GlobalTechnology/android-gto-support
gto-support-util/src/test/kotlin/org/ccci/gto/android/common/util/database/CursorTest.kt
2
4250
package org.ccci.gto.android.common.util.database import android.database.Cursor import net.javacrumbs.jsonunit.JsonMatchers.jsonEquals import org.hamcrest.MatcherAssert.assertThat import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever private const val VALID = "valid" private const val INVALID = "invalid" class CursorTest { private lateinit var cursor: Cursor @Before fun setup() { cursor = mock() whenever(cursor.getColumnIndex(VALID)).thenReturn(0) whenever(cursor.getColumnIndex(INVALID)).thenReturn(-1) whenever(cursor.getString(-1)).thenThrow(RuntimeException::class.java) } // region getJSONArrayOrNull() @Test fun verifyGetJSONArrayOrNull() { wheneverGetValid().thenReturn("[\"a\", 1]") assertThat(cursor.getJSONArrayOrNull(VALID), jsonEquals(JSONArray(listOf("a", 1)))) } @Test fun testGetJSONArrayWhenNullValue() { wheneverGetValid().thenReturn(null) assertNull(cursor.getJSONArrayOrNull(VALID)) } @Test fun verifyGetJSONArrayOrNullWhenInvalidValue() { wheneverGetValid().thenReturn("{\"a\":1") assertNull(cursor.getJSONArrayOrNull(VALID)) } @Test fun verifyGetJSONArrayOrNullWhenNonExistentField() { assertNull(cursor.getJSONArrayOrNull(INVALID)) verify(cursor, never()).getString(any()) } // endregion getJSONArrayOrNull() // region getJSONObjectOrNull() @Test fun verifyGetJSONObjectOrNull() { wheneverGetValid().thenReturn("{\"a\":1}") assertThat(cursor.getJSONObjectOrNull(VALID), jsonEquals(JSONObject(mapOf("a" to 1)))) } @Test fun testGetJSONObjectWhenNullValue() { wheneverGetValid().thenReturn(null) assertNull(cursor.getJSONObjectOrNull(VALID)) } @Test fun verifyGetJSONObjectOrNullWhenInvalidValue() { wheneverGetValid().thenReturn("{\"a\":1") assertNull(cursor.getJSONObjectOrNull(VALID)) } @Test fun verifyGetJSONObjectOrNullWhenNonExistentField() { assertNull(cursor.getJSONObjectOrNull(INVALID)) verify(cursor, never()).getString(any()) } // endregion getJSONObjectOrNull() // region getLong() @Test fun testGetLong() { wheneverGetValid().thenReturn("1") assertEquals(1L, cursor.getLong(VALID)) } @Test fun testGetLongDefaultWhenNullValue() { wheneverGetValid().thenReturn(null) assertNull(cursor.getLong(VALID)) assertEquals(1, cursor.getLong(VALID, 1)) assertNull(cursor.getLong(VALID, null)) } @Test fun testGetLongDefaultWhenInvalidValue() { wheneverGetValid().thenReturn("abcde") assertNull(cursor.getLong(VALID)) assertEquals(1, cursor.getLong(VALID, 1)) assertNull(cursor.getLong(VALID, null)) } @Test fun testGetLongDefaultWhenNonExistentField() { assertNull(cursor.getLong(INVALID)) assertEquals(1, cursor.getLong(INVALID, 1)) assertNull(cursor.getLong(INVALID, null)) verify(cursor, never()).getString(any()) } // endregion getLong() // region getString() @Test fun testGetString() { wheneverGetValid().thenReturn("string") assertEquals("string", cursor.getString(VALID)) } @Test fun testGetStringDefaultWhenNullValue() { wheneverGetValid().thenReturn(null) assertNull(cursor.getString(VALID)) assertEquals("default", cursor.getString(VALID, "default")) assertNull(cursor.getString(VALID, null)) } @Test fun testGetStringDefaultWhenNonExistentField() { assertNull(cursor.getString(INVALID)) assertEquals("default", cursor.getString(INVALID, "default")) assertNull(cursor.getString(INVALID, null)) verify(cursor, never()).getString(any()) } // endregion getString() private fun wheneverGetValid() = whenever(cursor.getString(0)) }
mit
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/handlers/basic/StringFakeConstructor.kt
8
101
fun some() { String<caret> } // ELEMENT: String // TAIL_TEXT: "(bytes: ByteArray) (kotlin.text)"
apache-2.0
WillowChat/Kale
processor/src/main/kotlin/chat/willow/kale/generator/RplGenerator.kt
2
6156
package chat.willow.kale.generator import com.squareup.kotlinpoet.* import java.io.File import javax.annotation.processing.* import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import kotlin.reflect.KClass annotation class SourceTargetContent(val numeric: String) annotation class SourceTargetChannelContent(val numeric: String) class RplGenerator : AbstractProcessor() { override fun getSupportedSourceVersion(): SourceVersion { return SourceVersion.latestSupported() } override fun getSupportedAnnotationTypes(): MutableSet<String> { return mutableSetOf("*") } fun rpl_container(numeric: String, name: String, parent: ClassName, parameters: Iterable<ParameterSpec>): TypeSpec { val message = ClassName.bestGuess("$parent.Message") val parser = ClassName.bestGuess("$parent.Parser") val serialiser = ClassName.bestGuess("$parent.Serialiser") val descriptor = ClassName.bestGuess("$parent.Descriptor") val command = ClassName.bestGuess("ICommand") val messageTypeSpec = TypeSpec .classBuilder("Message") .superclass(message) .primaryConstructor( FunSpec .constructorBuilder() .addParameters(parameters) .build() ) .addSuperclassConstructorParameter(CodeBlock.of(parameters.map { it.name }.joinToString(separator = ", "))) .build() val parserTypeSpec = TypeSpec .objectBuilder("Parser") .superclass(parser) .addSuperclassConstructorParameter(CodeBlock.of("command")) .build() val serialiserTypeSpec = TypeSpec .objectBuilder(serialiser) .superclass(serialiser) .addSuperclassConstructorParameter(CodeBlock.of("command")) .build() val descriptorTypeSpec = TypeSpec .objectBuilder(descriptor) .superclass(descriptor) .addSuperclassConstructorParameter(CodeBlock.of("command, Parser")) .build() return TypeSpec .objectBuilder(name.toUpperCase()) .addSuperinterface(command) .addProperty(PropertySpec .builder("command", String::class, KModifier.OVERRIDE) .initializer(CodeBlock.of("%S", numeric)) .build() ) .addType(messageTypeSpec) .addType(parserTypeSpec) .addType(serialiserTypeSpec) .addType(descriptorTypeSpec) .build() } override fun process(set: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { if (roundEnv.processingOver()) { return true } val kaleNumericsTypeSpec = TypeSpec.objectBuilder("KaleNumerics") generateSourceTargetContent(kaleNumericsTypeSpec, roundEnv) generateSourceTargetChannelContent(kaleNumericsTypeSpec, roundEnv) val kaleNumerics = kaleNumericsTypeSpec.build() val fileSpec = FileSpec.builder("chat.willow.kale.generated", "KaleNumerics") fileSpec.addType(kaleNumerics) fileSpec.addStaticImport("chat.willow.kale.core", "*") val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] fileSpec.build().writeTo(File(kaptKotlinGeneratedDir, "")) return true } fun generateSourceTargetContent(kaleNumericsTypeSpec: TypeSpec.Builder, roundEnv: RoundEnvironment) { val sourceTargetContentsToGenerate = roundEnv.getElementsAnnotatedWith(SourceTargetContent::class.java) sourceTargetContentsToGenerate .forEach { val annotation = it.getAnnotation(SourceTargetContent::class.java)!! val numeric = annotation.numeric val className = it.simpleName.toString() val parent = ClassName.bestGuess("RplSourceTargetContent") val parameters = listOf( ParameterSpec.builder("source", String::class).build(), ParameterSpec.builder("target", String::class).build(), ParameterSpec.builder("content", String::class).build() ) generate(kaleNumericsTypeSpec, numeric, className, parent, parameters) } } fun generateSourceTargetChannelContent(kaleNumericsTypeSpec: TypeSpec.Builder, roundEnv: RoundEnvironment) { val sourceTargetContentsToGenerate = roundEnv.getElementsAnnotatedWith(SourceTargetChannelContent::class.java) sourceTargetContentsToGenerate .forEach { val annotation = it.getAnnotation(SourceTargetChannelContent::class.java)!! val numeric = annotation.numeric val className = it.simpleName.toString() val parent = ClassName.bestGuess("RplSourceTargetChannelContent") val parameters = listOf( ParameterSpec.builder("source", String::class).build(), ParameterSpec.builder("target", String::class).build(), ParameterSpec.builder("channel", String::class).build(), ParameterSpec.builder("content", String::class).build() ) generate(kaleNumericsTypeSpec, numeric, className, parent, parameters) } } fun generate(kaleNumericsTypeSpec: TypeSpec.Builder, numeric: String, className: String, parent: ClassName, parameters: Iterable<ParameterSpec>) { val rplTypeSpec = rpl_container(numeric, className, parent, parameters) kaleNumericsTypeSpec.addType(rplTypeSpec) } companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" } }
isc
magmaOffenburg/RoboViz
src/main/kotlin/org/magmaoffenburg/roboviz/gui/menus/HelpMenu.kt
1
631
package org.magmaoffenburg.roboviz.gui.menus import org.magmaoffenburg.roboviz.gui.windows.config.ConfigWindow import org.magmaoffenburg.roboviz.gui.windows.ControlsHelpWindow import java.awt.event.KeyEvent class HelpMenu : MenuBase() { init { initializeMenu() } private fun initializeMenu() { text = "Help" addItem("Help", KeyEvent.VK_F1) { openHelp() } addItem("Configuration", KeyEvent.VK_F2) { openConfiguration() } } private fun openHelp() { ControlsHelpWindow.showWindow() } private fun openConfiguration() { ConfigWindow.showWindow() } }
apache-2.0
kunalkanojia/tasks-teamcity-plugin
tasks-teamcity-plugin-agent/src/main/kotlin/org/kkanojia/tasks/teamcity/agent/TaskBuildProcessAdapter.kt
1
3824
package org.kkanojia.tasks.teamcity.agent import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.BuildProgressLogger import jetbrains.buildServer.agent.artifacts.ArtifactsWatcher import org.kkanojia.tasks.teamcity.common.InterruptionChecker import org.kkanojia.tasks.teamcity.common.StatusLogger import org.kkanojia.tasks.teamcity.common.TaskBuildRunnerConstants import org.kkanojia.tasks.teamcity.common.TaskScanner import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.util.concurrent.atomic.AtomicReference class TaskBuildProcessAdapter( internal val artifactsWatcher: ArtifactsWatcher, logger: BuildProgressLogger, internal val workingRoot: File, internal val reportingRoot: File, internal val includes: List<String>, internal val excludes: List<String>, internal val minors: List<String>, internal val majors: List<String>, internal val criticals: List<String>, internal val failBuild: Boolean) : AbstractBuildProcessAdapter(logger) { @Throws(RunBuildException::class) override fun runProcess() { try { // initialize working root path val workingRootCanonicalPath = workingRoot.canonicalPath progressLogger.message(String.format("The working root path is [%1\$s].", workingRootCanonicalPath)) val workingRootPath = Paths.get(workingRootCanonicalPath) // initialize reporting root path val reportingRootCanonicalPath = reportingRoot.canonicalPath progressLogger.message(String.format("The reporting root path is [%1\$s].", reportingRootCanonicalPath)) val reportingRootPath = Paths.get(reportingRootCanonicalPath, TaskBuildRunnerConstants.TASK_REPORTING_FOLDER) Files.createDirectory(reportingRootPath) progressLogger.message(String.format("Create directory for reporting [%1\$s].", reportingRootPath)) // initialize the Task Scanner val scanner = TaskScanner( workingRootPath, reportingRootPath, includes, excludes, minors, majors, criticals, 2, 5, failBuild) val scannerException = AtomicReference<Exception>(null) val interruptibleScanner = Runnable { try { scanner.Run( object : InterruptionChecker { override val isInterrupted: Boolean get() = [email protected] }, object : StatusLogger { override fun info(message: String) { progressLogger.message(message) } }) } catch (e: Exception) { progressLogger.error(e.message) scannerException.set(e) } } // run the Task Scanner val scannerThread = Thread(interruptibleScanner) scannerThread.start() scannerThread.join() // register artifacts artifactsWatcher.addNewArtifactsPath(reportingRootPath.toString()) // handle exceptions val innerException = scannerException.get() if (innerException != null) { throw innerException } } catch (e: RunBuildException) { throw e } catch (e: Exception) { throw RunBuildException(e) } } }
mit
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/decompiler/decompiledText/InnerClasses.expected.kt
13
876
// IntelliJ API Decompiler stub source generated from a class file // Implementation of methods is not available package test public final class InnerClasses<E, F> public constructor() { public final fun bar(x: test.InnerClasses<kotlin.String, kotlin.Double>.Inner2, y: test.InnerClasses<E, F>.Inner2): kotlin.Unit { /* compiled code */ } public final inner class Inner<G, H> public constructor() { public final inner class Inner3<I> public constructor() { public final fun foo(x: test.InnerClasses<kotlin.String, F>.Inner<G, kotlin.Int>, y: test.InnerClasses<E, F>.Inner<E, kotlin.Double>, z: test.InnerClasses<kotlin.String, F>.Inner<G, kotlin.Int>.Inner3<kotlin.Double>, w: test.InnerClasses<E, F>.Inner<G, H>.Inner3<*>): kotlin.Unit { /* compiled code */ } } } public final inner class Inner2 public constructor() { } }
apache-2.0
treelzebub/pizarro
app/src/main/java/net/treelzebub/pizarro/activity/FileTreeActivity.kt
1
6782
package net.treelzebub.pizarro.activity import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.NavigationView import android.support.v4.content.ContextCompat import android.support.v4.view.GestureDetectorCompat import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.* import android.widget.Toast import butterknife.bindView import net.treelzebub.kapsule.extensions.TAG import net.treelzebub.pizarro.R import net.treelzebub.pizarro.adapter.FileTreeAdapter import net.treelzebub.pizarro.dialog.NewFolderDialogFragment import net.treelzebub.pizarro.explorer.entities.FileMetadata import net.treelzebub.pizarro.listener.FileTreeOnTouchListener import net.treelzebub.pizarro.presenter.FileTreePresenter import net.treelzebub.pizarro.presenter.FileTreePresenterImpl import net.treelzebub.pizarro.view.FileTreeView import net.treelzebub.pizarro.presenter.PresenterHolder import kotlin.properties.Delegates /** * Created by Tre Murillo on 3/19/16 */ class FileTreeActivity : AppCompatActivity(), FileTreeView, NavigationView.OnNavigationItemSelectedListener, FileTreeOnTouchListener, OnNewFolderListener { private val toolbar: Toolbar by bindView(R.id.toolbar) private val fab: FloatingActionButton by bindView(R.id.fab) private val drawer: DrawerLayout by bindView(R.id.drawer_layout) private val nav: NavigationView by bindView(R.id.nav_view) private val recycler: RecyclerView by bindView(R.id.recycler) private var presenter: FileTreePresenter by Delegates.notNull() private val fileTreeAdapter = FileTreeAdapter() private val gestureDetector by lazy { GestureDetectorCompat(this, RecyclerGestureListener()) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) setupView() setupRecycler() } override fun onResume() { super.onResume() presenter = createPresenter() presenter.create() } override fun onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else if (presenter.canGoBack()) { presenter.onBack() } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.file_tree_activity, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_back -> { presenter.onBack() } } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(bundle: Bundle) { presenter.view = null PresenterHolder.putPresenter(FileTreePresenter::class.java, presenter) } override fun onDestroy() { super.onDestroy() if (isFinishing) { PresenterHolder.remove(FileTreePresenter::class.java) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { when(item.itemId) { //TODO } drawer.closeDrawer(GravityCompat.START) return true } override fun onInterceptTouchEvent(rv: RecyclerView, event: MotionEvent): Boolean { gestureDetector.onTouchEvent(event) return false } override fun setFileTree(treeItems: List<FileMetadata>?) { treeItems ?: return fileTreeAdapter.treeItems = treeItems } override fun onNewFolder(name: String) { val result = if (presenter.mkDir(name)) { presenter.reload() "$name created." } else { "Can't create folder here." } Toast.makeText(this, result, Toast.LENGTH_SHORT).show() } fun createPresenter(): FileTreePresenter { val presenter = PresenterHolder.getPresenter(FileTreePresenter::class.java) ?: FileTreePresenterImpl(this) presenter.view = this return presenter } private fun setupView() { fab.setOnClickListener { NewFolderDialogFragment().apply { listener = this@FileTreeActivity show(supportFragmentManager, TAG) } } val toggle = ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.addDrawerListener(toggle) toggle.syncState() nav.setNavigationItemSelectedListener(this) } private fun setupRecycler() { recycler.apply { itemAnimator = DefaultItemAnimator() layoutManager = LinearLayoutManager(this@FileTreeActivity) addOnItemTouchListener(this@FileTreeActivity) adapter = fileTreeAdapter } } private inner class RecyclerGestureListener: GestureDetector.SimpleOnGestureListener() { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { val view = getViewAtXY(e) ?: return false onClick(view) return super.onSingleTapConfirmed(e) } override fun onLongPress(e: MotionEvent) { val view = getViewAtXY(e) ?: return onLongClick(view) } } private fun getViewAtXY(e: MotionEvent): View? { return recycler.findChildViewUnder(e.x, e.y) } private fun onClick(view: View) { val position = recycler.getChildLayoutPosition(view) val data = fileTreeAdapter.getItem(position) ?: return presenter.changeDirOrOpen(this, data) } private fun onLongClick(view: View) { val position = recycler.getChildLayoutPosition(view) val data = fileTreeAdapter.getItem(position) ?: return AlertDialog.Builder(this) .setIcon(ContextCompat.getDrawable(this, R.drawable.ic_delete)) .setTitle("Delete file?") .setPositiveButton("Yes") { di, which -> presenter.rm(data) } .setNegativeButton("No") { di, which -> di.dismiss() } .show() } } interface OnNewFolderListener { fun onNewFolder(name: String) }
gpl-3.0
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/class/publicClass.kt
56
10
class Test
apache-2.0
dev-cloverlab/Kloveroid
app/src/main/kotlin/com/cloverlab/kloveroid/internal/di/annotations/scopes/Network.kt
1
353
package com.cloverlab.kloveroid.internal.di.annotations.scopes import javax.inject.Scope /** * A scoping annotation to permit objects whose lifetime should depend to the life of the application to be * memorized in the correct component. * * @author Jieyi Wu * @since 2017/06/15 */ @Scope @Retention @MustBeDocumented annotation class Network
mit