repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
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
4d1e1bb0391e4de7b0e57addf68085eb
36.079365
116
0.690497
4.662675
false
false
false
false
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
c7e97f21433e2fb50e45a00d1dab3708
35.147059
114
0.666848
4.908123
false
false
false
false
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
a4ca6c4df63cdd2cf9f51f22257de51a
37.673203
175
0.687443
5.32967
false
false
false
false
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
4e47f3e4c804cfc32a84bdf2d2dd1cae
41.945736
140
0.727749
4.470541
false
false
false
false
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
e1231c4c661a7bee16662fe8bedeffa8
34.263158
158
0.748259
4.407895
false
false
false
false
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
1a53e61331f9d0388c3687917a41e6e4
35.044118
97
0.748674
4.408273
false
false
false
false
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
9610b13172c98b12dc1f21383916eb3e
42.291085
163
0.613388
5.562241
false
true
false
false
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
a09609f7cb1306a89058cdac1e7157af
42.438202
140
0.664166
4.759852
false
true
false
false
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
2e819585164c2bc3416a614b50357e0a
45.467532
124
0.738887
5.444444
false
false
false
false
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
e66f7174a56fa882563da41da5cd7230
38.014563
158
0.731832
4.936118
false
false
false
false
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
aca3f0a868231721081af7266392a6f0
36.021622
143
0.716309
4.547809
false
false
false
false
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
9953e12ca80f50bbb1c2e325741472a7
32.066667
70
0.748739
3.93254
false
false
false
false
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
f430dd3e2a1ded08669b0308c605fab2
32.111111
100
0.647651
3.415473
false
false
false
false
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
1172d62022465295f35fd0cec0c7653b
40.962264
148
0.679257
4.674451
false
false
false
false
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
0a7e1edeb1f799e993721c6fea8868d1
36.723404
147
0.722927
5.280715
false
true
false
false
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
a09a4b9e2415695d3a2b14c2cb190525
37.464286
146
0.732296
4.707104
false
false
false
false
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
abf16a9d3de62bd73fdfb255b5b512dc
15.133333
36
0.497925
3.492754
false
false
false
false
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
7f1f3811468f7466c406a35d3dfb83fc
37.287234
122
0.729647
5.012535
false
false
false
false
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
644ea50977a4486a1a153ced80ce052d
26.428571
101
0.647979
3.669856
false
false
false
false
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
bba97a68c63efa21d4ce625f8d792633
31.12766
140
0.696588
4.30057
false
false
false
false
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
8548474cd1a919da4c6de8a3077cef0f
37.010638
158
0.656311
4.969402
false
false
false
false
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
2b2f3ff15da762aeb88cc6c89aab794e
35.455446
140
0.743548
4.467233
false
false
false
false
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
3bcb72e8eae0a9e32a70ac3990f029a7
51.933333
158
0.798489
4.783133
false
false
false
false
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
cc0fb51ee31702cef8a67264b0b306b5
40.884354
150
0.614035
5.616788
false
false
false
false
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
faf3585bbbc476a20e61f302ed53887a
40.11828
121
0.592835
5.550073
false
false
false
false
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
3823ff9dcb5025235c93c525a1fd6f5e
33.080402
108
0.672958
4.861649
false
false
false
false
ozbek/quran_android
app/src/warsh/java/com/quran/labs/androidquran/data/QuranFileConstants.kt
2
685
package com.quran.labs.androidquran.data import com.quran.labs.androidquran.ui.util.TypefaceManager import com.quran.labs.androidquran.database.DatabaseHandler object QuranFileConstants { // server urls const val FONT_TYPE = TypefaceManager.TYPE_UTHMANIC_WARSH // arabic database const val ARABIC_DATABASE = "quran.ar.warsh.db" const val ARABIC_SHARE_TABLE = DatabaseHandler.ARABIC_TEXT_TABLE const val ARABIC_SHARE_TEXT_HAS_BASMALLAH = true const val FETCH_QUARTER_NAMES_FROM_DATABASE = true const val FALLBACK_PAGE_TYPE = "warsh" const val SEARCH_EXTRA_REPLACEMENTS = "\u0626" var ICON_RESOURCE_ID = com.quran.labs.androidquran.pages.warsh.R.drawable.icon }
gpl-3.0
ecc3f7467691545afe01658af77af40e
33.25
80
0.779562
3.549223
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/DocumentationResultData.kt
8
1555
// 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.lang.documentation import com.intellij.lang.documentation.DocumentationResult.Data import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import org.jetbrains.annotations.VisibleForTesting import java.awt.Image @VisibleForTesting data class DocumentationResultData internal constructor( internal val content: DocumentationContentData, internal val links: LinkData = LinkData(), val anchor: String? = null, internal val updates: Flow<DocumentationContentData> = emptyFlow(), ) : Data { val html: String get() = content.html override fun html(html: String): Data { return content(content.copy(html = html)) } override fun images(images: Map<String, Image>): Data { return content(content.copy(imageResolver = imageResolver(images))) } override fun content(content: DocumentationContent): Data { return copy(content = content as DocumentationContentData) } override fun anchor(anchor: String?): Data { return copy(anchor = anchor) } override fun externalUrl(externalUrl: String?): Data { return copy(links = links.copy(externalUrl = externalUrl)) } override fun updates(updates: Flow<DocumentationContent>): Data { @Suppress("UNCHECKED_CAST") return copy(updates = updates as Flow<DocumentationContentData>) } override fun updates(updater: DocumentationContentUpdater): Data { return updates(updater.asFlow()) } }
apache-2.0
4f42c98968637c28638ef09fe796114c
31.395833
120
0.754984
4.417614
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/JpsIncrementalCache.kt
1
2747
// 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.jps.incremental import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.jps.builders.storage.StorageProvider import org.jetbrains.jps.incremental.ModuleBuildTarget import org.jetbrains.jps.incremental.storage.BuildDataManager import org.jetbrains.jps.incremental.storage.StorageOwner import org.jetbrains.kotlin.incremental.IncrementalCacheCommon import org.jetbrains.kotlin.incremental.IncrementalJsCache import org.jetbrains.kotlin.incremental.IncrementalJvmCache import org.jetbrains.kotlin.incremental.storage.FileToPathConverter import org.jetbrains.kotlin.jps.build.KotlinBuilder import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol import java.io.File interface JpsIncrementalCache : IncrementalCacheCommon, StorageOwner { fun addJpsDependentCache(cache: JpsIncrementalCache) } class JpsIncrementalJvmCache( target: ModuleBuildTarget, paths: BuildDataPaths, pathConverter: FileToPathConverter ) : IncrementalJvmCache(paths.getTargetDataRoot(target), target.outputDir, pathConverter), JpsIncrementalCache { override fun addJpsDependentCache(cache: JpsIncrementalCache) { if (cache is JpsIncrementalJvmCache) { addDependentCache(cache) } } override fun debugLog(message: String) { KotlinBuilder.LOG.debug(message) } } class JpsIncrementalJsCache( target: ModuleBuildTarget, paths: BuildDataPaths, pathConverter: FileToPathConverter ) : IncrementalJsCache(paths.getTargetDataRoot(target), pathConverter, JsSerializerProtocol), JpsIncrementalCache { override fun addJpsDependentCache(cache: JpsIncrementalCache) { if (cache is JpsIncrementalJsCache) { addDependentCache(cache) } } } private class KotlinIncrementalStorageProvider( private val target: KotlinModuleBuildTarget<*>, private val paths: BuildDataPaths ) : StorageProvider<JpsIncrementalCache>() { init { check(target.hasCaches) } override fun equals(other: Any?) = other is KotlinIncrementalStorageProvider && target == other.target override fun hashCode() = target.hashCode() override fun createStorage(targetDataDir: File): JpsIncrementalCache = target.createCacheStorage(paths) } fun BuildDataManager.getKotlinCache(target: KotlinModuleBuildTarget<*>?): JpsIncrementalCache? = if (target == null || !target.hasCaches) null else getStorage(target.jpsModuleBuildTarget, KotlinIncrementalStorageProvider(target, dataPaths))
apache-2.0
2015cff759c176af017aff511beea922
38.811594
158
0.789589
4.624579
false
false
false
false
jwren/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginModelValidator.kt
1
24377
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonGenerator import com.intellij.openapi.application.PathManager.getHomePath import com.intellij.util.getErrorsAsString import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.xml.dom.XmlElement import com.intellij.util.xml.dom.readXmlAsModel import java.io.StringWriter import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.* import kotlin.io.path.div private val emptyPath by lazy { Path.of("/") } internal val homePath by lazy { Path.of(getHomePath()) } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val moduleSkipList = java.util.Set.of( "fleet", "intellij.indexing.shared.ultimate.plugin.internal.generator", "intellij.indexing.shared.ultimate.plugin.public", "kotlin-ultimate.appcode-kmm.main", /* Used only when running from sources */ "intellij.javaFX.community", "intellij.lightEdit", "intellij.webstorm", "intellij.cwm.plugin", /* platform/cwm-plugin/resources/META-INF/plugin.xml doesn't have `id` - ignore for now */ "intellij.osgi", /* no particular package prefix to choose */ "intellij.hunspell", /* MP-3656 Marketplace doesn't allow uploading plugins without dependencies */ "kotlin.resources-fir", /* Kotlin FIR IDE Plugin has the same plugin id as the plain Kotlin plugin */ ) class PluginModelValidator(sourceModules: List<Module>) { interface Module { val name: String val sourceRoots: List<Path> } private val pluginIdToInfo = LinkedHashMap<String, ModuleInfo>() private val _errors = mutableListOf<Throwable>() val errors: List<Throwable> get() = java.util.List.copyOf(_errors) val errorsAsString: CharSequence get() = if (_errors.isEmpty()) "" else getErrorsAsString(_errors, includeStackTrace = false) init { // 1. collect plugin and module file info set val sourceModuleNameToFileInfo = sourceModules.associate { it.name to ModuleDescriptorFileInfo(it) } for (module in sourceModules) { val moduleName = module.name if (moduleName.startsWith("fleet.") || moduleSkipList.contains(moduleName)) { continue } for (sourceRoot in module.sourceRoots) { updateFileInfo( moduleName, sourceRoot, sourceModuleNameToFileInfo[moduleName]!! ) } } val moduleNameToInfo = HashMap<String, ModuleInfo>() // 2. process plugins - process content to collect modules for ((sourceModuleName, moduleMetaInfo) in sourceModuleNameToFileInfo) { // interested only in plugins val descriptor = moduleMetaInfo.pluginDescriptor ?: continue val descriptorFile = moduleMetaInfo.pluginDescriptorFile ?: continue val id = descriptor.getChild("id")?.content ?: descriptor.getChild("name")?.content if (id == null) { _errors.add(PluginValidationError( "Plugin id is not specified", mapOf( "descriptorFile" to descriptorFile ), )) continue } val moduleInfo = ModuleInfo(pluginId = id, name = null, sourceModuleName = sourceModuleName, descriptorFile = descriptorFile, packageName = descriptor.getAttributeValue("package"), descriptor = descriptor) val prev = pluginIdToInfo.put(id, moduleInfo) if (prev != null) { throw PluginValidationError( "Duplicated plugin id: $id", mapOf( "prev" to prev, "current" to moduleInfo, ), ) } descriptor.getChild("content")?.let { contentElement -> checkContent(content = contentElement, referencingModuleInfo = moduleInfo, sourceModuleNameToFileInfo = sourceModuleNameToFileInfo, moduleNameToInfo = moduleNameToInfo) } } // 3. check dependencies - we are aware about all modules now for (pluginInfo in pluginIdToInfo.values) { val descriptor = pluginInfo.descriptor val dependenciesElements = descriptor.children("dependencies").toList() if (dependenciesElements.size > 1) { _errors.add(PluginValidationError( "The only `dependencies` tag is expected", mapOf( "descriptorFile" to pluginInfo.descriptorFile, ), )) } else if (dependenciesElements.size == 1) { checkDependencies(dependenciesElements.first(), pluginInfo, pluginInfo, moduleNameToInfo, sourceModuleNameToFileInfo) } // in the end after processing content and dependencies if (pluginInfo.packageName == null && hasContentOrDependenciesInV2Format(descriptor)) { // some plugins cannot be yet fully migrated val error = PluginValidationError( "Plugin ${pluginInfo.pluginId} is not fully migrated: package is not specified", mapOf( "pluginId" to pluginInfo.pluginId, "descriptor" to pluginInfo.descriptorFile, ), ) System.err.println(error.message) } if (pluginInfo.packageName != null) { descriptor.children.firstOrNull { it.name == "depends" && it.getAttributeValue("optional") == null }?.let { _errors.add(PluginValidationError( "The old format should not be used for a plugin with the specified package prefix, but `depends` tag is used." + " Please use the new format (see https://github.com/JetBrains/intellij-community/blob/master/docs/plugin.md#the-dependencies-element)", mapOf( "descriptorFile" to pluginInfo.descriptorFile, "depends" to it, ), )) } } for (contentModuleInfo in pluginInfo.content) { contentModuleInfo.descriptor.getChild("dependencies")?.let { dependencies -> checkDependencies(dependencies, contentModuleInfo, pluginInfo, moduleNameToInfo, sourceModuleNameToFileInfo) } contentModuleInfo.descriptor.getChild("depends")?.let { _errors.add(PluginValidationError( "Old format must be not used for a module but `depends` tag is used", mapOf( "descriptorFile" to contentModuleInfo.descriptorFile, "depends" to it, ), )) } } } } fun graphAsString(): CharSequence { val stringWriter = StringWriter() val writer = JsonFactory().createGenerator(stringWriter) writer.useDefaultPrettyPrinter() writer.use { writer.obj { val entries = pluginIdToInfo.entries.toMutableList() entries.sortBy { it.value.sourceModuleName } for (entry in entries) { val item = entry.value if (item.packageName == null && !hasContentOrDependenciesInV2Format(item.descriptor)) { continue } writer.writeFieldName(item.sourceModuleName) writeModuleInfo(writer, item) } } } return stringWriter.buffer } fun writeGraph(outFile: Path) { PluginGraphWriter(pluginIdToInfo).write(outFile) } private fun checkDependencies(element: XmlElement, referencingModuleInfo: ModuleInfo, referencingPluginInfo: ModuleInfo, moduleNameToInfo: Map<String, ModuleInfo>, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>) { if (referencingModuleInfo.packageName == null && !knownNotFullyMigratedPluginIds.contains(referencingModuleInfo.pluginId)) { _errors.add(PluginValidationError( "`dependencies` must be specified only for plugin in a new format: package prefix is not specified", mapOf( "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ))) } for (child in element.children) { fun getErrorInfo(): Map<String, Any?> { return mapOf( "entry" to child, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ) } if (child.name != "module") { if (child.name == "plugin") { // todo check that the referenced plugin exists val id = child.getAttributeValue("id") if (id == null) { _errors.add(PluginValidationError( "Id is not specified for dependency on plugin", getErrorInfo(), )) continue } if (id == "com.intellij.modules.java") { _errors.add(PluginValidationError( "Use com.intellij.java id instead of com.intellij.modules.java", getErrorInfo(), )) continue } if (id == "com.intellij.modules.platform") { _errors.add(PluginValidationError( "No need to specify dependency on $id", getErrorInfo(), )) continue } if (id == referencingPluginInfo.pluginId) { _errors.add(PluginValidationError( "Do not add dependency on a parent plugin", getErrorInfo(), )) continue } val dependency = pluginIdToInfo[id] if (!id.startsWith("com.intellij.modules.") && dependency == null) { _errors.add(PluginValidationError( "Plugin not found: $id", getErrorInfo(), )) continue } val ref = Reference( name = id, isPlugin = true, moduleInfo = dependency ?: ModuleInfo(null, id, "", emptyPath, null, XmlElement("", Collections.emptyMap(), Collections.emptyList(), null)) ) if (referencingModuleInfo.dependencies.contains(ref)) { _errors.add(PluginValidationError( "Referencing module dependencies contains $id: $id", getErrorInfo(), )) continue } referencingModuleInfo.dependencies.add(ref) continue } if (referencingModuleInfo.isPlugin) { _errors.add(PluginValidationError( "Unsupported dependency type: ${child.name}", getErrorInfo(), )) continue } } val moduleName = child.getAttributeValue("name") if (moduleName == null) { _errors.add(PluginValidationError( "Module name is not specified", getErrorInfo(), )) continue } if (moduleName == "intellij.platform.commercial.verifier") { continue } if (child.attributes.size > 1) { _errors.add(PluginValidationError( "Unknown attributes: ${child.attributes.entries.filter { it.key != "name" }}", getErrorInfo(), )) continue } val moduleInfo = moduleNameToInfo[moduleName] if (moduleInfo == null) { val moduleDescriptorFileInfo = sourceModuleNameToFileInfo[moduleName] if (moduleDescriptorFileInfo != null) { if (moduleDescriptorFileInfo.pluginDescriptor != null) { _errors.add(PluginValidationError( message = "Dependency on plugin must be specified using `plugin` and not `module`", params = getErrorInfo(), fix = """ Change dependency element to: <plugin id="${moduleDescriptorFileInfo.pluginDescriptor!!.getChild("id")?.content}"/> """, )) continue } } _errors.add(PluginValidationError("Module not found: $moduleName", getErrorInfo())) continue } referencingModuleInfo.dependencies.add(Reference(moduleName, isPlugin = false, moduleInfo)) for (dependsElement in referencingModuleInfo.descriptor.children) { if (dependsElement.name != "depends") { continue } if (dependsElement.getAttributeValue("config-file")?.removePrefix("/META-INF/") == moduleInfo.descriptorFile.fileName.toString()) { _errors.add(PluginValidationError( "Module, that used as dependency, must be not specified in `depends`", getErrorInfo(), )) break } } } } // for plugin two variants: // 1) depends + dependency on plugin in a referenced descriptor = optional descriptor. In old format: depends tag // 2) no depends + no dependency on plugin in a referenced descriptor = directly injected into plugin (separate classloader is not created // during transition period). In old format: xi:include (e.g. <xi:include href="dockerfile-language.xml"/>). private fun checkContent(content: XmlElement, referencingModuleInfo: ModuleInfo, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>, moduleNameToInfo: MutableMap<String, ModuleInfo>) { for (child in content.children) { fun getErrorInfo(): Map<String, Any> { return mapOf( "entry" to child, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ) } if (child.name != "module") { _errors.add(PluginValidationError( "Unexpected element: $child", getErrorInfo(), )) continue } val moduleName = child.getAttributeValue("name") if (moduleName == null) { _errors.add(PluginValidationError( "Module name is not specified", getErrorInfo(), )) continue } if (child.attributes.size > 1) { _errors.add(PluginValidationError( "Unknown attributes: ${child.attributes.entries.filter { it.key != "name" }}", getErrorInfo(), )) continue } if (moduleName == "intellij.platform.commercial.verifier") { _errors.add(PluginValidationError( "intellij.platform.commercial.verifier is not supposed to be used as content of plugin", getErrorInfo(), )) continue } // ignore null - getModule reports error val moduleDescriptorFileInfo = getModuleDescriptorFileInfo(moduleName, referencingModuleInfo, sourceModuleNameToFileInfo) ?: continue val moduleDescriptor = moduleDescriptorFileInfo.moduleDescriptor!! val packageName = moduleDescriptor.getAttributeValue("package") if (packageName == null) { _errors.add(PluginValidationError( "Module package is not specified", mapOf( "descriptorFile" to moduleDescriptorFileInfo.moduleDescriptorFile!!, ), )) continue } val moduleInfo = ModuleInfo(pluginId = null, name = moduleName, sourceModuleName = moduleDescriptorFileInfo.sourceModule.name, descriptorFile = moduleDescriptorFileInfo.moduleDescriptorFile!!, packageName = packageName, descriptor = moduleDescriptor) moduleNameToInfo[moduleName] = moduleInfo referencingModuleInfo.content.add(moduleInfo) @Suppress("GrazieInspection") // check that not specified using `depends` tag for (dependsElement in referencingModuleInfo.descriptor.children) { if (dependsElement.name != "depends") { continue } if (dependsElement.getAttributeValue("config-file")?.removePrefix("/META-INF/") == moduleInfo.descriptorFile.fileName.toString()) { _errors.add(PluginValidationError( "Module must be not specified in `depends`.", getErrorInfo() + mapOf( "referencedDescriptorFile" to moduleInfo.descriptorFile ), )) continue } } moduleDescriptor.getChild("content")?.let { _errors.add(PluginValidationError( "Module cannot define content", getErrorInfo() + mapOf( "referencedDescriptorFile" to moduleInfo.descriptorFile ), )) } } } private fun getModuleDescriptorFileInfo(moduleName: String, referencingModuleInfo: ModuleInfo, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>): ModuleDescriptorFileInfo? { var module = sourceModuleNameToFileInfo[moduleName] if (module != null) { return module } fun getErrorInfo(): Map<String, Path> { return mapOf( "referencingDescriptorFile" to referencingModuleInfo.descriptorFile ) } val prefix = referencingModuleInfo.sourceModuleName + "/" if (!moduleName.startsWith(prefix)) { _errors.add(PluginValidationError( "Cannot find module $moduleName", getErrorInfo(), )) return null } val slashIndex = prefix.length - 1 val containingModuleName = moduleName.substring(0, slashIndex) module = sourceModuleNameToFileInfo[containingModuleName] if (module == null) { _errors.add(PluginValidationError( "Cannot find module $containingModuleName", getErrorInfo(), )) return null } val fileName = "$containingModuleName.${moduleName.substring(slashIndex + 1)}.xml" val result = loadFileInModule(sourceModule = module.sourceModule, fileName = fileName) if (result == null) { _errors.add(PluginValidationError( message = "Module ${module.sourceModule.name} doesn't have descriptor file", params = mapOf( "expectedFile" to fileName, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ), fix = """ Create file $fileName in ${pathToShortString(module.sourceModule.sourceRoots.first())} with content: <idea-plugin package="REPLACE_BY_MODULE_PACKAGE"> </idea-plugin> """ )) } return result } private fun updateFileInfo( moduleName: String, sourceRoot: Path, fileInfo: ModuleDescriptorFileInfo, ) { val metaInf = sourceRoot / "META-INF" val moduleXml = metaInf / "$moduleName.xml" if (Files.exists(moduleXml)) { _errors.add(PluginValidationError( "Module descriptor must be in the root of module root", mapOf( "module" to moduleName, "moduleDescriptor" to moduleXml, ), )) return } val pluginDescriptorFile = metaInf / "plugin.xml" val pluginDescriptor = pluginDescriptorFile.readXmlAsModel() val moduleDescriptorFile = sourceRoot / "$moduleName.xml" val moduleDescriptor = moduleDescriptorFile.readXmlAsModel() if (pluginDescriptor == null && moduleDescriptor == null) { return } if (fileInfo.pluginDescriptorFile != null && pluginDescriptor != null) { _errors.add(PluginValidationError( "Duplicated plugin.xml", mapOf( "module" to moduleName, "firstPluginDescriptor" to fileInfo.pluginDescriptorFile, "secondPluginDescriptor" to pluginDescriptorFile, ), )) return } if (fileInfo.pluginDescriptorFile != null) { _errors.add(PluginValidationError( "Module cannot have both plugin.xml and module descriptor", mapOf( "module" to moduleName, "pluginDescriptor" to fileInfo.pluginDescriptorFile, "moduleDescriptor" to moduleDescriptorFile, ), )) return } if (fileInfo.moduleDescriptorFile != null && pluginDescriptor != null) { _errors.add(PluginValidationError( "Module cannot have both plugin.xml and module descriptor", mapOf( "module" to moduleName, "pluginDescriptor" to pluginDescriptorFile, "moduleDescriptor" to fileInfo.moduleDescriptorFile, ), )) return } if (pluginDescriptor == null) { fileInfo.moduleDescriptorFile = moduleDescriptorFile fileInfo.moduleDescriptor = moduleDescriptor } else { fileInfo.pluginDescriptorFile = pluginDescriptorFile fileInfo.pluginDescriptor = pluginDescriptor } } } internal data class ModuleInfo( val pluginId: String?, val name: String?, val sourceModuleName: String, val descriptorFile: Path, val packageName: String?, val descriptor: XmlElement, ) { val content = mutableListOf<ModuleInfo>() val dependencies = mutableListOf<Reference>() val isPlugin: Boolean get() = pluginId != null } internal data class Reference(val name: String, val isPlugin: Boolean, val moduleInfo: ModuleInfo) private data class PluginInfo(val pluginId: String, val sourceModuleName: String, val descriptor: XmlElement, val descriptorFile: Path) private class ModuleDescriptorFileInfo(val sourceModule: PluginModelValidator.Module) { var pluginDescriptorFile: Path? = null var moduleDescriptorFile: Path? = null var pluginDescriptor: XmlElement? = null var moduleDescriptor: XmlElement? = null } private fun writeModuleInfo(writer: JsonGenerator, item: ModuleInfo) { writer.obj { writer.writeStringField("name", item.name ?: item.sourceModuleName) writer.writeStringField("package", item.packageName) writer.writeStringField("descriptor", pathToShortString(item.descriptorFile)) if (!item.content.isEmpty()) { writer.array("content") { for (child in item.content) { writeModuleInfo(writer, child) } } } if (!item.dependencies.isEmpty()) { writer.array("dependencies") { writeDependencies(item.dependencies, writer) } } } } internal fun pathToShortString(file: Path): String { return when { file === emptyPath -> "" homePath.fileSystem === file.fileSystem -> homePath.relativize(file).toString() else -> file.toString() } } private fun writeDependencies(items: List<Reference>, writer: JsonGenerator) { for (entry in items) { writer.obj { writer.writeStringField(if (entry.isPlugin) "plugin" else "module", entry.name) } } } private class PluginValidationError private constructor(message: String) : RuntimeException(message) { constructor( message: String, params: Map<String, Any?> = mapOf(), fix: String? = null, ) : this( params.entries.joinToString( prefix = "$message (\n ", separator = ",\n ", postfix = "\n)" + (fix?.let { "\n\nProposed fix:\n\n" + fix.trimIndent() + "\n\n" } ?: "") ) { it.key + "=" + paramValueToString(it.value) } ) } private fun paramValueToString(value: Any?): String { return when (value) { is Path -> pathToShortString(value) else -> value.toString() } } private fun loadFileInModule(sourceModule: PluginModelValidator.Module, fileName: String): ModuleDescriptorFileInfo? { for (sourceRoot in sourceModule.sourceRoots) { val moduleDescriptorFile = sourceRoot / fileName val moduleDescriptor = moduleDescriptorFile.readXmlAsModel() if (moduleDescriptor != null) { return ModuleDescriptorFileInfo(sourceModule).also { it.moduleDescriptor = moduleDescriptor it.moduleDescriptorFile = moduleDescriptorFile } } } return null } private fun Path.readXmlAsModel(): XmlElement? { return try { Files.newInputStream(this).use(::readXmlAsModel) } catch (ignore: NoSuchFileException) { null } } internal fun hasContentOrDependenciesInV2Format(descriptor: XmlElement): Boolean { return descriptor.children.any { it.name == "content" || it.name == "dependencies" } }
apache-2.0
99f13487d1ea4ef2cf63843c0e8df605
33.190743
147
0.621036
5.038652
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt
2
2118
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.calls.util.getType private fun KtStringTemplateExpression.singleExpressionOrNull() = children.singleOrNull()?.children?.firstOrNull() as? KtExpression class RemoveSingleExpressionStringTemplateInspection : IntentionBasedInspection<KtStringTemplateExpression>( RemoveSingleExpressionStringTemplateIntention::class, additionalChecker = { templateExpression -> templateExpression.singleExpressionOrNull()?.let { KotlinBuiltIns.isString(it.getType(it.analyze())) } ?: false } ) { override val problemText = KotlinBundle.message("redundant.string.template") } class RemoveSingleExpressionStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("remove.single.expression.string.template") ) { override fun isApplicableTo(element: KtStringTemplateExpression) = element.singleExpressionOrNull() != null override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val expression = element.singleExpressionOrNull() ?: return val type = expression.getType(expression.analyze()) val newElement = if (KotlinBuiltIns.isString(type)) expression else KtPsiFactory(element).createExpressionByPattern("$0.$1()", expression, "toString") element.replace(newElement) } }
apache-2.0
2b4dc9a6083b06ee170dda2e0b41b3d2
46.088889
158
0.788008
5.295
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/rw/cancellableReadAction.kt
1
1891
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems") // KTIJ-19938 package com.intellij.openapi.application.rw import com.intellij.openapi.application.ReadAction.CannotReadException import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.progress.ensureCurrentJob import com.intellij.openapi.progress.executeWithJobAndCompleteIt import com.intellij.openapi.progress.util.ProgressIndicatorUtils.runActionAndCancelBeforeWrite import kotlinx.coroutines.Job import kotlinx.coroutines.ensureActive import kotlin.coroutines.cancellation.CancellationException internal fun <X> cancellableReadAction(action: () -> X): X = ensureCurrentJob { currentJob -> try { cancellableReadActionInternal(currentJob, action) } catch (e: CancellationException) { throw e.cause as? CannotReadException // cancelled normally by a write action ?: e // exception from the computation } } internal fun <X> cancellableReadActionInternal(currentJob: Job, action: () -> X): X { // A child Job is started to be externally cancellable by a write action without cancelling the current Job. val readJob = Job(parent = currentJob) var resultRef: Value<X>? = null val application = ApplicationManagerEx.getApplicationEx() runActionAndCancelBeforeWrite(application, readJob::cancelReadJob) { readJob.ensureActive() application.tryRunReadAction { readJob.ensureActive() resultRef = Value(executeWithJobAndCompleteIt(readJob, action)) } } val result = resultRef if (result == null) { readJob.ensureActive() error("read job must've been cancelled") } return result.value } private fun Job.cancelReadJob() { cancel(cause = CancellationException(CannotReadException())) } private class Value<T>(val value: T)
apache-2.0
fa3fa9d958cdb661a1a72ba5697cda46
37.591837
120
0.773136
4.367206
false
false
false
false
stoyicker/dinger
app/src/main/kotlin/app/home/seen/SeenFragment.kt
1
1771
package app.home.seen import android.arch.lifecycle.Observer import android.arch.paging.PagedList import android.arch.paging.PagedListAdapter import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import domain.recommendation.DomainRecommendationUser import domain.seen.SeenRecommendationsViewModel import org.stoyicker.dinger.R import javax.inject.Inject internal class SeenFragment : Fragment() { @Inject lateinit var viewModel: SeenRecommendationsViewModel @Inject lateinit var observer: Observer<PagedList<DomainRecommendationUser>> @Inject lateinit var seenAdapter: PagedListAdapter<DomainRecommendationUser, SeenRecommendationViewHolder> @Inject lateinit var layoutManager: RecyclerView.LayoutManager override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_seen, parent, false)!! override fun onAttach(context: Context?) { super.onAttach(context) if (context != null) { inject(context) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.filter() .observe(this@SeenFragment, observer) (view as RecyclerView).apply { adapter = seenAdapter layoutManager = [email protected] } } private fun inject(context: Context) = DaggerSeenComponent.builder() .fragment(this) .context(context) .build() .inject(this) companion object { fun newInstance() = SeenFragment() } }
mit
89211d934105605aa51f932f14e52600
29.016949
100
0.733484
4.685185
false
false
false
false
gorrotowi/BitsoPriceChecker
app/src/main/java/com/chilangolabs/bitsopricechecker/models/ItemCoin.kt
1
527
package com.chilangolabs.bitsopricechecker.models import android.support.annotation.DrawableRes /** * @author Gorro * @since 14/06/17 */ data class ItemCoin(val coin: String? = "BTC", val value: String? = "42000", val currency: String? = "MXN", val min: String? = "40200", val max: String? = "42024", val ask: String? = "2134", val bid: String? = "23413", @DrawableRes val bg: Int?)
apache-2.0
003ba6ee7d486064e8ba3bf67b8ef260
32
50
0.504744
4.18254
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ContentRootEntityImpl.kt
2
21236
// 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.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ContentRootEntityImpl(val dataSource: ContentRootEntityData) : ContentRootEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val EXCLUDEDURLS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, ExcludeUrlEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val SOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val SOURCEROOTORDER_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootOrderEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, EXCLUDEDURLS_CONNECTION_ID, SOURCEROOTS_CONNECTION_ID, SOURCEROOTORDER_CONNECTION_ID, ) } override val module: ModuleEntity get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!! override val url: VirtualFileUrl get() = dataSource.url override val excludedUrls: List<ExcludeUrlEntity> get() = snapshot.extractOneToManyChildren<ExcludeUrlEntity>(EXCLUDEDURLS_CONNECTION_ID, this)!!.toList() override val excludedPatterns: List<String> get() = dataSource.excludedPatterns override val sourceRoots: List<SourceRootEntity> get() = snapshot.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() override val sourceRootOrder: SourceRootOrderEntity? get() = snapshot.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ContentRootEntityData?) : ModifiableWorkspaceEntityBase<ContentRootEntity, ContentRootEntityData>( result), ContentRootEntity.Builder { constructor() : this(ContentRootEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ContentRootEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null index(this, "url", this.url) // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field ContentRootEntity#module should be initialized") } } if (!getEntityData().isUrlInitialized()) { error("Field ContentRootEntity#url should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(EXCLUDEDURLS_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#excludedUrls should be initialized") } } else { if (this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] == null) { error("Field ContentRootEntity#excludedUrls should be initialized") } } if (!getEntityData().isExcludedPatternsInitialized()) { error("Field ContentRootEntity#excludedPatterns should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(SOURCEROOTS_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#sourceRoots should be initialized") } } else { if (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] == null) { error("Field ContentRootEntity#sourceRoots should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_excludedPatterns = getEntityData().excludedPatterns if (collection_excludedPatterns is MutableWorkspaceList<*>) { collection_excludedPatterns.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ContentRootEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.url != dataSource.url) this.url = dataSource.url if (this.excludedPatterns != dataSource.excludedPatterns) this.excludedPatterns = dataSource.excludedPatterns.toMutableList() if (parents != null) { val moduleNew = parents.filterIsInstance<ModuleEntity>().single() if ((this.module as WorkspaceEntityBase).id != (moduleNew as WorkspaceEntityBase).id) { this.module = moduleNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var module: ModuleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var url: VirtualFileUrl get() = getEntityData().url set(value) { checkModificationAllowed() getEntityData(true).url = value changedProperty.add("url") val _diff = diff if (_diff != null) index(this, "url", value) } // List of non-abstract referenced types var _excludedUrls: List<ExcludeUrlEntity>? = emptyList() override var excludedUrls: List<ExcludeUrlEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<ExcludeUrlEntity>(EXCLUDEDURLS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] as? List<ExcludeUrlEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] as? List<ExcludeUrlEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) { // Backref setup before adding to store if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, EXCLUDEDURLS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(EXCLUDEDURLS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, EXCLUDEDURLS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] = value } changedProperty.add("excludedUrls") } private val excludedPatternsUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("excludedPatterns") } override var excludedPatterns: MutableList<String> get() { val collection_excludedPatterns = getEntityData().excludedPatterns if (collection_excludedPatterns !is MutableWorkspaceList) return collection_excludedPatterns if (diff == null || modifiable.get()) { collection_excludedPatterns.setModificationUpdateAction(excludedPatternsUpdater) } else { collection_excludedPatterns.cleanModificationUpdateAction() } return collection_excludedPatterns } set(value) { checkModificationAllowed() getEntityData(true).excludedPatterns = value excludedPatternsUpdater.invoke(value) } // List of non-abstract referenced types var _sourceRoots: List<SourceRootEntity>? = emptyList() override var sourceRoots: List<SourceRootEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) { // Backref setup before adding to store if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(SOURCEROOTS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] = value } changedProperty.add("sourceRoots") } override var sourceRootOrder: SourceRootOrderEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity } else { this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneChildOfParent(SOURCEROOTORDER_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] = value } changedProperty.add("sourceRootOrder") } override fun getEntityClass(): Class<ContentRootEntity> = ContentRootEntity::class.java } } class ContentRootEntityData : WorkspaceEntityData<ContentRootEntity>() { lateinit var url: VirtualFileUrl lateinit var excludedPatterns: MutableList<String> fun isUrlInitialized(): Boolean = ::url.isInitialized fun isExcludedPatternsInitialized(): Boolean = ::excludedPatterns.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ContentRootEntity> { val modifiable = ContentRootEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ContentRootEntity { return getCached(snapshot) { val entity = ContentRootEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): ContentRootEntityData { val clonedEntity = super.clone() clonedEntity as ContentRootEntityData clonedEntity.excludedPatterns = clonedEntity.excludedPatterns.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ContentRootEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ContentRootEntity(url, excludedPatterns, entitySource) { this.module = parents.filterIsInstance<ModuleEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ModuleEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.entitySource != other.entitySource) return false if (this.url != other.url) return false if (this.excludedPatterns != other.excludedPatterns) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.url != other.url) return false if (this.excludedPatterns != other.excludedPatterns) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + url.hashCode() result = 31 * result + excludedPatterns.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + url.hashCode() result = 31 * result + excludedPatterns.hashCode() return result } override fun equalsByKey(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.url != other.url) return false return true } override fun hashCodeByKey(): Int { var result = javaClass.hashCode() result = 31 * result + url.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.url?.let { collector.add(it::class.java) } this.excludedPatterns?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
bbf961e679f6f85b7bc3a12387b01284
41.302789
190
0.65323
5.453518
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToFunctionCallIntention.kt
2
6912
// 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.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class FoldIfToFunctionCallIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("lift.function.call.out.of.if"), ) { override fun applicabilityRange(element: KtIfExpression): TextRange? = if (canFoldToFunctionCall(element)) element.ifKeyword.textRange else null override fun applyTo(element: KtIfExpression, editor: Editor?) { foldToFunctionCall(element) } companion object { fun branches(expression: KtExpression): List<KtExpression>? { val branches = when (expression) { is KtIfExpression -> expression.branches is KtWhenExpression -> expression.entries.map { it.expression } else -> emptyList() } val branchesSize = branches.size if (branchesSize < 2) return null return branches.filterNotNull().takeIf { it.size == branchesSize } } private fun canFoldToFunctionCall(element: KtExpression): Boolean { val branches = branches(element) ?: return false val callExpressions = branches.mapNotNull { it.callExpression() } if (branches.size != callExpressions.size) return false if (differentArgumentIndex(callExpressions) == null) return false val headCall = callExpressions.first() val tailCalls = callExpressions.drop(1) val context = headCall.analyze(BodyResolveMode.PARTIAL) val (headFunctionFqName, headFunctionParameters) = headCall.fqNameAndParameters(context) ?: return false return tailCalls.all { call -> val (fqName, parameters) = call.fqNameAndParameters(context) ?: return@all false fqName == headFunctionFqName && parameters.zip(headFunctionParameters).all { it.first == it.second } } } private fun foldToFunctionCall(element: KtExpression) { val branches = branches(element) ?: return val callExpressions = branches.mapNotNull { it.callExpression() } val headCall = callExpressions.first() val argumentIndex = differentArgumentIndex(callExpressions) ?: return val hasNamedArgument = callExpressions.any { call -> call.valueArguments.any { it.getArgumentName() != null } } val copiedIf = element.copy() as KtIfExpression copiedIf.branches.forEach { branch -> val call = branch.callExpression() ?: return val argument = call.valueArguments[argumentIndex].getArgumentExpression() ?: return call.getQualifiedExpressionForSelectorOrThis().replace(argument) } headCall.valueArguments[argumentIndex].getArgumentExpression()?.replace(copiedIf) if (hasNamedArgument) { headCall.valueArguments.forEach { if (it.getArgumentName() == null) AddNameToArgumentIntention.apply(it, givenResolvedCall = null) } } element.replace(headCall.getQualifiedExpressionForSelectorOrThis()).reformatted() } private fun differentArgumentIndex(callExpressions: List<KtCallExpression>): Int? { val headCall = callExpressions.first() val headCalleeText = headCall.calleeText() val tailCalls = callExpressions.drop(1) if (headCall.valueArguments.any { it is KtLambdaArgument }) return null val headArguments = headCall.valueArguments.mapNotNull { it.getArgumentExpression()?.text } val headArgumentsSize = headArguments.size if (headArgumentsSize != headCall.valueArguments.size) return null val differentArgumentIndexes = tailCalls.mapNotNull { call -> if (call.calleeText() != headCalleeText) return@mapNotNull null val arguments = call.valueArguments.mapNotNull { it.getArgumentExpression()?.text } if (arguments.size != headArgumentsSize) return@mapNotNull null val differentArgumentIndexes = arguments.zip(headArguments).mapIndexedNotNull { index, (arg, headArg) -> if (arg != headArg) index else null } differentArgumentIndexes.singleOrNull() } if (differentArgumentIndexes.size != tailCalls.size || differentArgumentIndexes.distinct().size != 1) return null return differentArgumentIndexes.first() } private fun KtExpression?.callExpression(): KtCallExpression? { return when (val expression = if (this is KtBlockExpression) statements.singleOrNull() else this) { is KtCallExpression -> expression is KtQualifiedExpression -> expression.callExpression else -> null }?.takeIf { it.calleeExpression != null } } private fun KtCallExpression.calleeText(): String { val parent = this.parent val (receiver, op) = if (parent is KtQualifiedExpression) { parent.receiverExpression.text to parent.operationSign.value } else { "" to "" } return "$receiver$op${calleeExpression?.text.orEmpty()}" } private fun KtCallExpression.fqNameAndParameters(context: BindingContext): Pair<FqName, List<ValueParameterDescriptor>>? { val resolvedCall = getResolvedCall(context) ?: return null val fqName = resolvedCall.resultingDescriptor.fqNameOrNull() ?: return null val parameters = valueArguments.mapNotNull { (resolvedCall.getArgumentMapping(it) as? ArgumentMatch)?.valueParameter } return fqName to parameters } } }
apache-2.0
f9f39646f494eb91c437917f27ede421
50.969925
140
0.676649
5.520767
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/application/options/editor/fonts/AppEditorFontOptionsPanel.kt
1
9215
// 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.application.options.editor.fonts import com.intellij.application.options.colors.AbstractFontOptionsPanel import com.intellij.application.options.colors.ColorAndFontOptions import com.intellij.application.options.colors.ColorAndFontSettingsListener import com.intellij.ide.DataManager import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.colors.FontPreferences import com.intellij.openapi.editor.colors.ModifiableFontPreferences import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl import com.intellij.openapi.editor.impl.FontFamilyService import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.colors.pages.GeneralColorsPage import com.intellij.openapi.options.ex.Settings import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.AbstractFontCombo import com.intellij.ui.components.ActionLink import com.intellij.ui.layout.* import com.intellij.util.ObjectUtils import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Dimension import java.util.function.Consumer import javax.swing.JComponent class AppEditorFontOptionsPanel(private val scheme: EditorColorsScheme) : AbstractFontOptionsPanel() { private val defaultPreferences = FontPreferencesImpl() private lateinit var restoreDefaults: ActionLink private var regularWeightCombo: FontWeightCombo? = null private var boldWeightCombo: FontWeightCombo? = null init { addListener(object : ColorAndFontSettingsListener.Abstract() { override fun fontChanged() { updateFontPreferences() } }) AppEditorFontOptions.initDefaults(defaultPreferences) updateOptionsList() } override fun isReadOnly(): Boolean { return false } override fun isDelegating(): Boolean { return false } override fun getFontPreferences(): FontPreferences { return scheme.fontPreferences } override fun setFontSize(fontSize: Int) { scheme.editorFontSize = fontSize } override fun getLineSpacing(): Float { return scheme.lineSpacing } override fun setCurrentLineSpacing(lineSpacing: Float) { scheme.lineSpacing = lineSpacing } override fun createPrimaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(true) } else { super.createPrimaryFontCombo() } } override fun createSecondaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(false) } else { super.createSecondaryFontCombo() } } fun updateOnChangedFont() { updateOptionsList() fireFontChanged() } private fun restoreDefaults() { AppEditorFontOptions.initDefaults(fontPreferences as ModifiableFontPreferences) updateOnChangedFont() } override fun createControls(): JComponent { return panel { row(primaryLabel) { component(primaryCombo) } row(sizeLabel) { component(editorFontSizeField) component(lineSpacingLabel).withLargeLeftGap() component(lineSpacingField) } fullRow { component(enableLigaturesCheckbox) component(enableLigaturesHintLabel).withLeftGap() } row { hyperlink(ApplicationBundle.message("comment.use.ligatures.with.reader.mode"), style = UIUtil.ComponentStyle.SMALL, color = UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)) { goToReaderMode() } } row { restoreDefaults = ActionLink(ApplicationBundle.message("settings.editor.font.restored.defaults")) { restoreDefaults() } component(restoreDefaults) } row { component(createTypographySettings()) } }.withBorder(JBUI.Borders.empty(BASE_INSET)) } fun updateFontPreferences() { restoreDefaults.isEnabled = defaultPreferences != fontPreferences regularWeightCombo?.apply { update(fontPreferences) } boldWeightCombo?.apply { update(fontPreferences) } } private fun createTypographySettings(): DialogPanel { return panel { hideableRow(ApplicationBundle.message("settings.editor.font.typography.settings"), incrementsIndent = false) { if (isAdvancedFontFamiliesUI()) { row(ApplicationBundle.message("settings.editor.font.main.weight")) { val component = createRegularWeightCombo() regularWeightCombo = component component(component) } row(ApplicationBundle.message("settings.editor.font.bold.weight")) { val component = createBoldWeightCombo() boldWeightCombo = component component(component) } row("") { hyperlink(ApplicationBundle.message("settings.editor.font.bold.weight.hint"), style = UIUtil.ComponentStyle.SMALL, color = UIUtil.getContextHelpForeground()) { navigateToColorSchemeTextSettings() } } // .largeGapAfter() doesn't work now } row { val secondaryFont = label(ApplicationBundle.message("secondary.font")) setSecondaryFontLabel(secondaryFont.component) component(secondaryCombo) } row("") { val description = label(ApplicationBundle.message("label.fallback.fonts.list.description"), style = UIUtil.ComponentStyle.SMALL) description.component.foreground = UIUtil.getContextHelpForeground() } } } } private fun navigateToColorSchemeTextSettings() { var defaultTextOption = OptionsBundle.message("options.general.attribute.descriptor.default.text") val separator = "//" val separatorPos = defaultTextOption.lastIndexOf(separator) if (separatorPos > 0) { defaultTextOption = defaultTextOption.substring(separatorPos + separator.length) } val allSettings = Settings.KEY.getData(DataManager.getInstance().getDataContext(this)) if (allSettings != null) { val colorSchemeConfigurable = allSettings.find(ColorAndFontOptions.ID) if (colorSchemeConfigurable is ColorAndFontOptions) { val generalSettings: Configurable? = colorSchemeConfigurable.findSubConfigurable(GeneralColorsPage.getDisplayNameText()) if (generalSettings != null) { allSettings.select(generalSettings, defaultTextOption) } } } } private fun createRegularWeightCombo(): FontWeightCombo { val result = RegularFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: ModifiableFontPreferences -> val newSubFamily = result.selectedSubFamily if (preferences.regularSubFamily != newSubFamily) { preferences.boldSubFamily = null // Reset bold subfamily for a different regular } preferences.regularSubFamily = newSubFamily } } return result } private fun createBoldWeightCombo(): FontWeightCombo { val result = BoldFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: ModifiableFontPreferences -> preferences.boldSubFamily = result.selectedSubFamily } } return result } private fun changeFontPreferences(consumer: Consumer<ModifiableFontPreferences>) { val preferences = fontPreferences assert(preferences is ModifiableFontPreferences) consumer.accept(preferences as ModifiableFontPreferences) fireFontChanged() } private class RegularFontWeightCombo : FontWeightCombo(false) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.regularSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedSubFamily(family) } } private inner class BoldFontWeightCombo : FontWeightCombo(true) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.boldSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedBoldSubFamily( family, ObjectUtils.notNull(regularWeightCombo?.selectedSubFamily, FontFamilyService.getRecommendedSubFamily(family))) } } } private fun isAdvancedFontFamiliesUI(): Boolean { return AppEditorFontOptions.NEW_FONT_SELECTOR } private const val FONT_WEIGHT_COMBO_WIDTH = 250 private fun fixComboWidth(combo: FontWeightCombo) { val width = JBUI.scale(FONT_WEIGHT_COMBO_WIDTH) with(combo) { minimumSize = Dimension(width, 0) maximumSize = Dimension(width, Int.MAX_VALUE) preferredSize = Dimension(width, preferredSize.height) } }
apache-2.0
b9eeae71ff8c1d44f68aa57aa8dad054
31.450704
158
0.718285
4.951639
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableMutabilityFix.kt
3
4496
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class ChangeVariableMutabilityFix( element: KtValVarKeywordOwner, private val makeVar: Boolean, private val actionText: String? = null, private val deleteInitializer: Boolean = false ) : KotlinPsiOnlyQuickFixAction<KtValVarKeywordOwner>(element) { override fun getText() = actionText ?: (if (makeVar) KotlinBundle.message("change.to.var") else KotlinBundle.message("change.to.val")) + if (deleteInitializer) KotlinBundle.message("and.delete.initializer") else "" override fun getFamilyName(): String = text override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false val valOrVar = element.valOrVarKeyword?.node?.elementType ?: return false return (valOrVar == KtTokens.VAR_KEYWORD) != makeVar } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val factory = KtPsiFactory(project) val newKeyword = if (makeVar) factory.createVarKeyword() else factory.createValKeyword() element.valOrVarKeyword!!.replace(newKeyword) if (deleteInitializer) { (element as? KtProperty)?.initializer = null } if (makeVar) { (element as? KtModifierListOwner)?.removeModifier(KtTokens.CONST_KEYWORD) } } companion object { val VAL_WITH_SETTER_FACTORY: QuickFixesPsiBasedFactory<KtPropertyAccessor> = quickFixesPsiBasedFactory { psiElement: KtPropertyAccessor -> listOf(ChangeVariableMutabilityFix(psiElement.property, true)) } val VAR_OVERRIDDEN_BY_VAL_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> when (psiElement) { is KtProperty, is KtParameter -> listOf(ChangeVariableMutabilityFix(psiElement as KtValVarKeywordOwner, true)) else -> emptyList() } } val VAR_ANNOTATION_PARAMETER_FACTORY: QuickFixesPsiBasedFactory<KtParameter> = quickFixesPsiBasedFactory { psiElement: KtParameter -> listOf(ChangeVariableMutabilityFix(psiElement, false)) } val LATEINIT_VAL_FACTORY: QuickFixesPsiBasedFactory<KtModifierListOwner> = quickFixesPsiBasedFactory { psiElement: KtModifierListOwner -> val property = psiElement as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList() if (property.valOrVarKeyword.text != "val") { emptyList() } else { listOf(ChangeVariableMutabilityFix(property, makeVar = true)) } } val CONST_VAL_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> if (psiElement.node.elementType as? KtModifierKeywordToken != KtTokens.CONST_KEYWORD) return@quickFixesPsiBasedFactory emptyList() val property = psiElement.getStrictParentOfType<KtProperty>() ?: return@quickFixesPsiBasedFactory emptyList() listOf(ChangeVariableMutabilityFix(property, makeVar = false)) } val MUST_BE_INITIALIZED_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> val property = psiElement as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList() val getter = property.getter ?: return@quickFixesPsiBasedFactory emptyList() if (!getter.hasBody()) return@quickFixesPsiBasedFactory emptyList() if (getter.hasBlockBody() && property.typeReference == null) return@quickFixesPsiBasedFactory emptyList() listOf(ChangeVariableMutabilityFix(property, makeVar = false)) } } }
apache-2.0
143b670449b5ca5eaf166b3c13cad4f3
48.417582
158
0.682162
5.456311
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptExternalLibrariesNodesProvider.kt
1
3221
// 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.core.script import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.projectView.impl.nodes.ExternalLibrariesWorkspaceModelNodesProvider import com.intellij.ide.projectView.impl.nodes.SyntheticLibraryElementNode import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.project.Project import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.workspaceModel.ide.impl.virtualFile import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRootTypeId import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptEntity import org.jetbrains.kotlin.idea.core.script.ucache.relativeName import org.jetbrains.kotlin.idea.core.script.ucache.scriptsAsEntities import java.nio.file.Path import javax.swing.Icon class KotlinScriptExternalLibrariesNodesProvider: ExternalLibrariesWorkspaceModelNodesProvider<KotlinScriptEntity> { override fun getWorkspaceClass(): Class<KotlinScriptEntity> = KotlinScriptEntity::class.java override fun createNode(entity: KotlinScriptEntity, project: Project, settings: ViewSettings?): AbstractTreeNode<*>? { if (!scriptsAsEntities) return null val dependencies = entity.listDependencies() val scriptFile = VirtualFileManager.getInstance().findFileByNioPath(Path.of(entity.path)) ?: error("Cannot find file: ${entity.path}") val library = KotlinScriptDependenciesLibrary("Script: ${scriptFile.relativeName(project)}", dependencies.compiled, dependencies.sources) return SyntheticLibraryElementNode(project, library, library, settings) } } private data class KotlinScriptDependenciesLibrary(val name: String, val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) : SyntheticLibrary(), ItemPresentation { override fun getBinaryRoots(): Collection<VirtualFile> = classes override fun getSourceRoots(): Collection<VirtualFile> = sources override fun getPresentableText(): String = name override fun getIcon(unused: Boolean): Icon = KotlinIcons.SCRIPT } private fun KotlinScriptEntity.listDependencies(): ScriptDependencies { fun List<LibraryRoot>.files() = asSequence() .mapNotNull { it.url.virtualFile } .filter { it.isValid } .toList() val (compiledRoots, sourceRoots) = dependencies.asSequence() .flatMap { it.roots } .partition { it.type == LibraryRootTypeId.COMPILED } return ScriptDependencies(Pair(compiledRoots.files(), sourceRoots.files())) } @JvmInline private value class ScriptDependencies(private val compiledAndSources: Pair<List<VirtualFile>, List<VirtualFile>>) { val compiled get() = compiledAndSources.first val sources get() = compiledAndSources.second }
apache-2.0
17ba901683a8b33af67da66795bb10e7
43.136986
146
0.773052
4.850904
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrArrayInitializerImpl.kt
9
1414
// 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.lang.psi.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiListLikeElement import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.childrenOfType import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.T_LBRACE import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GrArrayInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression class GrArrayInitializerImpl(node: ASTNode) : GroovyPsiElementImpl(node), GrArrayInitializer, PsiListLikeElement { override fun toString(): String = "Array initializer" override fun accept(visitor: GroovyElementVisitor): Unit = visitor.visitArrayInitializer(this) override fun getLBrace(): PsiElement = findNotNullChildByType(T_LBRACE) override fun isEmpty(): Boolean = node.getChildren(TokenSet.ANY).none { it.psi is GrExpression } override fun getExpressions(): List<GrExpression> = childrenOfType() override fun getRBrace(): PsiElement? = findChildByType(GroovyElementTypes.T_RBRACE) override fun getComponents(): List<PsiElement> = expressions }
apache-2.0
c293974bc0b747346db8afc10a0764a2
46.133333
140
0.815417
4.297872
false
false
false
false
ianhanniballake/muzei
main/src/main/java/com/google/android/apps/muzei/settings/EffectsScreenFragment.kt
2
6964
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.settings import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.SeekBar import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.google.android.apps.muzei.render.MuzeiBlurRenderer import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.EffectsScreenFragmentBinding /** * Fragment for allowing the user to configure advanced settings. */ class EffectsScreenFragment : Fragment(R.layout.effects_screen_fragment) { companion object { private const val PREF_BLUR = "pref_blur" private const val PREF_DIM = "pref_dim" private const val PREF_GREY = "pref_grey" internal fun create( prefBlur: String, prefDim: String, prefGrey: String ) = EffectsScreenFragment().apply { arguments = bundleOf( PREF_BLUR to prefBlur, PREF_DIM to prefDim, PREF_GREY to prefGrey ) } } private lateinit var blurPref: String private lateinit var dimPref: String private lateinit var greyPref: String private lateinit var blurOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private lateinit var dimOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private lateinit var greyOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private var updateBlur: Job? = null private var updateDim: Job? = null private var updateGrey: Job? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) blurPref = requireArguments().getString(PREF_BLUR) ?: throw IllegalArgumentException("Missing required argument $PREF_BLUR") dimPref = requireArguments().getString(PREF_DIM) ?: throw IllegalArgumentException("Missing required argument $PREF_DIM") greyPref = requireArguments().getString(PREF_GREY) ?: throw IllegalArgumentException("Missing required argument $PREF_GREY") } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = EffectsScreenFragmentBinding.bind(view) val prefs = Prefs.getSharedPreferences(requireContext()) binding.content.blurAmount.progress = prefs.getInt(blurPref, MuzeiBlurRenderer.DEFAULT_BLUR) binding.content.blurAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateBlur?.cancel() updateBlur = lifecycleScope.launch { delay(750) prefs.edit { putInt(blurPref, binding.content.blurAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) blurOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.blurAmount.progress = prefs.getInt(blurPref, MuzeiBlurRenderer.DEFAULT_BLUR) } prefs.registerOnSharedPreferenceChangeListener(blurOnPreferenceChangeListener) binding.content.dimAmount.progress = prefs.getInt(dimPref, MuzeiBlurRenderer.DEFAULT_MAX_DIM) binding.content.dimAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateDim?.cancel() updateDim = lifecycleScope.launch { delay(750) prefs.edit { putInt(dimPref, binding.content.dimAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) dimOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.dimAmount.progress = prefs.getInt(dimPref, MuzeiBlurRenderer.DEFAULT_MAX_DIM) } prefs.registerOnSharedPreferenceChangeListener(dimOnPreferenceChangeListener) binding.content.greyAmount.progress = prefs.getInt(greyPref, MuzeiBlurRenderer.DEFAULT_GREY) binding.content.greyAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateGrey?.cancel() updateGrey = lifecycleScope.launch { delay(750) prefs.edit { putInt(greyPref, binding.content.greyAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) greyOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.greyAmount.progress = prefs.getInt(greyPref, MuzeiBlurRenderer.DEFAULT_GREY) } prefs.registerOnSharedPreferenceChangeListener(greyOnPreferenceChangeListener) } override fun onDestroyView() { super.onDestroyView() Prefs.getSharedPreferences(requireContext()).apply { unregisterOnSharedPreferenceChangeListener(blurOnPreferenceChangeListener) unregisterOnSharedPreferenceChangeListener(dimOnPreferenceChangeListener) unregisterOnSharedPreferenceChangeListener(greyOnPreferenceChangeListener) } } }
apache-2.0
b114f67a40fd5a5b2dbaad9416f0c172
41.723926
107
0.661114
5.607085
false
false
false
false
Jire/Charlatano
src/main/kotlin/com/charlatano/settings/Scripts.kt
1
1765
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.settings /** * Enables the bunny hop script. * * When using "LEAGUE_MODE" you need to unbind the bunnyhop key, * and bind mwheelup and mwheeldown to jump. * * To do this, type the following commands into the in-game developer console: * unbind "space" * bind "mwheelup" "+jump" * bind "mwheeldown" "+jump" */ var ENABLE_BUNNY_HOP = false /** * Enables the recoil control system (RCS) script. */ var ENABLE_RCS = true /** * Enables the extra sensory perception (ESP) script. */ var ENABLE_ESP = true /** * Enables the flat aim script. * * This script uses traditional flat linear-regression smoothing. */ var ENABLE_FLAT_AIM = true /** * Enables the path aim script. * * This script uses an advanced path generation smoothing. */ var ENABLE_PATH_AIM = false /** * Enables the bone trigger bot script. */ var ENABLE_BONE_TRIGGER = false /** * Enables the bomb timer script. */ var ENABLE_BOMB_TIMER = false
agpl-3.0
2a033ccd03ec03e4a73fa0c461aa33ac
25.757576
78
0.712748
3.654244
false
false
false
false
intrigus/jtransc
jtransc-gen-cpp/src/com/jtransc/gen/cpp/libs/Libs.kt
1
1223
package com.jtransc.gen.cpp.libs import com.jtransc.gen.cpp.CppCompiler import com.jtransc.io.ProcessUtils import com.jtransc.service.JTranscService import com.jtransc.vfs.ExecOptions import com.jtransc.vfs.SyncVfsFile import org.rauschig.jarchivelib.ArchiveFormat import org.rauschig.jarchivelib.ArchiverFactory import org.rauschig.jarchivelib.CompressionType import java.io.File import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* object Libs { //val LIBS = ServiceLoader.load(Lib::class.java).toList() //val LIBS = listOf(BoostLib(), BdwgcLib(), JniHeadersLib()) //val LIBS = listOf(BdwgcLib(), JniHeadersLib()) val LIBS = listOf(BdwgcLib()) val cppCommonFolder get() = CppCompiler.CPP_COMMON_FOLDER.realfile val sdkDir = CppCompiler.CPP_COMMON_FOLDER.realfile val includeFolders: List<File> get() = LIBS.flatMap { it.includeFolders } val libFolders: List<File> get() = LIBS.flatMap { it.libFolders } val libs: List<String> get() = LIBS.flatMap { it.libs } val extraDefines: List<String> get() = LIBS.flatMap { it.extraDefines } fun installIfRequired(resourcesVfs: SyncVfsFile) { for (lib in LIBS) { lib.installIfRequired(resourcesVfs) } } }
apache-2.0
f19d3092b79951a7e7548333d079b626
32.972222
74
0.771055
3.127877
false
false
false
false
bixlabs/bkotlin
bkotlin/src/main/java/com/bixlabs/bkotlin/Only.kt
1
4392
@file:Suppress("unused", "MemberVisibilityCanBePrivate") package com.bixlabs.bkotlin import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo @DslMarker annotation class OnlyDsl /** * An easy way of running tasks a specific amount of times throughout the lifespan of an app, * either between versions of itself or regardless of the same. */ object Only { private lateinit var preference: SharedPreferences private lateinit var buildVersion: String private var isDebuggable = 0 private var doOnDebugMode = false /** initialize [Only] */ fun init(context: Context) { val info = context.packageManager.getPackageInfo(context.packageName, 0) init(context, info.versionName) } /** initialize [Only], providing a specific version for the tasks. */ fun init(context: Context, version: String) { this.preference = context.applicationContext.getSharedPreferences("Only", Context.MODE_PRIVATE) this.isDebuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE this.buildVersion = version } /** Sets if [Only] should be in debug mode. */ fun setDebugMode(debug: Boolean): Only { this.doOnDebugMode = debug return this@Only } /** Checks if [Only] is in debug mode. */ fun isDebugModeEnabled(): Boolean = doOnDebugMode && isDebuggable != 0 /** Gets the amount of times a specific task has been run. */ fun getTaskTimes(taskName: String): Int = this.preference.getInt(taskName, 0) /** Sets the amount of times a specific task has been run. */ fun setTaskTimes(taskName: String, time: Int) = this.preference.edit().putInt(taskName, time).apply() /** Gets the version of a specific task if any */ fun getTaskVersion(taskName: String): String? = preference.getString(getTaskVersionName(taskName), buildVersion) /** Clear the amount of times a specific task has been run. */ fun clearTask(taskName: String) = this.preference.edit().remove(taskName).apply() /** Clear the amount of times for all tasks. */ fun clearAllTasks() = this.preference.edit().clear().apply() /* ******************************************** * Private methods * ******************************************** */ private inline fun onDo(name: String, times: Int, crossinline onDo: () -> Unit, crossinline onDone: () -> Unit, version: String = ""): Only { checkTaskVersion(name, version) // run only onDo block when debug mode. if (isDebugModeEnabled()) { onDo() return this@Only } val persistVersion = getTaskTimes(name) if (persistVersion < times) { setTaskTimes(name, persistVersion + 1) onDo() } else { onDone() } return this@Only } private fun checkTaskVersion(taskName: String, version: String): Boolean { val theVersion = if (version.isEmpty()) buildVersion else version if (getTaskVersion(taskName).equals(theVersion)) return true setTaskTimes(taskName, 0) setTaskVersion(taskName, theVersion) return false } private fun runByBuilder(builder: Builder) = onDo(builder.name, builder.times, builder.onDo, builder.onPreviouslyDone, builder.version) private fun setTaskVersion(name: String, version: String) = this.preference.edit().putString(getTaskVersionName(name), version).apply() private fun getTaskVersionName(name: String): String = "${name}_version" @OnlyDsl class Builder internal constructor(val name: String, val times: Int = 1) { var onDo: () -> Unit = { } var onPreviouslyDone: () -> Unit = { } var version: String = "" fun onDo(onDo: () -> Unit): Builder = apply { this.onDo = onDo } fun onPreviouslyDone(onDone: () -> Unit): Builder = apply { this.onPreviouslyDone = onDone } fun taskVersion(version: String): Builder = apply { this.version = version } fun run() = runByBuilder(this@Builder) } } /** Run [Only] by [Only.Builder] using kotlin DSL. */ @OnlyDsl fun only(taskName: String, times: Int, block: Only.Builder.() -> Unit): Unit = Only.Builder(taskName, times) .apply(block) .run() .toUnit()
apache-2.0
c991642878221a1a4494323b8e355647
34.427419
145
0.642077
4.405216
false
false
false
false
intrigus/jtransc
jtransc-utils/src/com/jtransc/lang/bool.kt
2
896
package com.jtransc.lang inline fun <T> Boolean.map(t: T, f: T) = if (this) t else f fun Boolean.toBool() = (this) fun Byte.toBool() = (this.toInt() != 0) fun Char.toBool() = (this.toInt() != 0) fun Short.toBool() = (this.toInt() != 0) fun Int.toBool() = (this.toInt() != 0) fun Long.toBool() = (this.toInt() != 0) fun Float.toBool() = (this != 0f) fun Double.toBool() = (this != 0.0) fun Boolean.toByte() = this.map(1, 0).toByte() fun Boolean.toChar() = this.map(1, 0).toChar() fun Boolean.toShort() = this.map(1, 0).toShort() fun Boolean.toInt() = this.map(1, 0).toInt() fun Boolean.toLong() = this.map(1, 0).toLong() fun Boolean.toFloat() = this.map(1, 0).toFloat() fun Boolean.toDouble() = this.map(1, 0).toDouble() fun Number.toBool() = (this.toInt() != 0) val Long.high:Int get() = ((this ushr 32) and 0xFFFFFFFF).toInt() val Long.low:Int get() = ((this ushr 0) and 0xFFFFFFFF).toInt()
apache-2.0
48f82b5511f4cead2b81709d52860628
34.88
65
0.635045
2.682635
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/writer/DatabaseWriter.kt
1
7339
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.ext.AndroidTypeNames import androidx.room.ext.L import androidx.room.ext.N import androidx.room.ext.RoomTypeNames import androidx.room.ext.S import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.T import androidx.room.solver.CodeGenScope import androidx.room.vo.DaoMethod import androidx.room.vo.Database import com.google.auto.common.MoreElements import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import stripNonJava import javax.lang.model.element.Modifier import javax.lang.model.element.Modifier.PRIVATE import javax.lang.model.element.Modifier.PROTECTED import javax.lang.model.element.Modifier.PUBLIC import javax.lang.model.element.Modifier.VOLATILE /** * Writes implementation of classes that were annotated with @Database. */ class DatabaseWriter(val database: Database) : ClassWriter(database.implTypeName) { override fun createTypeSpecBuilder(): TypeSpec.Builder { val builder = TypeSpec.classBuilder(database.implTypeName) builder.apply { addModifiers(PUBLIC) superclass(database.typeName) addMethod(createCreateOpenHelper()) addMethod(createCreateInvalidationTracker()) addMethod(createClearAllTables()) } addDaoImpls(builder) return builder } private fun createClearAllTables(): MethodSpec { val scope = CodeGenScope(this) return MethodSpec.methodBuilder("clearAllTables").apply { addStatement("super.assertNotMainThread()") val dbVar = scope.getTmpVar("_db") addStatement("final $T $L = super.getOpenHelper().getWritableDatabase()", SupportDbTypeNames.DB, dbVar) val deferVar = scope.getTmpVar("_supportsDeferForeignKeys") if (database.enableForeignKeys) { addStatement("boolean $L = $L.VERSION.SDK_INT >= $L.VERSION_CODES.LOLLIPOP", deferVar, AndroidTypeNames.BUILD, AndroidTypeNames.BUILD) } addAnnotation(Override::class.java) addModifiers(PUBLIC) returns(TypeName.VOID) beginControlFlow("try").apply { if (database.enableForeignKeys) { beginControlFlow("if (!$L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA foreign_keys = FALSE") } endControlFlow() } addStatement("super.beginTransaction()") if (database.enableForeignKeys) { beginControlFlow("if ($L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA defer_foreign_keys = TRUE") } endControlFlow() } database.entities.sortedWith(EntityDeleteComparator()).forEach { addStatement("$L.execSQL($S)", dbVar, "DELETE FROM `${it.tableName}`") } addStatement("super.setTransactionSuccessful()") } nextControlFlow("finally").apply { addStatement("super.endTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (!$L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA foreign_keys = TRUE") } endControlFlow() } addStatement("$L.query($S).close()", dbVar, "PRAGMA wal_checkpoint(FULL)") beginControlFlow("if (!$L.inTransaction())", dbVar).apply { addStatement("$L.execSQL($S)", dbVar, "VACUUM") } endControlFlow() } endControlFlow() }.build() } private fun createCreateInvalidationTracker(): MethodSpec { return MethodSpec.methodBuilder("createInvalidationTracker").apply { addAnnotation(Override::class.java) addModifiers(PROTECTED) returns(RoomTypeNames.INVALIDATION_TRACKER) val tableNames = database.entities.joinToString(",") { "\"${it.tableName}\"" } addStatement("return new $T(this, $L)", RoomTypeNames.INVALIDATION_TRACKER, tableNames) }.build() } private fun addDaoImpls(builder: TypeSpec.Builder) { val scope = CodeGenScope(this) builder.apply { database.daoMethods.forEach { method -> val name = method.dao.typeName.simpleName().decapitalize().stripNonJava() val fieldName = scope.getTmpVar("_$name") val field = FieldSpec.builder(method.dao.typeName, fieldName, PRIVATE, VOLATILE).build() addField(field) addMethod(createDaoGetter(field, method)) } } } private fun createDaoGetter(field: FieldSpec, method: DaoMethod): MethodSpec { return MethodSpec.overriding(MoreElements.asExecutable(method.element)).apply { beginControlFlow("if ($N != null)", field).apply { addStatement("return $N", field) } nextControlFlow("else").apply { beginControlFlow("synchronized(this)").apply { beginControlFlow("if($N == null)", field).apply { addStatement("$N = new $T(this)", field, method.dao.implTypeName) } endControlFlow() addStatement("return $N", field) } endControlFlow() } endControlFlow() }.build() } private fun createCreateOpenHelper(): MethodSpec { val scope = CodeGenScope(this) return MethodSpec.methodBuilder("createOpenHelper").apply { addModifiers(Modifier.PROTECTED) addAnnotation(Override::class.java) returns(SupportDbTypeNames.SQLITE_OPEN_HELPER) val configParam = ParameterSpec.builder(RoomTypeNames.ROOM_DB_CONFIG, "configuration").build() addParameter(configParam) val openHelperVar = scope.getTmpVar("_helper") val openHelperCode = scope.fork() SQLiteOpenHelperWriter(database) .write(openHelperVar, configParam, openHelperCode) addCode(openHelperCode.builder().build()) addStatement("return $L", openHelperVar) }.build() } }
apache-2.0
0eab3903efa4aab5cff8af2729264705
40.937143
99
0.608394
5.089459
false
false
false
false
aosp-mirror/platform_frameworks_support
navigation/safe-args-generator/src/main/kotlin/androidx/navigation/safe/args/generator/NavParser.kt
1
8153
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.safe.args.generator import androidx.navigation.safe.args.generator.models.Action import androidx.navigation.safe.args.generator.models.Argument import androidx.navigation.safe.args.generator.models.Destination import androidx.navigation.safe.args.generator.models.ResReference import java.io.File import java.io.FileReader private const val TAG_NAVIGATION = "navigation" private const val TAG_ACTION = "action" private const val TAG_ARGUMENT = "argument" private const val ATTRIBUTE_ID = "id" private const val ATTRIBUTE_DESTINATION = "destination" private const val ATTRIBUTE_DEFAULT_VALUE = "defaultValue" private const val ATTRIBUTE_NAME = "name" private const val ATTRIBUTE_TYPE = "type" private const val NAMESPACE_RES_AUTO = "http://schemas.android.com/apk/res-auto" private const val NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android" internal class NavParser( private val parser: XmlPositionParser, private val context: Context, private val rFilePackage: String, private val applicationId: String ) { companion object { fun parseNavigationFile( navigationXml: File, rFilePackage: String, applicationId: String, context: Context ): Destination { FileReader(navigationXml).use { reader -> val parser = XmlPositionParser(navigationXml.path, reader, context.logger) parser.traverseStartTags { true } return NavParser(parser, context, rFilePackage, applicationId).parseDestination() } } } internal fun parseDestination(): Destination { val position = parser.xmlPosition() val type = parser.name() val name = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_NAME) ?: "" val idValue = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_ID) val args = mutableListOf<Argument>() val actions = mutableListOf<Action>() val nested = mutableListOf<Destination>() parser.traverseInnerStartTags { when { parser.name() == TAG_ACTION -> actions.add(parseAction()) parser.name() == TAG_ARGUMENT -> args.add(parseArgument()) type == TAG_NAVIGATION -> nested.add(parseDestination()) } } val id = idValue?.let { parseId(idValue, rFilePackage, position) } val className = Destination.createName(id, name, applicationId) if (className == null && (actions.isNotEmpty() || args.isNotEmpty())) { context.logger.error(NavParserErrors.UNNAMED_DESTINATION, position) return context.createStubDestination() } return Destination(id, className, type, args, actions, nested) } private fun parseArgument(): Argument { val xmlPosition = parser.xmlPosition() val name = parser.attrValueOrError(NAMESPACE_ANDROID, ATTRIBUTE_NAME) val defaultValue = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_DEFAULT_VALUE) val typeString = parser.attrValue(NAMESPACE_RES_AUTO, ATTRIBUTE_TYPE) if (name == null) return context.createStubArg() if (typeString == null && defaultValue != null) { return inferArgument(name, defaultValue, rFilePackage) } val type = NavType.from(typeString) if (type == null) { context.logger.error(NavParserErrors.unknownType(typeString), xmlPosition) return context.createStubArg() } if (defaultValue == null) { return Argument(name, type, null) } val defaultTypedValue = when (type) { NavType.INT -> parseIntValue(defaultValue) NavType.FLOAT -> parseFloatValue(defaultValue) NavType.BOOLEAN -> parseBoolean(defaultValue) NavType.REFERENCE -> parseReference(defaultValue, rFilePackage)?.let { ReferenceValue(it) } NavType.STRING -> StringValue(defaultValue) } if (defaultTypedValue == null) { val errorMessage = when (type) { NavType.REFERENCE -> NavParserErrors.invalidDefaultValueReference(defaultValue) else -> NavParserErrors.invalidDefaultValue(defaultValue, type) } context.logger.error(errorMessage, xmlPosition) return context.createStubArg() } return Argument(name, type, defaultTypedValue) } private fun parseAction(): Action { val idValue = parser.attrValueOrError(NAMESPACE_ANDROID, ATTRIBUTE_ID) val destValue = parser.attrValue(NAMESPACE_RES_AUTO, ATTRIBUTE_DESTINATION) val args = mutableListOf<Argument>() val position = parser.xmlPosition() parser.traverseInnerStartTags { if (parser.name() == TAG_ARGUMENT) { args.add(parseArgument()) } } val id = if (idValue != null) { parseId(idValue, rFilePackage, position) } else { context.createStubId() } val destination = destValue?.let { parseId(destValue, rFilePackage, position) } return Action(id, destination, args) } private fun parseId( xmlId: String, rFilePackage: String, xmlPosition: XmlPosition ): ResReference { val ref = parseReference(xmlId, rFilePackage) if (ref?.isId() == true) { return ref } context.logger.error(NavParserErrors.invalidId(xmlId), xmlPosition) return context.createStubId() } } internal fun inferArgument(name: String, defaultValue: String, rFilePackage: String): Argument { val reference = parseReference(defaultValue, rFilePackage) if (reference != null) { return Argument(name, NavType.REFERENCE, ReferenceValue(reference)) } val intValue = parseIntValue(defaultValue) if (intValue != null) { return Argument(name, NavType.INT, intValue) } val floatValue = parseFloatValue(defaultValue) if (floatValue != null) { return Argument(name, NavType.FLOAT, floatValue) } val boolValue = parseBoolean(defaultValue) if (boolValue != null) { return Argument(name, NavType.BOOLEAN, boolValue) } return Argument(name, NavType.STRING, StringValue(defaultValue)) } // @[+][package:]id/resource_name -> package.R.id.resource_name private val RESOURCE_REGEX = Regex("^@[+]?(.+?:)?(.+?)/(.+)$") internal fun parseReference(xmlValue: String, rFilePackage: String): ResReference? { val matchEntire = RESOURCE_REGEX.matchEntire(xmlValue) ?: return null val groups = matchEntire.groupValues val resourceName = groups.last() val resType = groups[groups.size - 2] val packageName = if (groups[1].isNotEmpty()) groups[1].removeSuffix(":") else rFilePackage return ResReference(packageName, resType, resourceName) } internal fun parseIntValue(value: String): IntValue? { try { if (value.startsWith("0x")) { Integer.parseUnsignedInt(value.substring(2), 16) } else { Integer.parseInt(value) } } catch (ex: NumberFormatException) { return null } return IntValue(value) } private fun parseFloatValue(value: String): FloatValue? = value.toFloatOrNull()?.let { FloatValue(value) } private fun parseBoolean(value: String): BooleanValue? { if (value == "true" || value == "false") { return BooleanValue(value) } return null }
apache-2.0
b11036af071cb657341a05a7fedca9dc
36.571429
97
0.6562
4.516898
false
false
false
false
aspanu/SolutionsHackerRank
src/ClockTimes.kt
1
1037
import java.time.LocalTime.MIDNIGHT import java.time.format.DateTimeFormatter /** * Created by aspanu on 2017-09-12. */ fun main(args: Array<String>) { var currTime = MIDNIGHT var numTimes = 0 do { if (maxNumSameDigits(currTime.format(DateTimeFormatter.ofPattern("h:mm"))) >= 3) { numTimes++ println("Time: ${currTime.format(DateTimeFormatter.ofPattern("h:mm"))} has 3 or more digits.") } currTime = currTime.plusMinutes(1) } while (currTime != MIDNIGHT) println("Total number of times: $numTimes") } fun maxNumSameDigits(stringTime: String): Int { val charMap = mutableMapOf<Char, Int>() var maxNumDigits = -1 for (c in stringTime.toCharArray()) { if (c.isDigit()) { if (!charMap.containsKey(c)) { charMap.put(c, 0) } charMap.put(c, (charMap[c]!! + 1)) if (charMap[c]!! > maxNumDigits) maxNumDigits = charMap[c]!! } } return maxNumDigits }
gpl-2.0
b4acee1d40a35de49beb40a166e440a5
23.690476
106
0.581485
3.757246
false
false
false
false
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/service/connection/ServiceSocket.kt
1
2808
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.download.service.connection import android.content.Context import android.content.Intent import android.os.IBinder import android.os.Message import android.os.Messenger import android.os.RemoteException import jp.hazuki.yuzubrowser.core.service.ServiceBindHelper import jp.hazuki.yuzubrowser.core.service.ServiceConnectionHelper import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.download.service.DownloadService class ServiceSocket(private val context: Context, listener: ActivityClient.ActivityClientListener) : ServiceConnectionHelper<Messenger> { private val messenger = Messenger(ActivityClient(listener)) private val serviceHelper = ServiceBindHelper(context, this) override fun onBind(service: IBinder): Messenger { service.messenger.run { safeSend(createMessage(REGISTER_OBSERVER)) safeSend(createMessage(GET_DOWNLOAD_INFO)) return this } } override fun onUnbind(service: Messenger?) { serviceHelper.binder?.safeSend(createMessage(UNREGISTER_OBSERVER)) } fun bindService() { serviceHelper.bindService(Intent(context, DownloadService::class.java)) } fun unbindService() { serviceHelper.unbindService() } fun cancelDownload(id: Long) { serviceHelper.binder?.safeSend(createMessage(CANCEL_DOWNLOAD, id)) } fun pauseDownload(id: Long) { serviceHelper.binder?.safeSend(createMessage(PAUSE_DOWNLOAD, id)) } private fun Messenger.safeSend(message: Message) { try { send(message) } catch (e: RemoteException) { ErrorReport.printAndWriteLog(e) } } private fun createMessage(@ServiceCommand command: Int, obj: Any? = null) = Message.obtain(null, command, obj).apply { replyTo = messenger } private val IBinder.messenger get() = Messenger(this) companion object { const val REGISTER_OBSERVER = 0 const val UNREGISTER_OBSERVER = 1 const val UPDATE = 2 const val GET_DOWNLOAD_INFO = 3 const val CANCEL_DOWNLOAD = 4 const val PAUSE_DOWNLOAD = 5 } }
apache-2.0
284f3798c86e2db0aeaee6947b904d0e
32.440476
137
0.707977
4.464229
false
false
false
false
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/actions/IAction.kt
1
1337
package de.markusfisch.android.binaryeye.actions import android.content.Context import android.content.Intent import de.markusfisch.android.binaryeye.content.execShareIntent import de.markusfisch.android.binaryeye.content.openUrl import de.markusfisch.android.binaryeye.widget.toast interface IAction { val iconResId: Int val titleResId: Int fun canExecuteOn(data: ByteArray): Boolean suspend fun execute(context: Context, data: ByteArray) } abstract class IntentAction : IAction { abstract val errorMsg: Int final override suspend fun execute(context: Context, data: ByteArray) { val intent = createIntent(context, data) if (intent == null) { context.toast(errorMsg) } else { context.execShareIntent(intent) } } abstract suspend fun createIntent( context: Context, data: ByteArray ): Intent? } abstract class SchemeAction : IAction { abstract val scheme: String open val buildRegex: Boolean = false final override fun canExecuteOn(data: ByteArray): Boolean { val content = String(data) return if (buildRegex) { content.matches( """^$scheme://[\w\W]+$""".toRegex( RegexOption.IGNORE_CASE ) ) } else { content.startsWith("$scheme://", ignoreCase = true) } } final override suspend fun execute(context: Context, data: ByteArray) { context.openUrl(String(data)) } }
mit
9eb9a720960fcb8d545033e06e509b02
23.309091
72
0.737472
3.663014
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/output/oracles/SupportedCodeOracle.kt
1
6217
package org.evomaster.core.output.oracles import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.Lines import org.evomaster.core.output.OutputFormat import org.evomaster.core.output.ObjectGenerator import org.evomaster.core.problem.rest.HttpVerb import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.problem.rest.RestIndividual import org.evomaster.core.search.EvaluatedAction import org.evomaster.core.search.EvaluatedIndividual import org.slf4j.Logger import org.slf4j.LoggerFactory /** * The [SupportedCodeOracle] class generates an expectation and writes it to the code. * * A comparison is made between the status code of the [RestCallResult] and the supported return codes as defined * by the schema. If the actual code is not supported by the schema, the relevant expectation is generated and added * to the code. */ class SupportedCodeOracle : ImplementedOracle() { private val variableName = "sco" private lateinit var objectGenerator: ObjectGenerator private val log: Logger = LoggerFactory.getLogger(SupportedCodeOracle::class.java) override fun variableDeclaration(lines: Lines, format: OutputFormat) { lines.add("/**") lines.add("* $variableName - supported code oracle - checking that the response status code is among those supported according to the schema") lines.add("*/") when{ format.isJava() -> lines.add("private static boolean $variableName = false;") format.isKotlin() -> lines.add("private val $variableName = false") format.isJavaScript() -> lines.add("const $variableName = false;") } } override fun addExpectations(call: RestCallAction, lines: Lines, res: HttpWsCallResult, name: String, format: OutputFormat) { //if(!supportedCode(call, res)){ if(generatesExpectation(call, res)){ // The code is not among supported codes, so an expectation will be generated //val actualCode = res.getStatusCode() ?: 0 //lines.add(".that($oracleName, Arrays.asList(${getSupportedCode(call)}).contains($actualCode))") val supportedCodes = getSupportedCode(call) //BMR: this will be a problem if supportedCode contains both codes and default... if(supportedCodes.contains("0")){ lines.add("// WARNING: the code list seems to contain an unsupported code (0 is not a valid HTTP code). This could indicate a problem with the schema. The issue has been logged.") supportedCodes.remove("0") LoggingUtil.uniqueWarn(log, "The list of supported codes appears to contain an unsupported code (0 is not a valid HTTP code). This could indicate a problem with the schema.") //TODO: if a need arises for more involved checks, refactor this } val supportedCode = supportedCodes.joinToString(", ") if(supportedCode.equals("")){ lines.add("/*") lines.add(" Note: No supported codes appear to be defined. https://swagger.io/docs/specification/describing-responses/.") lines.add(" This is somewhat unexpected, so the code below is likely to lead to a failed expectation") lines.add("*/") when { format.isJava() -> lines.add(".that($variableName, Arrays.asList().contains($name.extract().statusCode()))") format.isKotlin() -> lines.add(".that($variableName, listOf<Int>().contains($name.extract().statusCode()))") } } //TODO: check here if supported code contains 0 (or maybe check against a list of "acceptable" codes else when { format.isJava() -> lines.add(".that($variableName, Arrays.asList($supportedCode).contains($name.extract().statusCode()))") format.isKotlin() -> lines.add(".that($variableName, listOf<Int>($supportedCode).contains($name.extract().statusCode()))") } } } fun supportedCode(call: RestCallAction, res: HttpWsCallResult): Boolean{ val code = res.getStatusCode().toString() val validCodes = getSupportedCode(call) return (validCodes.contains(code) || validCodes.contains("default")) } fun getSupportedCode(call: RestCallAction): MutableSet<String>{ val verb = call.verb val path = retrievePath(objectGenerator, call) val result = when (verb){ HttpVerb.GET -> path?.get HttpVerb.POST -> path?.post HttpVerb.PUT -> path?.put HttpVerb.DELETE -> path?.delete HttpVerb.PATCH -> path?.patch HttpVerb.HEAD -> path?.head HttpVerb.OPTIONS -> path?.options HttpVerb.TRACE -> path?.trace else -> null } return result?.responses?.keys ?: mutableSetOf() } override fun setObjectGenerator(gen: ObjectGenerator){ objectGenerator = gen } override fun generatesExpectation(call: RestCallAction, res: HttpWsCallResult): Boolean { if(this::objectGenerator.isInitialized){ return !supportedCode(call, res) } return false } override fun generatesExpectation(individual: EvaluatedIndividual<*>): Boolean { if(individual.individual !is RestIndividual) return false if(!this::objectGenerator.isInitialized) return false val gens = individual.evaluatedMainActions().any { !supportedCode(it.action as RestCallAction, it.result as HttpWsCallResult) } return gens } override fun selectForClustering(action: EvaluatedAction): Boolean { return if (action.result is HttpWsCallResult && action.action is RestCallAction &&this::objectGenerator.isInitialized && !(action.action as RestCallAction).skipOracleChecks ) !supportedCode(action.action as RestCallAction, action.result as HttpWsCallResult) else false } override fun getName(): String { return "CodeOracle" } }
lgpl-3.0
c1f6f00edf29f76526bcf4ebf2232dab
46.830769
195
0.658195
4.83437
false
false
false
false
square/sqldelight
sqldelight-gradle-plugin/src/test/kotlin/com/squareup/sqldelight/tests/GenerateSchemaTest.kt
1
2570
package com.squareup.sqldelight.tests import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Test import java.io.File class GenerateSchemaTest { @Test fun `schema file generates correctly`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `generateSchema task can run twice`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() val lastModified = schemaFile.lastModified() while (System.currentTimeMillis() - lastModified <= 1000) { // last modified only updates per second. Thread.yield() } GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "--rerun-tasks", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() assertThat(schemaFile.lastModified()).isNotEqualTo(lastModified) schemaFile.delete() } @Test fun `schema file generates correctly with existing sqm files`() { val fixtureRoot = File("src/test/schema-file-sqm") GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/3.db") assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `schema file generates correctly for android`() { val fixtureRoot = File("src/test/schema-file-android") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateDebugDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() } }
apache-2.0
7cd1887c6417a71d1985f6e204c156ad
28.54023
92
0.685214
4.438687
false
true
false
false
KotlinPorts/pooled-client
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/column/ByteArrayEncoderDecoder.kt
2
3956
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.column import com.github.mauricio.async.db.column.ColumnEncoderDecoder import com.github.mauricio.async.db.postgresql.exceptions.ByteArrayFormatNotSupportedException import com.github.mauricio.async.db.util.HexCodec import java.nio.ByteBuffer import io.netty.buffer.ByteBuf import mu.KLogging object ByteArrayEncoderDecoder : ColumnEncoderDecoder, KLogging() { val HexStart = "\\x" val HexStartChars = HexStart.toCharArray() override fun decode(value: String): ByteArray = if (value.startsWith(HexStart)) { HexCodec.decode(value, 2) } else { // Default encoding is 'escape' // Size the buffer to the length of the string, the data can't be bigger val buffer = ByteBuffer.allocate(value.length) val ci = value.iterator() while (ci.hasNext()) { val c = ci.next(); when (c) { '\\' -> { val c2 = getCharOrDie(ci) when (c2) { '\\' -> buffer.put('\\'.toByte()) else -> { val firstDigit = c2 val secondDigit = getCharOrDie(ci) val thirdDigit = getCharOrDie(ci) // Must always be in triplets buffer.put( Integer.decode( String(charArrayOf('0', firstDigit, secondDigit, thirdDigit))).toByte()) } } } else -> buffer.put(c.toByte()) } } buffer.flip() val finalArray = ByteArray(buffer.remaining()) buffer.get(finalArray) finalArray } /** * This is required since {@link Iterator#next} when {@linke Iterator#hasNext} is false is undefined. * @param ci the iterator source of the data * @return the next character * @throws IllegalArgumentException if there is no next character */ private fun getCharOrDie(ci: Iterator<Char>): Char = if (ci.hasNext()) { ci.next() } else { throw IllegalArgumentException("Expected escape sequence character, found nothing") } override fun encode(value: Any): String { val array = when (value) { is ByteArray -> value is ByteBuffer -> if (value.hasArray()) value.array() else { val arr = ByteArray(value.remaining()) value.get(arr) arr } is ByteBuf -> if (value.hasArray()) value.array() else { val arr = ByteArray(value.readableBytes()) value.getBytes(0, arr) arr } else -> throw IllegalArgumentException("not a byte array/ByteBuffer/ByteArray") } return HexCodec.encode(array, HexStartChars) } }
apache-2.0
0b2e4b28d9060b9fd6b6a321857a4afd
35.953271
124
0.529084
5.175393
false
false
false
false
jayrave/falkon
falkon-dao-extn/src/test/kotlin/com/jayrave/falkon/dao/DaoForDeletesIntegrationTests.kt
1
5114
package com.jayrave.falkon.dao import com.jayrave.falkon.dao.testLib.TableForTest import org.assertj.core.api.Assertions.assertThat import org.junit.Test class DaoForDeletesIntegrationTests : BaseClassForIntegrationTests() { @Test fun testDeletionOfSingleModel() { val modelToBeDeleted = buildModelForTest(1) insertModelUsingInsertBuilder(table, modelToBeDeleted) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 7) val numberOfRowsDeleted = table.dao.delete(modelToBeDeleted) assertAbsenceOf(table, modelToBeDeleted) assertThat(numberOfRowsDeleted).isEqualTo(1) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(7) } @Test fun testDeletionOfVarargModels() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(66, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(99, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.delete(deletedModel1, deletedModel2) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testDeletionOfModelIterable() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(55, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(77, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.delete(listOf(deletedModel1, deletedModel2)) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testSingleModelDeleteById() { val modelToBeDeleted = buildModelForTest(1) insertModelUsingInsertBuilder(table, modelToBeDeleted) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 7) val numberOfRowsDeleted = table.dao.deleteById( TableForTest.Id(modelToBeDeleted.id1, modelToBeDeleted.id2) ) assertAbsenceOf(table, modelToBeDeleted) assertThat(numberOfRowsDeleted).isEqualTo(1) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(7) } @Test fun testVarargModelsDeleteById() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(66, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(99, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.deleteById( TableForTest.Id(deletedModel1.id1, deletedModel1.id2), TableForTest.Id(deletedModel2.id1, deletedModel2.id2) ) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testModelIterableDeleteById() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(55, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(77, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.deleteById(listOf( TableForTest.Id(deletedModel1.id1, deletedModel1.id2), TableForTest.Id(deletedModel2.id1, deletedModel2.id2) )) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testDeletionHasNoEffectIfModelDoesNotExist() { insertAdditionalRandomModelsUsingInsertBuilder(table, count = 8) val nonExistingModel = buildModelForTest(1) val numberOfRowsDeleted = table.dao.delete(nonExistingModel) assertAbsenceOf(table, nonExistingModel) assertThat(numberOfRowsDeleted).isEqualTo(0) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(8) } }
apache-2.0
146e27078a67283017b36d0f94b72465
40.585366
95
0.739734
4.700368
false
true
false
false
Takhion/android-extras-delegates
library/src/main/java/me/eugeniomarletti/extras/bundle/Utils.kt
1
3596
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.extras.bundle import android.os.Bundle import me.eugeniomarletti.extras.putExtra import me.eugeniomarletti.extras.readBoolean import me.eugeniomarletti.extras.readByte import me.eugeniomarletti.extras.readChar import me.eugeniomarletti.extras.readDouble import me.eugeniomarletti.extras.readFloat import me.eugeniomarletti.extras.readInt import me.eugeniomarletti.extras.readLong import me.eugeniomarletti.extras.readShort @PublishedApi internal inline fun getBoolean( receiver: Bundle, name: String ) = receiver.readBoolean( Bundle::containsKey, Bundle::getBoolean, name) @PublishedApi internal inline fun getInt( receiver: Bundle, name: String ) = receiver.readInt( Bundle::containsKey, Bundle::getInt, name) @PublishedApi internal inline fun getLong( receiver: Bundle, name: String ) = receiver.readLong( Bundle::containsKey, Bundle::getLong, name) @PublishedApi internal inline fun getShort( receiver: Bundle, name: String ) = receiver.readShort( Bundle::containsKey, Bundle::getShort, name) @PublishedApi internal inline fun getDouble( receiver: Bundle, name: String ) = receiver.readDouble( Bundle::containsKey, Bundle::getDouble, name) @PublishedApi internal inline fun getFloat( receiver: Bundle, name: String ) = receiver.readFloat( Bundle::containsKey, Bundle::getFloat, name) @PublishedApi internal inline fun getChar( receiver: Bundle, name: String ) = receiver.readChar( Bundle::containsKey, Bundle::getChar, name) @PublishedApi internal inline fun getByte( receiver: Bundle, name: String ) = receiver.readByte( Bundle::containsKey, Bundle::getByte, name) @PublishedApi internal inline fun putBoolean( receiver: Bundle, name: String, value: Boolean? ) = receiver.putExtra( Bundle::remove, Bundle::putBoolean, name, value) @PublishedApi internal inline fun putInt( receiver: Bundle, name: String, value: Int? ) = receiver.putExtra( Bundle::remove, Bundle::putInt, name, value) @PublishedApi internal inline fun putLong( receiver: Bundle, name: String, value: Long? ) = receiver.putExtra( Bundle::remove, Bundle::putLong, name, value) @PublishedApi internal inline fun putShort( receiver: Bundle, name: String, value: Short? ) = receiver.putExtra( Bundle::remove, Bundle::putShort, name, value) @PublishedApi internal inline fun putDouble( receiver: Bundle, name: String, value: Double? ) = receiver.putExtra( Bundle::remove, Bundle::putDouble, name, value) @PublishedApi internal inline fun putFloat( receiver: Bundle, name: String, value: Float? ) = receiver.putExtra( Bundle::remove, Bundle::putFloat, name, value) @PublishedApi internal inline fun putChar( receiver: Bundle, name: String, value: Char? ) = receiver.putExtra( Bundle::remove, Bundle::putChar, name, value) @PublishedApi internal inline fun putByte( receiver: Bundle, name: String, value: Byte? ) = receiver.putExtra( Bundle::remove, Bundle::putByte, name, value)
mit
295752f76398b789d07b5ade94983d1c
19.666667
45
0.637097
4.230588
false
false
false
false
PaleoCrafter/BitReplicator
src/main/kotlin/de/mineformers/bitreplicator/client/gui/SlotFontRenderer.kt
1
2190
package de.mineformers.bitreplicator.client.gui import de.mineformers.bitreplicator.client.getLocale import net.minecraft.client.Minecraft import net.minecraft.client.gui.FontRenderer import net.minecraft.util.ResourceLocation import java.text.NumberFormat class SlotFontRenderer : FontRenderer( Minecraft.getMinecraft().gameSettings, ResourceLocation("textures/font/ascii.png"), Minecraft.getMinecraft().textureManager, false) { private val alternative = Minecraft.getMinecraft().fontRendererObj var bypass = false override fun getStringWidth(text: String): Int { val displayedText = convertText(text) if (displayedText != text) { val oldFlag = alternative.unicodeFlag alternative.unicodeFlag = true val result = alternative.getStringWidth(displayedText) alternative.unicodeFlag = oldFlag return result } return super.getStringWidth(displayedText) } override fun drawString(text: String, x: Float, y: Float, color: Int, dropShadow: Boolean): Int { val displayedText = convertText(text) if (displayedText != text) { val oldFlag = alternative.unicodeFlag alternative.unicodeFlag = true val result = alternative.drawString(displayedText, x, y, color, dropShadow) alternative.unicodeFlag = oldFlag return result } return super.drawString(displayedText, x, y, color, dropShadow) } private fun convertText(text: String): String { if (bypass) return text if (!text.matches(Regex("\\d+"))) return text val number = text.toInt() if (number < 100) return text if (number < 1000) return " " + text val numberFormat = NumberFormat.getInstance(Minecraft.getMinecraft().getLocale()) numberFormat.maximumFractionDigits = 0 if (number < 100000) { numberFormat.maximumFractionDigits = 1 } if (number < 10000) { numberFormat.maximumFractionDigits = 2 } return numberFormat.format(number / 1000.0) + "k" } }
mit
f148fc29fbcc8ce258177eeb1161a67e
35.516667
101
0.647945
4.771242
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/ChangePolarParameter.kt
1
2044
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.scene.history import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource import uk.co.nickthecoder.tickle.editor.resources.ModificationType import uk.co.nickthecoder.tickle.editor.scene.SceneEditor import uk.co.nickthecoder.tickle.editor.util.PolarParameter class ChangePolarParameter( private val actorResource: DesignActorResource, private val parameter: PolarParameter, private var newDegrees: Double, private var newMagnitude: Double ) : Change { private val oldDegrees = parameter.angle ?: 0.0 private val oldMagnitude = parameter.magnitude ?: 0.0 override fun redo(sceneEditor: SceneEditor) { parameter.angle = newDegrees parameter.magnitude = newMagnitude sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE) } override fun undo(sceneEditor: SceneEditor) { parameter.angle = oldDegrees parameter.magnitude = oldMagnitude sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE) } override fun mergeWith(other: Change): Boolean { if (other is ChangePolarParameter && other.actorResource == actorResource) { other.newDegrees = newDegrees other.newMagnitude = newMagnitude return true } return false } }
gpl-3.0
d9555e1899f70ca72ebc245005916167
34.241379
84
0.743151
4.522124
false
false
false
false
droibit/quickly
app/src/main/kotlin/com/droibit/quickly/main/apps/AppsModule.kt
1
916
package com.droibit.quickly.main.apps import com.droibit.quickly.main.mainModule import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.instance import com.github.salomonbrys.kodein.provider import com.github.salomonbrys.kodein.singleton import rx.subscriptions.CompositeSubscription fun appsModule(view: AppsContract.View, navigator: AppsContract.Navigator) = Kodein.Module { import(mainModule()) bind<AppsContract.View>() with instance(view) bind<AppsContract.Navigator>() with instance(navigator) bind<AppsContract.Presenter>() with provider { AppsPresenter( view = instance(), navigator = instance(), loadTask = instance(), showSettingsTask = instance(), subscriptions = instance() ) } bind<CompositeSubscription>() with singleton { CompositeSubscription() } }
apache-2.0
057bf543f7a776f7b97f85bcc207e945
31.75
92
0.700873
4.898396
false
false
false
false
MoonCheesez/sstannouncer
sstannouncer/app/src/main/java/sst/com/anouncements/feed/ui/FeedAdapter.kt
1
1684
package sst.com.anouncements.feed.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import android.widget.TextView import sst.com.anouncements.R import sst.com.anouncements.feed.model.Entry class FeedAdapter( private var entries: List<Entry>, private val onItemClickListener: (Entry) -> Unit ) : RecyclerView.Adapter<FeedAdapter.FeedViewHolder>() { class FeedViewHolder(feedView: ViewGroup) : RecyclerView.ViewHolder(feedView) { val titleTextView: TextView = feedView.findViewById(R.id.title_text_view) val excerptTextView: TextView = feedView.findViewById(R.id.excerpt_text_view) val dateTextView: TextView = feedView.findViewById(R.id.date_text_view) val layoutView : View = feedView.findViewById(R.id.feed_item_layout) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FeedViewHolder { val feedView = LayoutInflater.from(parent.context) .inflate(R.layout.recyclerview_feed_item, parent, false) as ViewGroup return FeedViewHolder(feedView) } override fun onBindViewHolder(holder: FeedViewHolder, position: Int) { val entry: Entry = entries[position] holder.titleTextView.text = entry.title holder.excerptTextView.text = entry.contentWithoutHTML holder.dateTextView.text = entry.relativePublishedDate holder.layoutView.setOnClickListener { onItemClickListener(entry) } } override fun getItemCount() = entries.size fun setEntries(newEntries: List<Entry>) { entries = newEntries notifyDataSetChanged() } }
mit
b5fc4cf051cd34c9674becf1533a0ed5
36.444444
87
0.736342
4.362694
false
false
false
false
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/DependencyExtensions.kt
1
857
/* * Copyright 2018 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.commons import io.michaelrocks.lightsaber.processor.model.Dependency fun Dependency.boxed(): Dependency { val boxedType = type.boxed() return if (boxedType === type) this else copy(type = boxedType) }
apache-2.0
d72b76f98d04c98b7add3a41fd8ac87f
34.708333
75
0.751459
4.242574
false
false
false
false
shiraji/permissions-dispatcher-plugin
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/data/AndroidGradleVersion.kt
1
583
package com.github.shiraji.permissionsdispatcherplugin.data class AndroidGradleVersion(versionText: String) { private var major: Int private var minor: Int init { try { major = versionText.substringBefore(".").toInt() minor = versionText.substring(versionText.indexOf(".") + 1, versionText.lastIndexOf(".")).toInt() } catch (e: NumberFormatException) { major = -1 minor = -1 } } fun isHigherThan2_2() = major > 2 || major == 2 && minor >= 2 fun isValid() = major >= 0 && minor >= 0 }
apache-2.0
f91acc9059670ab24aa9ca9bf4b4c9cb
28.2
109
0.586621
4.318519
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/other/CircleTransformation.kt
1
1319
package org.miaowo.miaowo.other import android.graphics.Bitmap import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.Shader import com.squareup.picasso.Transformation /** * Picasso 加载剪裁圆形 * Created by luqin on 17-4-11. */ class CircleTransformation : Transformation { override fun transform(source: Bitmap): Bitmap { val width = source.width val height = source.height val size = Math.min(width, height) val r = (size / 2).toFloat() val dw = (width - size).toFloat() val dh = (height - size).toFloat() val result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(result) val paint = Paint() val shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true paint.isDither = true if (dw != 0f || dh != 0f) { val centerMatrix = Matrix() centerMatrix.setTranslate(-dw / 2, -dh / 2) canvas.matrix = centerMatrix } canvas.drawCircle(r, r, r, paint) source.recycle() return result } override fun key() = "toCircle()" }
apache-2.0
462bb53524ff14c41010a357443d73f8
26.229167
87
0.635807
4.021538
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/db/entities/EventToPerson.kt
1
539
package be.digitalia.fosdem.db.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index @Entity(tableName = EventToPerson.TABLE_NAME, primaryKeys = ["event_id", "person_id"], indices = [Index(value = ["person_id"], name = "event_person_person_id_idx")]) class EventToPerson( @ColumnInfo(name = "event_id") val eventId: Long, @ColumnInfo(name = "person_id") val personId: Long ) { companion object { const val TABLE_NAME = "events_persons" } }
apache-2.0
7f58dc196ddd06e6cf1460c1eac2203a
29
86
0.664193
3.666667
false
false
false
false
jsargent7089/android
src/main/java/com/nextcloud/client/jobs/OfflineSyncWork.kt
1
6237
/* * Nextcloud Android client application * * @author Mario Danic * @author Chris Narkiewicz * Copyright (C) 2018 Mario Danic * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.content.ContentResolver import android.content.Context import android.os.Build import android.os.PowerManager import android.os.PowerManager.WakeLock import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.device.PowerManagementService import com.nextcloud.client.network.ConnectivityService import com.owncloud.android.MainApp import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.files.CheckEtagRemoteOperation import com.owncloud.android.operations.SynchronizeFileOperation import com.owncloud.android.utils.FileStorageUtils import java.io.File @Suppress("LongParameterList") // Legacy code class OfflineSyncWork constructor( private val context: Context, params: WorkerParameters, private val contentResolver: ContentResolver, private val userAccountManager: UserAccountManager, private val connectivityService: ConnectivityService, private val powerManagementService: PowerManagementService ) : Worker(context, params) { companion object { const val TAG = "OfflineSyncJob" private const val WAKELOCK_TAG_SEPARATION = ":" private const val WAKELOCK_ACQUISITION_TIMEOUT_MS = 10L * 60L * 1000L } override fun doWork(): Result { var wakeLock: WakeLock? = null if (!powerManagementService.isPowerSavingEnabled && !connectivityService.isInternetWalled) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager val wakeLockTag = MainApp.getAuthority() + WAKELOCK_TAG_SEPARATION + TAG wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag) wakeLock.acquire(WAKELOCK_ACQUISITION_TIMEOUT_MS) } val users = userAccountManager.allUsers for (user in users) { val storageManager = FileDataStorageManager(user.toPlatformAccount(), contentResolver) val ocRoot = storageManager.getFileByPath(OCFile.ROOT_PATH) if (ocRoot.storagePath == null) { break } recursive(File(ocRoot.storagePath), storageManager, user) } wakeLock?.release() } return Result.success() } @Suppress("ReturnCount", "ComplexMethod") // legacy code private fun recursive(folder: File, storageManager: FileDataStorageManager, user: User) { val downloadFolder = FileStorageUtils.getSavePath(user.accountName) val folderName = folder.absolutePath.replaceFirst(downloadFolder.toRegex(), "") + OCFile.PATH_SEPARATOR Log_OC.d(TAG, "$folderName: enter") // exit if (folder.listFiles() == null) { return } val ocFolder = storageManager.getFileByPath(folderName) Log_OC.d(TAG, folderName + ": currentEtag: " + ocFolder.etag) // check for etag change, if false, skip val checkEtagOperation = CheckEtagRemoteOperation(ocFolder.encryptedFileName, ocFolder.etagOnServer) val result = checkEtagOperation.execute(user.toPlatformAccount(), context) when (result.code) { ResultCode.ETAG_UNCHANGED -> { Log_OC.d(TAG, "$folderName: eTag unchanged") return } ResultCode.FILE_NOT_FOUND -> { val removalResult = storageManager.removeFolder(ocFolder, true, true) if (!removalResult) { Log_OC.e(TAG, "removal of " + ocFolder.storagePath + " failed: file not found") } return } ResultCode.ETAG_CHANGED -> Log_OC.d(TAG, "$folderName: eTag changed") else -> Log_OC.d(TAG, "$folderName: eTag changed") } // iterate over downloaded files val files = folder.listFiles { obj: File -> obj.isFile } if (files != null) { for (file in files) { val ocFile = storageManager.getFileByLocalPath(file.path) val synchronizeFileOperation = SynchronizeFileOperation(ocFile.remotePath, user, true, context) synchronizeFileOperation.execute(storageManager, context) } } // recursive into folder val subfolders = folder.listFiles { obj: File -> obj.isDirectory } if (subfolders != null) { for (subfolder in subfolders) { recursive(subfolder, storageManager, user) } } // update eTag @Suppress("TooGenericExceptionCaught") // legacy code try { val updatedEtag = result.data[0] as String ocFolder.etagOnServer = updatedEtag storageManager.saveFile(ocFolder) } catch (e: Exception) { Log_OC.e(TAG, "Failed to update etag on " + folder.absolutePath, e) } } }
gpl-2.0
06cfe7ffa9cc496db47d9f31beaf728e
42.615385
111
0.665865
4.721423
false
false
false
false
DUCodeWars/TournamentFramework
src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/NotificationPacketSer.kt
2
1096
package org.DUCodeWars.framework.server.net.packets.notifications import com.google.gson.JsonObject import org.DUCodeWars.framework.server.net.packets.JsonSerialiser import org.DUCodeWars.framework.server.net.packets.PacketSer import org.DUCodeWars.framework.server.net.packets.Request abstract class NotificationPacketSer<I : NotificationRequest>(action: String) : PacketSer<I, NotificationResponse>( action) { final override val resSer = NotificationResSer() } class NotificationResSer : JsonSerialiser<NotificationResponse>() { override fun ser(packet: NotificationResponse): JsonObject { val json = JsonObject() json.addProperty("received", 1) return json } override fun deserialise(json: JsonObject): NotificationResponse { val received = json["received"].asInt return if (received == 1) { val action = json["action"].asString!! NotificationResponse(action) } else { throw InvalidResponseException("Notification Response contained received = $received") } } }
mit
e59c6832dcbaec99951d712217f10319
35.566667
115
0.712591
4.871111
false
false
false
false
PizzaGames/emulio
core/src/main/com/github/emulio/ui/screens/dialogs/MainMenuDialog.kt
1
6841
package com.github.emulio.ui.screens.dialogs import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.List import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.github.emulio.Emulio import com.github.emulio.model.config.InputConfig import com.github.emulio.ui.screens.* import com.github.emulio.ui.screens.wizard.PlatformWizardScreen import com.github.emulio.utils.translate import mu.KotlinLogging val logger = KotlinLogging.logger { } class MainMenuDialog(emulio: Emulio, private val backCallback: () -> EmulioScreen, screen: EmulioScreen, private val stg: Stage = screen.stage) : EmulioDialog("Main Menu".translate(), emulio, "main-menu") { // we need to cache this font! private val mainFont = FreeTypeFontGenerator(Gdx.files.internal("fonts/RopaSans-Regular.ttf")).generateFont(FreeTypeFontGenerator.FreeTypeFontParameter().apply { size = 40 color = Color.WHITE }) private val listView: List<String> private val listScrollPane: ScrollPane private val menuItems = mapOf( "Scraper".translate() to { closeDialog(true) InfoDialog("Not yet implemented", "Not yet implemented", emulio).show(stg) }, "General Settings".translate() to { closeDialog(true) InfoDialog("Not yet implemented", "Not yet implemented", emulio).show(stg) }, "Input settings".translate() to { closeDialog(true) screen.switchScreen(InputConfigScreen(emulio, backCallback)) }, "Platform Config".translate() to { closeDialog(true) YesNoDialog("Platform Config".translate(), """ The platforms can be edited/configured using a Wizard or editing manually. """.trimIndent().translate(), emulio, "Proceed to Wizard".translate(), "Edit Manually".translate(), cancelCallback = { screen.launchPlatformConfigEditor() screen.showReloadConfirmation() }, confirmCallback = { screen.switchScreen(PlatformWizardScreen(emulio, backCallback)) }).show(stg) }, "Restart Emulio".translate() to { screen.showReloadConfirmation() }, "Quit Emulio".translate() to { showExitConfirmation(emulio, stg) } ) init { val title = titleLabel.text titleLabel.remove() titleTable.reset() titleTable.add(Label(title, emulio.skin, "title").apply { color.a = 0.8f }) listView = List<String>(List.ListStyle().apply { font = mainFont fontColorSelected = Color.WHITE fontColorUnselected = Color(0x878787FF.toInt()) val selectorTexture = createColorTexture(0x878787FF.toInt()) selection = TextureRegionDrawable(TextureRegion(selectorTexture)) }).apply { menuItems.keys.forEach { items.add(it) } width = screenWidth / 2 height = 100f addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { performClick() } }) selectedIndex = 0 } contentTable.reset() listScrollPane = ScrollPane(listView, ScrollPane.ScrollPaneStyle()).apply { setFlickScroll(true) setScrollBarPositions(false, true) setScrollingDisabled(true, false) setSmoothScrolling(true) isTransform = true setSize(screenWidth / 2, screenHeight / 2) } contentTable.add(listScrollPane).fillX().expandX().maxHeight(screenHeight / 2).minWidth(screenWidth / 2) } private var lastSelected: Int = -1 private fun performClick() { if (lastSelected == listView.selectedIndex) { performSelectItem() } lastSelected = listView.selectedIndex } private fun performSelectItem() { closeDialog() menuItems[listView.selected]!!.invoke() } private fun selectNext(amount: Int = 1) { val nextIndex = listView.selectedIndex + amount if (amount < 0) { if (nextIndex < 0) { listView.selectedIndex = listView.items.size + amount } else { listView.selectedIndex = nextIndex } } if (amount > 0) { if (nextIndex >= listView.items.size) { listView.selectedIndex = 0 } else { listView.selectedIndex = nextIndex } } lastSelected = listView.selectedIndex checkVisible(nextIndex) } private fun checkVisible(index: Int) { val itemHeight = listView.itemHeight val selectionY = index * itemHeight val selectionY2 = selectionY + itemHeight val minItemsVisible = itemHeight * 5 val itemsPerView = listScrollPane.height / itemHeight if (listView.selectedIndex > (menuItems.size - itemsPerView)) { listScrollPane.scrollY = listView.height - listScrollPane.height return } if (listView.selectedIndex == 0) { listScrollPane.scrollY = 0f return } if ((selectionY2 + minItemsVisible) > listScrollPane.height) { listScrollPane.scrollY = (selectionY2 - listScrollPane.height) + minItemsVisible } val minScrollY = Math.max(selectionY - minItemsVisible, 0f) if (minScrollY < listScrollPane.scrollY) { listScrollPane.scrollY = minScrollY } } override fun onDownButton(input: InputConfig) { selectNext(1) } override fun onUpButton(input: InputConfig) { selectNext(-1) } override fun onPageDownButton(input: InputConfig) { selectNext(5) } override fun onPageUpButton(input: InputConfig) { selectNext(-5) } override fun onConfirmButton(input: InputConfig) { performSelectItem() } override fun onCancelButton(input: InputConfig) { closeDialog() } }
gpl-3.0
864cdc88cbf7bda54d91bac0fdc64588
30.242009
206
0.604151
4.889921
false
true
false
false
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/main/notifications/FastHubNotificationDialog.kt
1
2677
package com.fastaccess.ui.modules.main.notifications import android.os.Bundle import androidx.fragment.app.FragmentManager import android.text.Html import android.view.View import butterknife.OnClick import com.fastaccess.R import com.fastaccess.data.dao.model.AbstractFastHubNotification.NotificationType import com.fastaccess.data.dao.model.FastHubNotification import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.helper.PrefGetter import com.fastaccess.ui.base.BaseDialogFragment import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import kotlinx.android.synthetic.main.dialog_guide_layout.* /** * Created by Kosh on 17.11.17. */ class FastHubNotificationDialog : BaseDialogFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { init { suppressAnimation = true isCancelable = false } private val model by lazy { arguments?.getParcelable<FastHubNotification>(BundleConstant.ITEM) } @OnClick(R.id.cancel) fun onCancel() { dismiss() } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { model?.let { title?.text = it.title description?.text = Html.fromHtml(it.body) it.isRead = true FastHubNotification.update(it) } ?: dismiss() } override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun fragmentLayout(): Int = R.layout.dialog_guide_layout companion object { @JvmStatic private val TAG = FastHubNotificationDialog::class.java.simpleName fun newInstance(model: FastHubNotification): FastHubNotificationDialog { val fragment = FastHubNotificationDialog() fragment.arguments = Bundler.start() .put(BundleConstant.ITEM, model) .end() return fragment } fun show(fragmentManager: FragmentManager, model: FastHubNotification? = null) { val notification = model ?: FastHubNotification.getLatest() notification?.let { if (it.type == NotificationType.PROMOTION || it.type == NotificationType.PURCHASE && model == null) { if (PrefGetter.isProEnabled()) { it.isRead = true FastHubNotification.update(it) return } } newInstance(it).show(fragmentManager, TAG) } } fun show(fragmentManager: FragmentManager) { show(fragmentManager, null) } } }
gpl-3.0
5273ca143e1facd99bf9637ae8b2ceb1
33.779221
117
0.658199
4.858439
false
false
false
false
anthologist/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/activities/EditActivity.kt
1
9446
package com.simplemobiletools.gallery.activities import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat import android.graphics.Point import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.OTG_PATH import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE import com.simplemobiletools.commons.helpers.REAL_FILE_PATH import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.gallery.R import com.simplemobiletools.gallery.dialogs.ResizeDialog import com.simplemobiletools.gallery.dialogs.SaveAsDialog import com.simplemobiletools.gallery.extensions.openEditor import com.theartofdev.edmodo.cropper.CropImageView import kotlinx.android.synthetic.main.view_crop_image.* import java.io.* class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener { private val ASPECT_X = "aspectX" private val ASPECT_Y = "aspectY" private val CROP = "crop" private lateinit var uri: Uri private lateinit var saveUri: Uri private var resizeWidth = 0 private var resizeHeight = 0 private var isCropIntent = false private var isEditingWithThirdParty = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.view_crop_image) handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { initEditActivity() } else { toast(R.string.no_storage_permissions) finish() } } } private fun initEditActivity() { if (intent.data == null) { toast(R.string.invalid_image_path) finish() return } uri = intent.data if (uri.scheme != "file" && uri.scheme != "content") { toast(R.string.unknown_file_location) finish() return } if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { val realPath = intent.extras.getString(REAL_FILE_PATH) uri = when { realPath.startsWith(OTG_PATH) -> Uri.parse(realPath) realPath.startsWith("file:/") -> Uri.parse(realPath) else -> Uri.fromFile(File(realPath)) } } else { (getRealPathFromURI(uri))?.apply { uri = Uri.fromFile(File(this)) } } saveUri = when { intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri else -> uri } isCropIntent = intent.extras?.get(CROP) == "true" crop_image_view.apply { setOnCropImageCompleteListener(this@EditActivity) setImageUriAsync(uri) if (isCropIntent && shouldCropSquare()) setFixedAspectRatio(true) } } override fun onResume() { super.onResume() isEditingWithThirdParty = false } override fun onStop() { super.onStop() if (isEditingWithThirdParty) { finish() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_editor, menu) menu.findItem(R.id.resize).isVisible = !isCropIntent return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.save_as -> crop_image_view.getCroppedImageAsync() R.id.rotate -> crop_image_view.rotateImage(90) R.id.resize -> resizeImage() R.id.flip_horizontally -> flipImage(true) R.id.flip_vertically -> flipImage(false) R.id.edit -> editWith() else -> return super.onOptionsItemSelected(item) } return true } private fun resizeImage() { val point = getAreaSize() if (point == null) { toast(R.string.unknown_error_occurred) return } ResizeDialog(this, point) { resizeWidth = it.x resizeHeight = it.y crop_image_view.getCroppedImageAsync() } } private fun shouldCropSquare(): Boolean { val extras = intent.extras return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) { extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y) } else { false } } private fun getAreaSize(): Point? { val rect = crop_image_view.cropRect ?: return null val rotation = crop_image_view.rotatedDegrees return if (rotation == 0 || rotation == 180) { Point(rect.width(), rect.height()) } else { Point(rect.height(), rect.width()) } } override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) { if (result.error == null) { if (isCropIntent) { if (saveUri.scheme == "file") { saveBitmapToFile(result.bitmap, saveUri.path) } else { var inputStream: InputStream? = null var outputStream: OutputStream? = null try { val stream = ByteArrayOutputStream() result.bitmap.compress(CompressFormat.JPEG, 100, stream) inputStream = ByteArrayInputStream(stream.toByteArray()) outputStream = contentResolver.openOutputStream(saveUri) inputStream.copyTo(outputStream) } finally { inputStream?.close() outputStream?.close() } Intent().apply { addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) setResult(RESULT_OK, this) } finish() } } else if (saveUri.scheme == "file") { SaveAsDialog(this, saveUri.path, true) { saveBitmapToFile(result.bitmap, it) } } else if (saveUri.scheme == "content") { var newPath = applicationContext.getRealPathFromURI(saveUri) ?: "" var shouldAppendFilename = true if (newPath.isEmpty()) { val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "" if (filename.isNotEmpty()) { val path = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) intent.getStringExtra(REAL_FILE_PATH).getParentPath() else internalStoragePath newPath = "$path/$filename" shouldAppendFilename = false } } if (newPath.isEmpty()) { newPath = "$internalStoragePath/${getCurrentFormattedDateTime()}.${saveUri.toString().getFilenameExtension()}" shouldAppendFilename = false } SaveAsDialog(this, newPath, shouldAppendFilename) { saveBitmapToFile(result.bitmap, it) } } else { toast(R.string.unknown_file_location) } } else { toast("${getString(R.string.image_editing_failed)}: ${result.error.message}") } } private fun saveBitmapToFile(bitmap: Bitmap, path: String) { try { Thread { val file = File(path) val fileDirItem = FileDirItem(path, path.getFilenameFromPath()) getFileOutputStream(fileDirItem, true) { if (it != null) { saveBitmap(file, bitmap, it) } else { toast(R.string.image_editing_failed) } } }.start() } catch (e: Exception) { showErrorToast(e) } catch (e: OutOfMemoryError) { toast(R.string.out_of_memory_error) } } private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream) { toast(R.string.saving) if (resizeWidth > 0 && resizeHeight > 0) { val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false) resized.compress(file.absolutePath.getCompressionFormat(), 90, out) } else { bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out) } setResult(Activity.RESULT_OK, intent) scanFinalPath(file.absolutePath) out.close() } private fun flipImage(horizontally: Boolean) { if (horizontally) { crop_image_view.flipImageHorizontally() } else { crop_image_view.flipImageVertically() } } private fun editWith() { openEditor(uri.toString()) isEditingWithThirdParty = true } private fun scanFinalPath(path: String) { scanPath(path) { setResult(Activity.RESULT_OK, intent) toast(R.string.file_saved) finish() } } }
apache-2.0
774397fd67e463a21b43f7733196d78c
34.115242
169
0.5686
4.807125
false
false
false
false
diyaakanakry/Diyaa
Priorites.kt
1
224
/* Operations rules| Priorites rules 1- () 2- ^ 3- *, / 4- +, - 5- = */ fun main(args:Array<String>){ var n1:Int=10 var n2:Int=10 var n3:Int=5 var sum:Int? sum=(n1+n2)*n3-3; print("sum:$sum" ) }
unlicense
eedc516ee56db6de06d31ac9d28f138a
9.714286
33
0.513393
2.217822
false
false
false
false
ModerateFish/component
framework/src/main/java/com/thornbirds/frameworkext/component/page/BasePage.kt
1
924
package com.thornbirds.frameworkext.component.page import android.view.View import android.view.ViewGroup import com.thornbirds.component.ControllerView /** * @author YangLi [email protected] */ abstract class BasePage<VIEW : View, CONTROLLER : BasePageController>( parentView: ViewGroup, controller: CONTROLLER ) : ControllerView<VIEW, CONTROLLER>(parentView, controller) { override fun startView() { super.startView() val contentView = ensureContentView if (contentView.parent == null) { mParentView.addView(contentView) } contentView.visibility = View.VISIBLE } override fun stopView() { super.stopView() ensureContentView.visibility = View.GONE } override fun release() { super.release() mParentView.removeView(ensureContentView) } fun onBackPressed(): Boolean { return false } }
apache-2.0
d65cf8cb33f047cf475bb5e51a9d4298
24
70
0.675325
4.597015
false
false
false
false
jabbink/PokemonGoAPI
src/main/kotlin/ink/abb/pogo/api/cache/MapPokemon.kt
1
3550
package ink.abb.pogo.api.cache import POGOProtos.Enums.PokemonIdOuterClass import POGOProtos.Map.Fort.FortDataOuterClass import POGOProtos.Map.Pokemon.MapPokemonOuterClass import POGOProtos.Map.Pokemon.WildPokemonOuterClass import ink.abb.pogo.api.PoGoApi class MapPokemon { val encounterKind: EncounterKind val spawnPointId: String val encounterId: Long val pokemonId: PokemonIdOuterClass.PokemonId val pokemonIdValue: Int val expirationTimestampMs: Long val latitude: Double val longitude: Double val poGoApi: PoGoApi val valid: Boolean get() = expirationTimestampMs == -1L || poGoApi.currentTimeMillis() < expirationTimestampMs constructor(poGoApi: PoGoApi, proto: MapPokemonOuterClass.MapPokemonOrBuilder) { this.encounterKind = EncounterKind.NORMAL this.spawnPointId = proto.spawnPointId this.encounterId = proto.encounterId this.pokemonId = proto.pokemonId this.pokemonIdValue = proto.pokemonIdValue this.expirationTimestampMs = proto.expirationTimestampMs this.latitude = proto.latitude this.longitude = proto.longitude this.poGoApi = poGoApi } constructor(poGoApi: PoGoApi, proto: WildPokemonOuterClass.WildPokemonOrBuilder) { this.encounterKind = EncounterKind.NORMAL this.spawnPointId = proto.spawnPointId this.encounterId = proto.encounterId this.pokemonId = proto.pokemonData.pokemonId this.pokemonIdValue = proto.pokemonData.pokemonIdValue this.expirationTimestampMs = proto.timeTillHiddenMs.toLong() this.latitude = proto.latitude this.longitude = proto.longitude this.poGoApi = poGoApi } constructor(poGoApi: PoGoApi, proto: FortDataOuterClass.FortDataOrBuilder) { this.spawnPointId = proto.lureInfo.fortId this.encounterId = proto.lureInfo.encounterId this.pokemonId = proto.lureInfo.activePokemonId this.pokemonIdValue = proto.lureInfo.activePokemonIdValue this.expirationTimestampMs = proto.lureInfo .lureExpiresTimestampMs this.latitude = proto.latitude this.longitude = proto.longitude this.encounterKind = EncounterKind.DISK this.poGoApi = poGoApi } enum class EncounterKind { NORMAL, DISK } override fun toString(): String { return "MapPokemon(encounterKind=$encounterKind, spawnPointId='$spawnPointId', encounterId=$encounterId, pokemonId=$pokemonId, pokemonIdValue=$pokemonIdValue, expirationTimestampMs=$expirationTimestampMs, latitude=$latitude, longitude=$longitude)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is MapPokemon) return false if (encounterKind != other.encounterKind) return false if (spawnPointId != other.spawnPointId) return false if (encounterId != other.encounterId) return false if (pokemonIdValue != other.pokemonIdValue) return false if (latitude != other.latitude) return false if (longitude != other.longitude) return false return true } override fun hashCode(): Int { var result = encounterKind.hashCode() result = 31 * result + spawnPointId.hashCode() result = 31 * result + encounterId.hashCode() result = 31 * result + pokemonIdValue result = 31 * result + latitude.hashCode() result = 31 * result + longitude.hashCode() return result } }
gpl-3.0
6b26e75bcb4b00196d283ce962a25eb9
33.144231
255
0.699718
4.628422
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/testing/PyNoseTest.kt
1
2683
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing import com.intellij.execution.Executor import com.intellij.execution.configurations.RunProfileState import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.jetbrains.python.PyNames import com.jetbrains.python.PythonHelper import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant /** * Nose runner */ class PyNoseTestSettingsEditor(configuration: PyAbstractTestConfiguration) : PyAbstractTestSettingsEditor( PyTestSharedForm.create(configuration, PyTestSharedForm.CustomOption( PyNoseTestConfiguration::regexPattern.name, PyRunTargetVariant.PATH))) class PyNoseTestExecutionEnvironment(configuration: PyNoseTestConfiguration, environment: ExecutionEnvironment) : PyTestExecutionEnvironment<PyNoseTestConfiguration>(configuration, environment) { override fun getRunner() = PythonHelper.NOSE } class PyNoseTestConfiguration(project: Project, factory: PyNoseTestFactory) : PyAbstractTestConfiguration(project, factory, PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.NOSE_TEST)) { @ConfigField var regexPattern = "" override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? = PyNoseTestExecutionEnvironment(this, environment) override fun createConfigurationEditor(): SettingsEditor<PyAbstractTestConfiguration> = PyNoseTestSettingsEditor(this) override fun getCustomRawArgumentsString(forRerun: Boolean): String = when { regexPattern.isEmpty() -> "" else -> "-m $regexPattern" } override fun isFrameworkInstalled() = VFSTestFrameworkListener.getInstance().isTestFrameworkInstalled(sdk, PyNames.NOSE_TEST) } object PyNoseTestFactory : PyAbstractTestFactory<PyNoseTestConfiguration>() { override fun createTemplateConfiguration(project: Project) = PyNoseTestConfiguration(project, this) override fun getName(): String = PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.NOSE_TEST) }
apache-2.0
8f105c47bbc8eeafaae62afe865bd556
37.898551
127
0.805069
4.887067
false
true
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/players/PlayerItemView.kt
1
1788
package com.garpr.android.features.players import android.content.Context import android.graphics.Typeface import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import com.garpr.android.R import com.garpr.android.data.models.AbsPlayer import kotlinx.android.synthetic.main.item_player.view.* class PlayerItemView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs), View.OnClickListener, View.OnLongClickListener { private var _player: AbsPlayer? = null val player: AbsPlayer get() = checkNotNull(_player) private val originalBackground: Drawable? = background @ColorInt private val cardBackgroundColor: Int = ContextCompat.getColor(context, R.color.card_background) var listeners: Listeners? = null interface Listeners { fun onClick(v: PlayerItemView) fun onLongClick(v: PlayerItemView) } init { setOnClickListener(this) setOnLongClickListener(this) } override fun onClick(v: View) { listeners?.onClick(this) } override fun onLongClick(v: View): Boolean { listeners?.onLongClick(this) return true } fun setContent(player: AbsPlayer, isIdentity: Boolean) { _player = player name.text = player.name if (isIdentity) { name.typeface = Typeface.DEFAULT_BOLD setBackgroundColor(cardBackgroundColor) } else { name.typeface = Typeface.DEFAULT ViewCompat.setBackground(this, originalBackground) } } }
unlicense
4775c09e3b0f10ffd03d869b93748967
26.507692
99
0.702461
4.717678
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/project/workspace/impl/CargoProjectWorkspaceServiceImpl.kt
1
11324
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.workspace.impl import com.intellij.execution.ExecutionException import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.progress.BackgroundTaskQueue import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.EmptyRunnable import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.Alarm import org.jetbrains.annotations.TestOnly import org.rust.cargo.project.settings.RustProjectSettingsService import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.settings.toolchain import org.rust.cargo.project.workspace.* import org.rust.cargo.project.workspace.CargoProjectWorkspaceService.UpdateResult import org.rust.cargo.toolchain.RustToolchain import org.rust.cargo.util.cargoProjectRoot import org.rust.ide.notifications.showBalloon import org.rust.ide.utils.checkReadAccessAllowed import org.rust.ide.utils.checkWriteAccessAllowed import org.rust.utils.pathAsPath import java.nio.file.Path private val LOG = Logger.getInstance(CargoProjectWorkspaceServiceImpl::class.java) /** * [CargoWorkspace] of a real project consists of two pieces: * * * Project structure reported by `cargo metadata` * * Standard library, usually retrieved from rustup. * * This two piece may vary independently. [WorkspaceMerger] * merges them into a single [CargoWorkspace]. It's executed * only on EDT, so you may think of it as an actor maintaining * a two bits of state. */ private class WorkspaceMerger(private val updateCallback: () -> Unit) { private var rawWorkspace: CargoWorkspace? = null private var stdlib: StandardLibrary? = null fun setStdlib(lib: StandardLibrary) { checkWriteAccessAllowed() stdlib = lib update() } fun setRawWorkspace(workspace: CargoWorkspace) { checkWriteAccessAllowed() rawWorkspace = workspace update() } var workspace: CargoWorkspace? = null get() { checkReadAccessAllowed() return field } private set(value) { field = value } private fun update() { val raw = rawWorkspace if (raw == null) { workspace = null return } workspace = raw.withStdlib(stdlib?.crates.orEmpty()) updateCallback() } } class CargoProjectWorkspaceServiceImpl(private val module: Module) : CargoProjectWorkspaceService { // First updates go through [debouncer] to be properly throttled, // and then via [taskQueue] to be serialized (it should be safe to execute // several Cargo's concurrently, but let's avoid that) private val debouncer = Debouncer(delayMillis = 1000, parentDisposable = module) private val taskQueue = BackgroundTaskQueue(module.project, "Cargo update") private val workspaceMerger = WorkspaceMerger { ProjectRootManagerEx.getInstanceEx(module.project).makeRootsChange(EmptyRunnable.getInstance(), false, true) } init { fun refreshStdlib() { val projectDirectory = module.cargoProjectRoot?.pathAsPath ?: return val rustup = module.project.toolchain?.rustup(projectDirectory) if (rustup != null) { taskQueue.run(SetupRustStdlibTask(module, rustup, { runWriteAction { workspaceMerger.setStdlib(it) } })) } else { ApplicationManager.getApplication().invokeLater { val lib = StandardLibrary.fromPath(module.project.rustSettings.explicitPathToStdlib ?: "") if (lib != null) { runWriteAction { workspaceMerger.setStdlib(lib) } } } } } with(module.messageBus.connect()) { subscribe(VirtualFileManager.VFS_CHANGES, CargoTomlWatcher(fun() { if (!module.project.rustSettings.autoUpdateEnabled) return val toolchain = module.project.toolchain ?: return requestUpdate(toolchain) })) subscribe(RustProjectSettingsService.TOOLCHAIN_TOPIC, object : RustProjectSettingsService.ToolchainListener { override fun toolchainChanged() { val toolchain = module.project.toolchain if (toolchain != null) { requestUpdate(toolchain) { refreshStdlib() } } } }) } refreshStdlib() val toolchain = module.project.toolchain if (toolchain != null) { requestImmediateUpdate(toolchain) { result -> when (result) { is UpdateResult.Err -> module.project.showBalloon( "Project '${module.name}' failed to update.<br> ${result.error.message}", NotificationType.ERROR ) is UpdateResult.Ok -> { val outsider = result.workspace.packages .filter { it.origin == PackageOrigin.WORKSPACE } .mapNotNull { it.contentRoot } .find { it !in module.moduleContentScope } if (outsider != null) { module.project.showBalloon( "Workspace member ${outsider.presentableUrl} is outside of IDE project, " + "please open the root of the workspace.", NotificationType.WARNING ) } } } } } } /** * Requests to updates Rust libraries asynchronously. Consecutive requests are coalesced. * * Works in two phases. First `cargo metadata` is executed on the background thread. Then, * the actual Library update happens on the event dispatch thread. */ override fun requestUpdate(toolchain: RustToolchain) = requestUpdate(toolchain, null) override fun requestImmediateUpdate(toolchain: RustToolchain, afterCommit: (UpdateResult) -> Unit) = requestUpdate(toolchain, afterCommit) override fun syncUpdate(toolchain: RustToolchain) { taskQueue.run(UpdateTask(toolchain, module.cargoProjectRoot!!.pathAsPath, null)) val projectDirectory = module.cargoProjectRoot?.pathAsPath ?: return val rustup = module.project.toolchain?.rustup(projectDirectory) ?: return taskQueue.run(SetupRustStdlibTask(module, rustup, { runWriteAction { workspaceMerger.setStdlib(it) } })) } private fun requestUpdate(toolchain: RustToolchain, afterCommit: ((UpdateResult) -> Unit)?) { val contentRoot = module.cargoProjectRoot ?: return debouncer.submit({ taskQueue.run(UpdateTask(toolchain, contentRoot.pathAsPath, afterCommit)) }, immediately = afterCommit != null) } /** * Delivers latest cached project-description instance * * NOTA BENE: [CargoProjectWorkspaceService] is rather low-level abstraction around, `Cargo.toml`-backed projects * mapping underpinning state of the `Cargo.toml` workspace _transparently_, i.e. it doesn't provide * any facade atop of the latter insulating itself from inconsistencies in the underlying layer. For * example, [CargoProjectWorkspaceService] wouldn't be able to provide a valid [CargoWorkspace] instance * until the `Cargo.toml` becomes sound */ override val workspace: CargoWorkspace? get() = workspaceMerger.workspace private fun commitUpdate(r: UpdateResult) { ApplicationManager.getApplication().assertIsDispatchThread() if (module.isDisposed) return if (r is UpdateResult.Ok) { runWriteAction { workspaceMerger.setRawWorkspace(r.workspace) } } } private inner class UpdateTask( private val toolchain: RustToolchain, private val projectDirectory: Path, private val afterCommit: ((UpdateResult) -> Unit)? = null ) : Task.Backgroundable(module.project, "Updating cargo") { private var result: UpdateResult? = null override fun run(indicator: ProgressIndicator) { if (module.isDisposed) return LOG.info("Cargo project update started") indicator.isIndeterminate = true if (!toolchain.looksLikeValidToolchain()) { result = UpdateResult.Err(ExecutionException("Invalid toolchain ${toolchain.presentableLocation}")) return } val cargo = toolchain.cargo(projectDirectory) result = try { val description = cargo.fullProjectDescription(module, object : ProcessAdapter() { override fun onTextAvailable(event: ProcessEvent, outputType: Key<Any>) { val text = event.text.trim { it <= ' ' } if (text.startsWith("Updating") || text.startsWith("Downloading")) { indicator.text = text } } }) UpdateResult.Ok(description) } catch (e: ExecutionException) { UpdateResult.Err(e) } } override fun onSuccess() { val r = requireNotNull(result) commitUpdate(r) afterCommit?.invoke(r) } } @TestOnly fun setRawWorkspace(workspace: CargoWorkspace) { commitUpdate(UpdateResult.Ok(workspace)) } @TestOnly fun setStdlib(libs: StandardLibrary) { workspaceMerger.setStdlib(libs) } } /** * Executes tasks with rate of at most once every [delayMillis]. */ private class Debouncer( private val delayMillis: Int, parentDisposable: Disposable ) { private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable) fun submit(task: () -> Unit, immediately: Boolean) { if (ApplicationManager.getApplication().isUnitTestMode) { check(ApplicationManager.getApplication().isDispatchThread) { "Background activity in unit tests can lead to deadlocks" } task() return } onAlarmThread { alarm.cancelAllRequests() if (immediately) { task() } else { alarm.addRequest(task, delayMillis) } } } private fun onAlarmThread(work: () -> Unit) = alarm.addRequest(work, 0) }
mit
9d31177ff01fda52490a209c97f18ff2
37
121
0.629371
5.204044
false
false
false
false
quarkusio/quarkus
integration-tests/hibernate-orm-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/kotlin/AccessorEntity.kt
1
1101
package io.quarkus.it.panache.kotlin import javax.persistence.Entity import javax.persistence.Transient @Entity open class AccessorEntity : GenericEntity<Int>() { var string: String? = null var c = 0.toChar() var bool = false var b: Byte = 0 get() { getBCalls++ return field } var s: Short = 0 var i: Int = 0 set(value) { setICalls++ field = value } var l: Long get() { throw UnsupportedOperationException("just checking") } set(value) { throw UnsupportedOperationException("just checking") } var f = 0f var d = 0.0 @Transient var trans: Any? = null @Transient var trans2: Any? = null // FIXME: those appear to be mapped by hibernate @Transient var getBCalls = 0 @Transient var setICalls = 0 @Transient var getTransCalls = 0 @Transient var setTransCalls = 0 fun method() { // touch some fields val b2 = b i = 2 t = 1 t2 = 2 } }
apache-2.0
b246c02e02b8c4161bf48c3c73c0913c
18.315789
64
0.541326
4.139098
false
false
false
false
valich/intellij-markdown
src/fileBasedTest/kotlin/org/intellij/markdown/HtmlGeneratorCommonTest.kt
1
6343
package org.intellij.markdown import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor import org.intellij.markdown.flavours.space.SFMFlavourDescriptor import org.intellij.markdown.html.* import kotlin.test.* class HtmlGeneratorCommonTest : HtmlGeneratorTestBase() { override fun getTestDataPath(): String { return getIntellijMarkdownHome() + "/${MARKDOWN_TEST_DATA_PATH}/html" } @Test fun testSimple() { defaultTest() } @Test fun testMarkers() { defaultTest() } @Test fun testTightLooseLists() { defaultTest() } @Test fun testPuppetApache() { defaultTest() } @Test fun testGoPlugin() { defaultTest() } @Test fun testHeaders() { defaultTest() } @Test fun testCodeFence() { defaultTest() } @Test fun testEscaping() { defaultTest() } @Test fun testHtmlBlocks() { defaultTest() } @Test fun testLinks() { defaultTest() } @Test fun testBlockquotes() { defaultTest() } @Test fun testExample226() { defaultTest() } @Test fun testExample2() { defaultTest() } @Test fun testEntities() { defaultTest() } @Test fun testImages() { defaultTest(tagRenderer = HtmlGenerator.DefaultTagRenderer(customizer = { node, _, attributes -> when { node.type == MarkdownElementTypes.IMAGE -> attributes + "style=\"max-width: 100%\"" else -> attributes } }, includeSrcPositions = false)) } @Test fun testRuby17052() { defaultTest() } @Test fun testRuby17351() { defaultTest(GFMFlavourDescriptor()) } @Test fun testBug28() { defaultTest(GFMFlavourDescriptor()) } @Test fun testStrikethrough() { defaultTest(GFMFlavourDescriptor()) } @Test fun testGfmAutolink() { defaultTest(GFMFlavourDescriptor()) } @Test fun testSfmAutolink() { defaultTest(SFMFlavourDescriptor(false)) } @Test fun testGfmTable() { defaultTest(GFMFlavourDescriptor()) } @Test fun testCheckedLists() { defaultTest(GFMFlavourDescriptor()) } @Test fun testGitBook() { defaultTest() } @Test fun testBaseUriHttp() { defaultTest(baseURI = URI("http://example.com/foo/bar.html")) } @Test fun testBaseUriRelativeRoot() { defaultTest(baseURI = URI("/user/repo-name/blob/master")) } @Test fun testBaseUriRelativeNoRoot() { defaultTest(baseURI = URI("user/repo-name/blob/master")) } @Test fun testBaseUriWithBadRelativeUrl() { try { generateHtmlFromFile(baseURI = URI("user/repo-name/blob/master")) } catch (t: Throwable) { fail("Expected to work without exception, got: $t") } } @Test fun testBaseUriWithAnchorLink() { defaultTest(baseURI = URI("/user/repo-name/blob/master")) } @Test fun testBaseUriWithAnchorLinkForceResolve() { defaultTest(baseURI = URI("/user/repo-name/blob/master"), flavour = CommonMarkFlavourDescriptor(absolutizeAnchorLinks = true)) } @Test fun testCustomRenderer() { defaultTest(tagRenderer = object: HtmlGenerator.TagRenderer { override fun openTag(node: ASTNode, tagName: CharSequence, vararg attributes: CharSequence?, autoClose: Boolean): CharSequence { return "OPEN TAG($tagName)\n" } override fun closeTag(tagName: CharSequence): CharSequence { return "CLOSE TAG($tagName)\n" } override fun printHtml(html: CharSequence): CharSequence { return "HTML($html)\n" } }) } @Test fun testXssProtection() { val disallowedLinkMd1 = "[Click me](javascript:alert(document.domain))" val disallowedLinkMd2 = "[Click me](file:///123)" val disallowedLinkMd3 = "[Click me]( VBSCRIPT:alert(1))" val disallowedLinkMd4 = "<VBSCRIPT:alert(1))>" val disallowedLinkHtml = """ <body><p><a href="#">Click me</a></p></body> """.trimIndent() val disallowedAutolinkHtml = """ <body><p><a href="#">VBSCRIPT:alert(1))</a></p></body> """.trimIndent() assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd1)) assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd2)) assertEqualsIgnoreLines(disallowedLinkHtml, generateHtmlFromString(disallowedLinkMd3)) assertEqualsIgnoreLines(disallowedAutolinkHtml, generateHtmlFromString(disallowedLinkMd4)) val disallowedImgMd = "![](javascript:alert('XSS');)" val disallowedImgHtml = """ <body><p><img src="#" alt="" /></p></body> """.trimIndent() assertEqualsIgnoreLines(disallowedImgHtml, generateHtmlFromString(disallowedImgMd)) val allowedImgMd = "![](data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7)" val allowedImgHtml = """ <body><p><img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" alt="" /></p></body> """.trimIndent() assertEqualsIgnoreLines(allowedImgHtml, generateHtmlFromString(allowedImgMd)) } } private fun assertEqualsIgnoreLines(expected: String, actual: String) { return assertEquals(expected.replace("\n", ""), actual.replace("\n", "")) }
apache-2.0
0e496123c99a7a2bd15dc8a47acc515a
26.111111
364
0.634873
3.934864
false
true
false
false
GlimpseFramework/glimpse-framework
api/src/test/kotlin/glimpse/gles/DisposableSpec.kt
1
1203
package glimpse.gles import com.nhaarman.mockito_kotlin.* import glimpse.test.GlimpseSpec class DisposableSpec : GlimpseSpec() { init { "Disposable object" should { "be disposed if registered by calling `Disposables.register()`" { val disposable = disposableMock() Disposables.register(disposable) Disposables.disposeAll() verify(disposable).dispose() } "be disposed if registered by calling `registerDisposable()`" { val disposable = disposableMock() disposable.registerDisposable() Disposables.disposeAll() verify(disposable).dispose() } "not be disposed if not registered" { val disposable = disposableMock() Disposables.disposeAll() verify(disposable, never()).dispose() } "be disposed only once" { val disposable = disposableMock() disposable.registerDisposable() repeat(10) { Disposables.disposeAll() } verify(disposable, times(1)).dispose() } } } fun disposableMock(): Disposable { val disposableMock = mock<DisposableImpl>() doCallRealMethod().`when`(disposableMock).registerDisposable() return disposableMock } open class DisposableImpl : Disposable { override fun dispose() { } } }
apache-2.0
5e32bbfed6ad02cc236bd93893253a9b
24.0625
68
0.706567
3.918567
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/ui/main/MyViewPagerAdapter.kt
1
2204
package im.fdx.v2ex.ui.main import android.content.Context import androidx.core.os.bundleOf import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import im.fdx.v2ex.R import im.fdx.v2ex.myApp import im.fdx.v2ex.pref import im.fdx.v2ex.ui.Tab import im.fdx.v2ex.utils.Keys import im.fdx.v2ex.utils.Keys.PREF_TAB import org.jetbrains.anko.collections.forEachWithIndex import java.util.* /** * Created by fdx on 2015/10/15. * 从MainActivity分离出来. 用了FragmentStatePagerAdapter 替代FragmentPagerAdapter,才可以动态切换Fragment * 弃用了Volley 和 模拟web + okhttp * * todo pageadapter有更新,明天需要完成 */ internal class MyViewPagerAdapter( fm: FragmentManager, private val mContext: Context) : FragmentStatePagerAdapter(fm, BEHAVIOR_SET_USER_VISIBLE_HINT ) { private val mFragments = ArrayList<TopicsFragment>() private val tabList = mutableListOf<Tab>() init { initFragment() } fun initFragment() { tabList.clear() mFragments.clear() var jsonData = pref.getString(PREF_TAB, null) if (jsonData == null) { val tabTitles = mContext.resources.getStringArray(R.array.v2ex_favorite_tab_titles) val tabPaths = mContext.resources.getStringArray(R.array.v2ex_favorite_tab_paths) val list = MutableList(tabTitles.size) { index: Int -> Tab(tabTitles[index], tabPaths[index]) } jsonData = Gson().toJson(list) } val turnsType = object : TypeToken<List<Tab>>() {}.type val list = Gson().fromJson<List<Tab>>(jsonData, turnsType) for (it in list) { if (!myApp.isLogin && it.path == "recent") { continue } mFragments.add(TopicsFragment().apply { arguments = bundleOf(Keys.KEY_TAB to it.path) }) tabList.add(it) } } override fun getItem(position: Int) = mFragments[position] override fun getCount() = tabList.size override fun getPageTitle(position: Int) = tabList[position].title }
apache-2.0
da7ad54af9bd0296296618df64cb5e39
30.441176
105
0.673527
3.83842
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/inbox/InboxRestClient.kt
2
4228
package org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox import android.content.Context import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class InboxRestClient @Inject constructor( dispatcher: Dispatcher, private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchInboxNotes( site: SiteModel, page: Int, pageSize: Int, inboxNoteTypes: Array<String> ): WooPayload<Array<InboxNoteDto>> { val url = WOOCOMMERCE.admin.notes.pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, mapOf( "page" to page.toString(), "per_page" to pageSize.toString(), "type" to inboxNoteTypes.joinToString(separator = ",") ), Array<InboxNoteDto>::class.java ) return when (response) { is JetpackSuccess -> WooPayload(response.data) is JetpackError -> WooPayload(response.error.toWooError()) } } suspend fun markInboxNoteAsActioned( site: SiteModel, inboxNoteId: Long, inboxNoteActionId: Long ): WooPayload<InboxNoteDto> { val url = WOOCOMMERCE.admin.notes.note(inboxNoteId) .action.item(inboxNoteActionId).pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, emptyMap(), InboxNoteDto::class.java ) return when (response) { is JetpackSuccess -> WooPayload(response.data) is JetpackError -> WooPayload(response.error.toWooError()) } } suspend fun deleteNote( site: SiteModel, inboxNoteId: Long ): WooPayload<Unit> { val url = WOOCOMMERCE.admin.notes.delete.note(inboxNoteId).pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( this, site, url, Unit::class.java ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } suspend fun deleteAllNotesForSite( site: SiteModel, page: Int, pageSize: Int, inboxNoteTypes: Array<String> ): WooPayload<Unit> { val url = WOOCOMMERCE.admin.notes.delete.all.pathV4Analytics val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( this, site, url, Array<InboxNoteDto>::class.java, mapOf( "page" to page.toString(), "per_page" to pageSize.toString(), "type" to inboxNoteTypes.joinToString(separator = ",") ) ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } }
gpl-2.0
6eb5f0f162083bb8e2fecbb8b0c3f95f
35.136752
130
0.662725
4.997636
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CommentsFragment.kt
1
2887
package com.boardgamegeek.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.paging.LoadState import androidx.paging.PagingData import androidx.recyclerview.widget.DividerItemDecoration import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentCommentsBinding import com.boardgamegeek.ui.adapter.GameCommentsPagedListAdapter import com.boardgamegeek.ui.viewmodel.GameCommentsViewModel import kotlinx.coroutines.launch class CommentsFragment : Fragment() { private var _binding: FragmentCommentsBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<GameCommentsViewModel>() private val adapter by lazy { GameCommentsPagedListAdapter() } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentCommentsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) binding.recyclerView.adapter = adapter adapter.addLoadStateListener { loadStates -> when (val state = loadStates.refresh) { is LoadState.Loading -> { binding.progressView.show() } is LoadState.NotLoading -> { binding.emptyView.setText(R.string.empty_comments) binding.emptyView.isVisible = adapter.itemCount == 0 binding.recyclerView.isVisible = adapter.itemCount > 0 binding.progressView.hide() } is LoadState.Error -> { binding.emptyView.text = state.error.localizedMessage binding.emptyView.isVisible = true binding.recyclerView.isVisible = false binding.progressView.hide() } } } viewModel.comments.observe(viewLifecycleOwner) { comments -> lifecycleScope.launch { adapter.submitData(comments) binding.recyclerView.isVisible = true } } } override fun onDestroyView() { super.onDestroyView() _binding = null } fun clear() { lifecycleScope.launch { adapter.submitData(PagingData.empty()) } } }
gpl-3.0
b1a1d0f3ad8cef98213232662e2327c4
36.493506
116
0.672671
5.426692
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/coupons/CouponRestClient.kt
2
8291
package org.wordpress.android.fluxc.network.rest.wpcom.wc.coupons import android.content.Context import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.coupon.UpdateCouponRequest import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.API_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class CouponRestClient @Inject constructor( dispatcher: Dispatcher, private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchCoupons( site: SiteModel, page: Int, pageSize: Int, searchQuery: String? = null ): WooPayload<Array<CouponDto>> { val url = WOOCOMMERCE.coupons.pathV3 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( restClient = this, site = site, url = url, params = mutableMapOf<String, String>().apply { put("page", page.toString()) put("per_page", pageSize.toString()) searchQuery?.let { put("search", searchQuery) } }, clazz = Array<CouponDto>::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun fetchCoupon( site: SiteModel, couponId: Long ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun createCoupon( site: SiteModel, request: UpdateCouponRequest ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.pathV3 val params = request.toNetworkRequest() val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun updateCoupon( site: SiteModel, couponId: Long, request: UpdateCouponRequest ): WooPayload<CouponDto> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val params = request.toNetworkRequest() val response = jetpackTunnelGsonRequestBuilder.syncPutRequest( this, site, url, params, CouponDto::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun deleteCoupon( site: SiteModel, couponId: Long, trash: Boolean ): WooPayload<Unit> { val url = WOOCOMMERCE.coupons.id(couponId).pathV3 val response = jetpackTunnelGsonRequestBuilder.syncDeleteRequest( restClient = this, site = site, url = url, clazz = Unit::class.java, params = mapOf("force" to trash.not().toString()) ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(Unit) } } suspend fun fetchCouponsReports( site: SiteModel, couponsIds: LongArray = longArrayOf(), after: Date ): WooPayload<List<CouponReportDto>> { val url = WOOCOMMERCE.reports.coupons.pathV4Analytics val dateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT) val params = mapOf( "after" to dateFormatter.format(after), "coupons" to couponsIds.joinToString(",") ) val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( restClient = this, site = site, url = url, params = params, clazz = Array<CouponReportDto>::class.java ) return when (response) { is JetpackError -> WooPayload(response.error.toWooError()) is JetpackSuccess -> WooPayload(response.data?.toList()) } } suspend fun fetchCouponReport( site: SiteModel, couponId: Long, after: Date ): WooPayload<CouponReportDto> { return fetchCouponsReports( site = site, couponsIds = longArrayOf(couponId), after = after ).let { when { it.isError -> WooPayload(it.error) it.result.isNullOrEmpty() -> WooPayload( WooError(API_ERROR, UNKNOWN, "Empty coupons report response") ) else -> WooPayload(it.result.first()) } } } @Suppress("ComplexMethod") private fun UpdateCouponRequest.toNetworkRequest(): Map<String, Any> { return mutableMapOf<String, Any>().apply { code?.let { put("code", it) } amount?.let { put("amount", it) } discountType?.let { put("discount_type", it) } description?.let { put("description", it) } expiryDate?.let { put("date_expires", it) } minimumAmount?.let { put("minimum_amount", it) } maximumAmount?.let { put("maximum_amount", it) } productIds?.let { put("product_ids", it) } excludedProductIds?.let { put("excluded_product_ids", it) } isShippingFree?.let { put("free_shipping", it) } productCategoryIds?.let { put("product_categories", it) } excludedProductCategoryIds?.let { put("excluded_product_categories", it) } restrictedEmails?.let { put("email_restrictions", it) } isForIndividualUse?.let { put("individual_use", it) } areSaleItemsExcluded?.let { put("exclude_sale_items", it) } // The following fields can have empty value. When updating a Coupon, // the REST API accepts and treats `0` as empty for these fields. put("usage_limit", usageLimit ?: 0) put("usage_limit_per_user", usageLimitPerUser ?: 0) put("limit_usage_to_x_items", limitUsageToXItems ?: 0) } } }
gpl-2.0
5f198688da3588334fd4041519088d8d
34.280851
130
0.607526
4.762206
false
false
false
false
rarnu/deprecated_project
src/main/kotlin/com/rarnu/tophighlight/xposed/Versions.kt
1
3538
package com.rarnu.tophighlight.xposed /** * Created by rarnu on 1/26/17. */ object Versions { // global var inited = false // top highlight color var conversationAdapter = "" var userInfoMethod = "" var topInfoMethod = "" var topInfoField = "" // statusbar immersion var mmFragmentActivity = "" var chatUIActivity = "" var expectImmersionList = arrayListOf<String>() var getAppCompact = "" var getActionBar = "" var dividerId = 0 var actionBarViewId = 0 var customizeActionBar = "" var actionBarContainer = "" // tab var bottomTabView = "" // top mac or reader & etc. var topMacActivity = "" var topReaderActivity = "" var topMacMethod = "" var topMacField = "" var topReaderMethod = "" var topReaderField = "" var topReaderViewId = 0 // settings var settingActivity = "" var settingPreference = "" var settingListField = "" var settingAddMethod = "" // global resource var colorToChange = arrayListOf<Int>() fun initVersion(idx: Int) { when (idx) { 0 -> { // 654 conversationAdapter = "com.tencent.mm.ui.conversation.b" userInfoMethod = "en" topInfoMethod = "j" topInfoField = "oLH" mmFragmentActivity = "com.tencent.mm.ui.MMFragmentActivity" chatUIActivity = "com.tencent.mm.ui.chatting.ChattingUI\$a" // bottomTab bottomTabView = "com.tencent.mm.ui.LauncherUIBottomTabView" // top mac or reader topMacActivity = "com.tencent.mm.ui.d.m" topReaderActivity = "com.tencent.mm.ui.d.o" topMacMethod = "aii" topMacField = "ejD" topReaderMethod = "setVisibility" topReaderField = "view" topReaderViewId = 0x7f101472 // settings settingActivity = "com.tencent.mm.plugin.setting.ui.setting.SettingsAboutSystemUI" settingPreference = "com.tencent.mm.ui.base.preference.Preference" settingListField = "oHs" settingAddMethod = "a" expectImmersionList = arrayListOf( "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyIndexUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyPrepareUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI", "com.tencent.mm.plugin.collect.ui.CollectMainUI", "com.tencent.mm.plugin.offline.ui.WalletOfflineCoinPurseUI", "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyMyRecordUI") // in mmfragmentactivity getAppCompact = "cU" getActionBar = "cV" dividerId = 2131755267 actionBarViewId = 2131755252 // in chatui customizeActionBar = "bIT" actionBarContainer = "oZl" colorToChange = arrayListOf( 2131231135, 2131231148, 2131689968, 2131689977, 2131690035, 2131690068, 2131690069, 2131690072, 2131690082) inited = true } } } }
gpl-3.0
98c1788ee66f6a12d71281706a7e1443
30.04386
98
0.527134
4.565161
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/util/palette/GlobalRegistryPalette.kt
1
1628
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.util.palette import org.lanternpowered.api.catalog.CatalogType import org.lanternpowered.api.util.palette.GlobalPalette import org.lanternpowered.server.registry.InternalCatalogTypeRegistry import java.util.function.Supplier /** * Gets this internal catalog type registry as a [GlobalPalette]. */ fun <T : CatalogType> InternalCatalogTypeRegistry<T>.asPalette(default: () -> T): GlobalPalette<T> = asPalette(Supplier(default)) /** * Gets this internal catalog type registry as a [GlobalPalette]. */ fun <T : CatalogType> InternalCatalogTypeRegistry<T>.asPalette(default: Supplier<out T>): GlobalPalette<T> = GlobalRegistryPalette(this, default) private class GlobalRegistryPalette<T : CatalogType>( private val registry: InternalCatalogTypeRegistry<T>, private val defaultSupplier: Supplier<out T> ) : GlobalPalette<T> { override fun getIdOrAssign(obj: T): Int = this.registry.getId(obj) override fun getId(obj: T): Int = this.registry.getId(obj) override fun get(id: Int): T? = this.registry.get(id) override val default: T get() = this.defaultSupplier.get() override val entries: Collection<T> get() = this.registry.all override val size: Int get() = this.registry.all.size }
mit
86726e67c8adbd0af8e317e1c70df911
33.638298
108
0.722359
3.932367
false
false
false
false
LISTEN-moe/android-app
app/src/main/kotlin/me/echeung/moemoekyun/ui/view/SongList.kt
1
4706
package me.echeung.moemoekyun.ui.view import android.app.Activity import android.text.Editable import android.text.TextWatcher import android.view.MenuItem import android.view.View import android.widget.EditText import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import me.echeung.moemoekyun.R import me.echeung.moemoekyun.adapter.SongsListAdapter import me.echeung.moemoekyun.util.SongActionsUtil import me.echeung.moemoekyun.util.SongSortUtil import me.echeung.moemoekyun.viewmodel.SongListViewModel import org.koin.core.component.KoinComponent import org.koin.core.component.inject import java.lang.ref.WeakReference class SongList( activity: Activity, private val songListViewModel: SongListViewModel, private val songsList: RecyclerView, private val swipeRefreshLayout: SwipeRefreshLayout?, filterView: View, listId: String, private val loadSongs: (adapter: SongsListAdapter) -> Unit, ) : KoinComponent { private val songActionsUtil: SongActionsUtil by inject() private val songSortUtil: SongSortUtil by inject() private val activity: WeakReference<Activity> = WeakReference(activity) private val adapter: SongsListAdapter = SongsListAdapter(activity, listId) init { // List adapter songsList.layoutManager = LinearLayoutManager(activity) songsList.adapter = adapter // Pull to refresh if (swipeRefreshLayout != null) { swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent) swipeRefreshLayout.setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener { this.loadSongs() }) swipeRefreshLayout.isRefreshing = false // Only allow pull to refresh when user is at the top of the list songsList.addOnScrollListener( object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val topRowVerticalPosition = if (songsList.childCount != 0) { songsList.getChildAt(0).top } else { 0 } swipeRefreshLayout.isEnabled = topRowVerticalPosition >= 0 } }, ) } // Filter if (filterView is EditText) { filterView.addTextChangedListener( object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun afterTextChanged(editable: Editable) { handleQuery(editable.toString()) } }, ) } if (filterView is SearchView) { filterView.setOnQueryTextListener( object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { handleQuery(query!!) return true } override fun onQueryTextChange(newText: String?): Boolean { handleQuery(newText!!) return true } }, ) filterView.setOnCloseListener { handleQuery("") true } } } private fun handleQuery(query: String) { val trimmedQuery = query.trim { it <= ' ' }.lowercase() adapter.filter(trimmedQuery) val hasResults = adapter.itemCount != 0 songListViewModel.hasResults = hasResults if (hasResults) { songsList.scrollToPosition(0) } } fun loadSongs() { loadSongs(adapter) } fun showLoading(loading: Boolean) { swipeRefreshLayout?.isRefreshing = loading } fun notifyDataSetChanged() { adapter.notifyDataSetChanged() } fun handleMenuItemClick(item: MenuItem): Boolean { val activityRef = activity.get() ?: return false if (songSortUtil.handleSortMenuItem(item, adapter)) { return true } if (item.itemId == R.id.action_random_request) { adapter.randomRequestSong?.let { songActionsUtil.request(activityRef, it) } return true } return false } }
mit
3c1e6bb79a86897fa05b796a81a69e53
32.375887
110
0.609647
5.421659
false
false
false
false
RoverPlatform/rover-android
core/src/main/kotlin/io/rover/sdk/core/routing/TransientLinkLaunchActivity.kt
1
1524
package io.rover.sdk.core.routing import android.os.Bundle import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import io.rover.sdk.core.Rover import io.rover.sdk.core.logging.log import java.net.URI /** * The intent filter you add for your universal links and `rv-$appname://` deep links should by default * point to this activity. */ open class TransientLinkLaunchActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val rover = Rover.shared if (rover == null) { log.e("A deep or universal link mapped to Rover was opened, but Rover is not initialized. Ignoring.") return } val linkOpen = rover.resolve(LinkOpenInterface::class.java) if (linkOpen == null) { log.e("A deep or universal link mapped to Rover was opened, but LinkOpenInterface is not registered in the Rover container. Ensure ExperiencesAssembler() is in Rover.initialize(). Ignoring.") return } val uri = URI(intent.data.toString()) log.v("Transient link launch activity running for received URI: '${intent.data}'") val intentStack = linkOpen.localIntentForReceived(uri) log.v("Launching stack ${intentStack.size} deep: ${intentStack.joinToString("\n") { it.toString() }}") if (intentStack.isNotEmpty()) ContextCompat.startActivities(this, intentStack.toTypedArray()) finish() } }
apache-2.0
db3dcb0229699f16c67af901af9ba0c3
37.125
203
0.690289
4.366762
false
false
false
false
pie-flavor/Pieconomy
src/main/kotlin/flavor/pie/pieconomy/PieconomyCurrencyRegistryModule.kt
1
1202
package flavor.pie.pieconomy import com.google.common.collect.HashBiMap import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableSet import flavor.pie.kludge.* import org.spongepowered.api.registry.AdditionalCatalogRegistryModule import org.spongepowered.api.registry.RegistrationPhase import org.spongepowered.api.registry.util.DelayedRegistration import org.spongepowered.api.service.economy.Currency import java.util.Optional class PieconomyCurrencyRegistryModule(defaults: Set<Currency>) : AdditionalCatalogRegistryModule<Currency> { val defaults: Set<Currency> val currencies: MutableMap<String, Currency> = HashBiMap.create() init { this.defaults = ImmutableSet.copyOf(defaults) } override fun getById(id: String): Optional<Currency> = currencies[id].optional override fun getAll(): Collection<Currency> = ImmutableList.copyOf(currencies.values) override fun registerAdditionalCatalog(extraCatalog: Currency) { currencies[extraCatalog.id] = extraCatalog } @DelayedRegistration(RegistrationPhase.POST_INIT) override fun registerDefaults() { defaults.forEach { currencies[it.id] = it } } }
mit
69ba3cbfa70e504ad8752ef88a8c6023
34.352941
108
0.781198
4.451852
false
false
false
false
FHannes/intellij-community
plugins/git4idea/src/git4idea/remote/GitConfigureRemotesDialog.kt
12
11183
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.remote import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.sortRepositories import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger 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.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.IDE import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.PROJECT import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Messages.* import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ColoredTableCellRenderer import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.ToolbarDecorator import com.intellij.ui.table.JBTable import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil.DEFAULT_HGAP import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.repo.GitRemote import git4idea.repo.GitRemote.ORIGIN import git4idea.repo.GitRepository import java.awt.Dimension import java.awt.Font import java.util.* import javax.swing.* import javax.swing.table.AbstractTableModel class GitConfigureRemotesDialog(val project: Project, val repositories: Collection<GitRepository>) : DialogWrapper(project, true, getModalityType()) { private val git = service<Git>() private val LOG = logger<GitConfigureRemotesDialog>() private val NAME_COLUMN = 0 private val URL_COLUMN = 1 private val REMOTE_PADDING = 30 private val table = JBTable(RemotesTableModel()) private var nodes = buildNodes(repositories) init { init() title = "Git Remotes" updateTableWidth() } override fun createActions() = arrayOf(okAction) override fun getPreferredFocusedComponent() = table override fun createCenterPanel(): JComponent? { table.selectionModel = DefaultListSelectionModel() table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) table.intercellSpacing = JBUI.emptySize() table.setDefaultRenderer(Any::class.java, MyCellRenderer()) return ToolbarDecorator.createDecorator(table). setAddAction { addRemote() }. setRemoveAction { removeRemote() }. setEditAction { editRemote() }. setEditActionUpdater { isRemoteSelected() }. setRemoveActionUpdater { isRemoteSelected() }. disableUpDownActions().createPanel() } private fun addRemote() { val repository = getSelectedRepo() val proposedName = if (repository.remotes.any { it.name == ORIGIN }) "" else ORIGIN val dialog = GitDefineRemoteDialog(repository, git, proposedName, "") if (dialog.showAndGet()) { runInModalTask("Adding Remote...", repository, "Add Remote", "Couldn't add remote ${dialog.remoteName} '${dialog.remoteUrl}'") { git.addRemote(repository, dialog.remoteName, dialog.remoteUrl) } } } private fun removeRemote() { val remoteNode = getSelectedRemote()!! val remote = remoteNode.remote if (YES == showYesNoDialog(rootPane, "Remove remote ${remote.name} '${getUrl(remote)}'?", "Remove Remote", getQuestionIcon())) { runInModalTask("Removing Remote...", remoteNode.repository, "Remove Remote", "Couldn't remove remote $remote") { git.removeRemote(remoteNode.repository, remote) } } } private fun editRemote() { val remoteNode = getSelectedRemote()!! val remote = remoteNode.remote val repository = remoteNode.repository val oldName = remote.name val oldUrl = getUrl(remote) val dialog = GitDefineRemoteDialog(repository, git, oldName, oldUrl) if (dialog.showAndGet()) { val newRemoteName = dialog.remoteName val newRemoteUrl = dialog.remoteUrl if (newRemoteName == oldName && newRemoteUrl == oldUrl) return runInModalTask("Changing Remote...", repository, "Change Remote", "Couldn't change remote $oldName to $newRemoteName '$newRemoteUrl'") { changeRemote(repository, oldName, oldUrl, newRemoteName, newRemoteUrl) } } } private fun changeRemote(repo: GitRepository, oldName: String, oldUrl: String, newName: String, newUrl: String): GitCommandResult { var result : GitCommandResult? = null if (newName != oldName) { result = git.renameRemote(repo, oldName, newName) if (!result.success()) return result } if (newUrl != oldUrl) { result = git.setRemoteUrl(repo, newName, newUrl) // NB: remote name has just been changed } return result!! // at least one of two has changed } private fun updateTableWidth() { var maxNameWidth = 30 var maxUrlWidth = 250 for (node in nodes) { val fontMetrics = table.getFontMetrics(UIManager.getFont("Table.font").deriveFont(Font.BOLD)) val nameWidth = fontMetrics.stringWidth(node.getPresentableString()) val remote = (node as? RemoteNode)?.remote val urlWidth = if (remote == null) 0 else fontMetrics.stringWidth(getUrl(remote)) if (maxNameWidth < nameWidth) maxNameWidth = nameWidth if (maxUrlWidth < urlWidth) maxUrlWidth = urlWidth } maxNameWidth += REMOTE_PADDING + DEFAULT_HGAP table.columnModel.getColumn(NAME_COLUMN).preferredWidth = maxNameWidth table.columnModel.getColumn(URL_COLUMN).preferredWidth = maxUrlWidth val defaultPreferredHeight = table.rowHeight*(table.rowCount+3) table.preferredScrollableViewportSize = Dimension(maxNameWidth + maxUrlWidth + DEFAULT_HGAP, defaultPreferredHeight) } private fun buildNodes(repositories: Collection<GitRepository>): List<Node> { val nodes = mutableListOf<Node>() for (repository in sortRepositories(repositories)) { if (repositories.size > 1) nodes.add(RepoNode(repository)) for (remote in sortedRemotes(repository)) { nodes.add(RemoteNode(remote, repository)) } } return nodes } private fun sortedRemotes(repository: GitRepository): List<GitRemote> { return repository.remotes.sortedWith(Comparator<GitRemote> { r1, r2 -> if (r1.name == ORIGIN) { if (r2.name == ORIGIN) 0 else -1 } else if (r2.name == ORIGIN) 1 else r1.name.compareTo(r2.name) }) } private fun rebuildTable() { nodes = buildNodes(repositories) (table.model as RemotesTableModel).fireTableDataChanged() } private fun runInModalTask(title: String, repository: GitRepository, errorTitle: String, errorMessage: String, operation: () -> GitCommandResult) { ProgressManager.getInstance().run(object : Task.Modal(project, title, true) { private var result: GitCommandResult? = null override fun run(indicator: ProgressIndicator) { result = operation() repository.update() } override fun onSuccess() { rebuildTable() if (result == null || !result!!.success()) { val errorDetails = if (result == null) "operation was not executed" else result!!.errorOutputAsJoinedString val message = "$errorMessage in $repository:\n$errorDetails" LOG.warn(message) Messages.showErrorDialog(myProject, message, errorTitle) } } }) } private fun getSelectedRepo(): GitRepository { val selectedRow = table.selectedRow if (selectedRow < 0) return sortRepositories(repositories).first() val value = nodes[selectedRow] if (value is RepoNode) return value.repository if (value is RemoteNode) return value.repository throw IllegalStateException("Unexpected selected value: $value") } private fun getSelectedRemote() : RemoteNode? { val selectedRow = table.selectedRow if (selectedRow < 0) return null return nodes[selectedRow] as? RemoteNode } private fun isRemoteSelected() = getSelectedRemote() != null private fun getUrl(remote: GitRemote) = remote.urls.firstOrNull() ?: "" private abstract class Node { abstract fun getPresentableString() : String } private class RepoNode(val repository: GitRepository) : Node() { override fun toString() = repository.presentableUrl override fun getPresentableString() = DvcsUtil.getShortRepositoryName(repository) } private class RemoteNode(val remote: GitRemote, val repository: GitRepository) : Node() { override fun toString() = remote.name override fun getPresentableString() = remote.name } private inner class RemotesTableModel() : AbstractTableModel() { override fun getRowCount() = nodes.size override fun getColumnCount() = 2 override fun getColumnName(column: Int): String { if (column == NAME_COLUMN) return "Name" else return "URL" } override fun getValueAt(rowIndex: Int, columnIndex: Int): Any { val node = nodes[rowIndex] when { columnIndex == NAME_COLUMN -> return node node is RepoNode -> return "" node is RemoteNode -> return getUrl(node.remote) else -> { LOG.error("Unexpected position at row $rowIndex and column $columnIndex") return "" } } } } private inner class MyCellRenderer : ColoredTableCellRenderer() { override fun customizeCellRenderer(table: JTable?, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) { if (value is RepoNode) { append(value.getPresentableString(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) } else if (value is RemoteNode) { if (repositories.size > 1) append("", SimpleTextAttributes.REGULAR_ATTRIBUTES, REMOTE_PADDING, SwingConstants.LEFT) append(value.getPresentableString()) } else if (value is String) { append(value) } border = null } } } private fun getModalityType() = if (Registry.`is`("ide.perProjectModality")) PROJECT else IDE
apache-2.0
7d490b714320d9d0a536fbb0279c6f61
36.780405
133
0.70473
4.483962
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/sync/AddAccountDialog.kt
1
2012
package org.tasks.sync import android.app.Dialog import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.fragment.app.setFragmentResult import com.google.android.material.composethemeadapter.MdcTheme import dagger.hilt.android.AndroidEntryPoint import org.tasks.R import org.tasks.dialogs.DialogBuilder import org.tasks.extensions.Context.openUri import javax.inject.Inject @AndroidEntryPoint class AddAccountDialog : DialogFragment() { @Inject lateinit var dialogBuilder: DialogBuilder private val hasTasksAccount: Boolean get() = arguments?.getBoolean(EXTRA_HAS_TASKS_ACCOUNT) ?: false enum class Platform { TASKS_ORG, GOOGLE_TASKS, MICROSOFT, DAVX5, CALDAV, ETESYNC, DECSYNC_CC } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return dialogBuilder .newDialog() .setTitle(R.string.choose_synchronization_service) .setContent { MdcTheme { org.tasks.compose.AddAccountDialog( hasTasksAccount = hasTasksAccount, selected = this::selected ) } } .setNeutralButton(R.string.help) { _, _ -> activity?.openUri(R.string.help_url_sync) } .setNegativeButton(R.string.cancel, null) .show() } private fun selected(platform: Platform) { setFragmentResult(ADD_ACCOUNT, bundleOf(EXTRA_SELECTED to platform)) dismiss() } companion object { const val ADD_ACCOUNT = "add_account" const val EXTRA_SELECTED = "selected" private const val EXTRA_HAS_TASKS_ACCOUNT = "extra_has_tasks_account" fun newAccountDialog(hasTasksAccount: Boolean) = AddAccountDialog().apply { arguments = bundleOf(EXTRA_HAS_TASKS_ACCOUNT to hasTasksAccount) } } }
gpl-3.0
e2281be8eaa24055a5c6a9f7fd968cbe
29.969231
98
0.640656
4.625287
false
false
false
false
RoyalDev/Fictitious
src/main/kotlin/org/royaldev/fictitious/commands/impl/StopCommand.kt
1
1686
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.royaldev.fictitious.commands.impl import com.google.common.collect.Sets import org.kitteh.irc.client.library.element.User import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent import org.kitteh.irc.client.library.event.helper.ActorEvent import org.royaldev.fictitious.FictitiousBot import org.royaldev.fictitious.games.FictitiousGame import xyz.cardstock.cardstock.commands.BaseCommand import xyz.cardstock.cardstock.commands.CallInfo import xyz.cardstock.cardstock.commands.Command @Command( name = "stop", aliases = arrayOf( "stopgame" ), description = "Stops a game in the channel", usage = "<command>", commandType = BaseCommand.CommandType.CHANNEL ) class StopCommand(val fictitious: FictitiousBot) : BaseCommand() { override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) { if (event !is ChannelMessageEvent) return val game = this.fictitious.gameRegistrar.find(event.channel) if (game == null) { event.actor.sendNotice("There is not a game in this channel!") return } val op = event.channel.getUserModes(event.actor).orElseGet { Sets.newHashSet() }.any { it.char == 'o' } if (!op && game.host != game.getPlayer(event.actor, false)) { event.actor.sendNotice("You are neither an op nor the host.") return } game.stop(FictitiousGame.GameEndCause.COMMAND) } }
mpl-2.0
aa7ea65cfb1a9dc65d09fd9f3f528b64
39.142857
111
0.704033
3.673203
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/TableResults.kt
1
16407
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.table import com.sun.javafx.collections.ImmutableObservableList import com.sun.javafx.scene.control.skin.TableColumnHeader import com.sun.javafx.scene.control.skin.TableViewSkin import com.sun.javafx.scene.control.skin.VirtualFlow import javafx.application.Platform import javafx.collections.transformation.FilteredList import javafx.collections.transformation.SortedList import javafx.geometry.Side import javafx.scene.Node import javafx.scene.control.* import javafx.scene.image.ImageView import javafx.scene.input.KeyEvent import javafx.scene.input.MouseButton import javafx.scene.input.MouseEvent import javafx.util.Callback import uk.co.nickthecoder.paratask.ParaTask import uk.co.nickthecoder.paratask.ParaTaskApp import uk.co.nickthecoder.paratask.gui.DragHelper import uk.co.nickthecoder.paratask.gui.DropHelper import uk.co.nickthecoder.paratask.options.Option import uk.co.nickthecoder.paratask.options.OptionsManager import uk.co.nickthecoder.paratask.options.RowOptionsRunner import uk.co.nickthecoder.paratask.project.AbstractResults import uk.co.nickthecoder.paratask.project.ParataskActions import uk.co.nickthecoder.paratask.project.ResultsTab import uk.co.nickthecoder.paratask.project.ToolPane import uk.co.nickthecoder.paratask.table.filter.RowFilter open class TableResults<R : Any>( final override val tool: TableTool<R>, val list: List<R>, label: String = "Results", val columns: List<Column<R, *>>, val rowFilter: RowFilter<R>? = null, canClose: Boolean = false) : AbstractResults(tool, label, canClose = canClose) { val data = WrappedList(list) val tableView: TableView<WrappedRow<R>> = TableView() override val node = tableView private val codeColumn: TableColumn<WrappedRow<R>, String> = TableColumn("") val runner = RowOptionsRunner<R>(tool) var filteredData: FilteredList<WrappedRow<R>>? = null /** * Used to ensure that the currently selected row is always visible. See move() */ var virtualFlow: VirtualFlow<*>? = null var dropHelper: DropHelper? = null set(v) { field?.cancel() field = v v?.applyTo(tableView) } var dragHelper: DragHelper? = null init { // Find the VitualFlow as soon as the tableView's skin has been set tableView.skinProperty().addListener { _, _, skin -> if (skin is TableViewSkin<*>) { virtualFlow = skin.children.filterIsInstance<VirtualFlow<*>>().firstOrNull() } } } fun selectedRows(): List<R> { return tableView.selectionModel.selectedItems.map { it.row } } override fun attached(resultsTab: ResultsTab, toolPane: ToolPane) { super.attached(resultsTab, toolPane) with(codeColumn) { setCellValueFactory { p -> p.value.codeProperty } isEditable = true setCellFactory({ EditCell(this@TableResults, IdentityConverter()) }) prefWidth = 50.0 } tableView.columns.add(codeColumn) for (column in columns) { if (rowFilter?.filtersColumn(column) == true) { column.graphic = ImageView(ParaTask.imageResource("buttons/filter.png")) } else { column.graphic = null } tableView.columns.add(column) } val sortedList: SortedList<WrappedRow<R>> if (rowFilter == null) { sortedList = SortedList(data) } else { filteredData = FilteredList(data) { rowFilter.accept(it.row) } sortedList = SortedList(filteredData) } sortedList.comparatorProperty().bind(tableView.comparatorProperty()) with(tableView) { items = sortedList isEditable = true selectionModel.selectionMode = SelectionMode.MULTIPLE tableView.addEventFilter(KeyEvent.KEY_PRESSED) { onKeyPressed(it) } rowFactory = Callback { val tableRow = tool.createRow() dragHelper?.applyTo(tableRow) tableRow.setOnMouseClicked { onRowClicked(it, tableRow) } tableRow } } dropHelper?.applyTo(resultsTab) if (rowFilter != null) { tableView.addEventFilter(MouseEvent.MOUSE_PRESSED) { if (it.button == MouseButton.SECONDARY) it.consume() } tableView.addEventFilter(MouseEvent.MOUSE_RELEASED) { tableMouseEvent(it) } } } override fun detaching() { super.detaching() dropHelper?.cancel() } override fun selected() { super.selected() tool.tabDropHelper = dropHelper } override fun deselected() { stopEditing() tool.tabDropHelper = null super.deselected() } fun tableMouseEvent(event: MouseEvent) { if (event.button == MouseButton.SECONDARY) { event.consume() var node: Node? = event.target as Node while (node != null && node !== tableView) { if (node is TableColumnHeader) { changeColumnFilter(node) return } node = node.parent } } } fun changeColumnFilter(tch: TableColumnHeader) { val tchCol = tch.tableColumn val column: Column<R, *>? = if (tchCol is Column<*, *>) { @Suppress("UNCHECKED_CAST") tchCol as Column<R, *> } else { null } rowFilter?.editColumnFilters(column) { Platform.runLater { filteredData?.setPredicate { rowFilter.accept(it.row) } columns.forEach { col -> if (rowFilter.filtersColumn(col)) { col.graphic = ImageView(filterIcon) } else { col.graphic = null } } if (rowFilter.filtersColumn(null)) { codeColumn.graphic = ImageView(filterIcon) } else { codeColumn.graphic = null } } } } fun stopEditing() { tableView.edit(-1, null) } override fun focus() { ParaTaskApp.logFocus("TableResults focus. runLater(...)") Platform.runLater { if (tableView.items.isNotEmpty()) { ParaTaskApp.logFocus("TableResults focus. tableView.requestFocus()") tableView.requestFocus() val index = tableView.selectionModel.focusedIndex if (index < 0) { tableView.selectionModel.clearAndSelect(0) ParaTaskApp.logFocus("TableResults focus. tableView.selectionModel.focus(0)") tableView.selectionModel.focus(0) editOption(0) } else { tableView.selectionModel.select(index) editOption(index) } } } } fun editOption(rowIndex: Int = -1) { val index = if (rowIndex >= 0) rowIndex else tableView.selectionModel.focusedIndex stopEditing() tableView.edit(index, codeColumn) } open fun onRowClicked(event: MouseEvent, tableRow: TableRow<WrappedRow<R>>) { contextMenu.hide() if (tableRow.item != null) { if (event.button == MouseButton.PRIMARY) { when (event.clickCount) { 1 -> { // Edit the tabelRow's option field editOption(tableRow.index) } 2 -> { runner.runDefault(tableRow.item.row) } } } else if (event.button == MouseButton.MIDDLE) { runner.runDefault(tableRow.item.row, newTab = true) } else if (event.button == MouseButton.SECONDARY) { showContextMenu(tableRow, event) } } } fun showContextMenu(node: Node, event: Any) { val rows = tableView.selectionModel.selectedItems.map { it.row } runner.buildContextMenu(contextMenu, rows) if (event is MouseEvent) { contextMenu.show(node, Side.BOTTOM, event.x, 0.0) } else { contextMenu.show(node, Side.BOTTOM, 0.0, 0.0) } } val contextMenu = ContextMenu() /** * Looks for shortcuts for the row-options, and passes control to super if no row-base options were found. * If the option found only matches SOME of the selected rows, then the rows that match will be unselected, * leaving the unmatches rows selected. For example, using a shortcut that has different options for files and * directories, it will only process one half. * The user can then hit the shortcut again to apply the other half. */ override fun checkOptionShortcuts(event: KeyEvent) { val tableRows = tableView.selectionModel.selectedItems if (tableRows.isEmpty()) { return } val topLevelOptions = OptionsManager.getTopLevelOptions(tool.optionsName) topLevelOptions.listFileOptions().forEach { fileOptions -> fileOptions.listOptions().forEach { option -> if (option.isRow) { option.shortcut?.let { shortcut -> if (shortcut.match(event) && fileOptions.acceptRow(tableRows[0].row)) { val acceptedRows = tableRows.filter { fileOptions.acceptRow(it.row) } tableView.selectionModel.clearSelection() tableRows.filter { !acceptedRows.contains(it) }.forEach { tableView.selectionModel.select(it) } runner.runRows(option, acceptedRows.map { it.row }) return } } } } } super.checkOptionShortcuts(event) } open fun onKeyPressed(event: KeyEvent) { if (ParataskActions.PREV_ROW.match(event)) { if (!move(-1)) event.consume() } else if (ParataskActions.NEXT_ROW.match(event)) { if (!move(1)) event.consume() } else if (ParataskActions.SELECT_ROW_UP.match(event)) { if (!move(-1, false)) event.consume() } else if (ParataskActions.SELECT_ROW_DOWN.match(event)) { if (!move(1, false)) event.consume() } else if (ParataskActions.OPTION_RUN.match(event)) { runTableOptions() event.consume() } else if (ParataskActions.OPTION_RUN_NEW_TAB.match(event)) { runTableOptions(newTab = true) event.consume() } else if (ParataskActions.OPTION_PROMPT.match(event)) { runTableOptions(prompt = true) event.consume() } else if (ParataskActions.OPTION_PROMPT_NEW_TAB.match(event)) { runTableOptions(prompt = true, newTab = true) event.consume() } else if (ParataskActions.SELECT_ALL.match(event)) { selectAll() event.consume() } else if (ParataskActions.SELECT_NONE.match(event)) { selectNone() event.consume() } else if (ParataskActions.ESCAPE.match(event)) { event.consume() } } fun move(delta: Int, clearSelection: Boolean = true): Boolean { val row = tableView.selectionModel.focusedIndex + delta if (row < 0 || row >= tableView.items.size) { return false } // We need to run later so the EditCell has a chance to save the textfield to the WrappedRow.code Platform.runLater { if (clearSelection) { tableView.selectionModel.clearSelection() } else { // Copy the code from the old focused row. val code = tableView.items[row - delta].code tableView.items[row].code = code } tableView.selectionModel.select(row) ParaTaskApp.logFocus("TableResults move. tableView.selectionMode.focus(row)") tableView.selectionModel.focus(row) // Ensure the new row is visible virtualFlow?.let { val first = it.firstVisibleCell.index val last = it.lastVisibleCell.index if (row < first || row > last) { it.show(row) } } editOption(row) } return true } fun selectAll() { stopEditing() // We need to run later so the EditCell has a chance to save the textfield to the WrappedRow.code Platform.runLater { val selectedRow = tableView.selectionModel.selectedIndex val code = if (selectedRow >= 0 && selectedRow < tableView.items.count()) tableView.items[selectedRow].code else "" tableView.selectionModel.selectAll() tableView.items.forEach { it.code = code } if (selectedRow >= 0 && selectedRow < tableView.items.count()) { editOption(selectedRow) } } } fun selectNone() { stopEditing() Platform.runLater { val selectedRow = tableView.selectionModel.selectedIndex tableView.selectionModel.clearSelection() tableView.items.forEach { it.code = "" } if (selectedRow >= 0 && selectedRow < tableView.items.count()) { editOption(selectedRow) } } } fun runTableOptions(newTab: Boolean = false, prompt: Boolean = false) { ParaTaskApp.logFocus("TableResults runTableOptions tableView.requestFocus()") // Unfocus from the cell being edited allows it to be committed tableView.requestFocus() Platform.runLater { var foundCode = false val batchOptions = mutableMapOf<Option, MutableList<WrappedRow<R>>>() for (wrappedRow in tableView.items) { val code = wrappedRow.code if (code != "") { foundCode = true val option = OptionsManager.findOptionForRow(code, tool.optionsName, wrappedRow.row) if (option != null) { var list = batchOptions[option] if (list == null) { list = mutableListOf<WrappedRow<R>>() batchOptions.put(option, list) } list.add(wrappedRow) wrappedRow.clearOption() } } } if (batchOptions.isNotEmpty()) { runner.runBatch(batchOptions, newTab = newTab, prompt = prompt) } if (!foundCode) { // Run the "default" option against the current row val rowIndex = tableView.selectionModel.focusedIndex if (rowIndex >= 0) { runner.runDefault(tableView.items[rowIndex].row, newTab = newTab) } } } } companion object { val filterIcon = ParaTask.imageResource("buttons/filter.png") } } class WrappedList<R>(list: List<R>) : ImmutableObservableList<WrappedRow<R>>() { var list = list.map { row: R -> WrappedRow(row) } override fun get(index: Int): WrappedRow<R> = list[index] override val size = list.size }
gpl-3.0
9760938cf2570e169f27760b01bc30dc
33.324268
127
0.58024
4.77781
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/request/ParsingContext.kt
1
1633
package com.github.pgutkowski.kgraphql.request import com.github.pgutkowski.kgraphql.RequestException data class ParsingContext( val fullString : String, val tokens: List<String>, val fragments: Document.Fragments, private var index : Int = 0, var nestedBrackets: Int = 0, var nestedParenthesis: Int = 0 ) { fun index() = index fun next(delta: Int = 1) { index += delta } fun currentToken() = tokens[index] fun currentTokenOrNull() = tokens.getOrNull(index) fun peekToken(delta: Int = 1) = tokens.getOrNull(index + delta) fun traverseObject(): List<String> { val subTokens = subTokens(tokens, index, "{", "}") next(subTokens.size + 1) return subTokens } fun traverseArguments(): List<String> { val subTokens = subTokens(tokens, index, "(", ")") next(subTokens.size + 1) return subTokens } private fun subTokens(allTokens: List<String>, startIndex: Int, openingToken: String, closingToken: String): List<String> { val tokens = allTokens.subList(startIndex, allTokens.size) var nestedLevel = 0 tokens.forEachIndexed { index, token -> when (token) { openingToken -> nestedLevel++ closingToken -> nestedLevel-- } if (nestedLevel == 0) return tokens.subList(1, index) } throw RequestException("Couldn't find matching closing token") } fun getFullStringIndex(tokenIndex : Int = index) : Int { //TODO: Provide reliable index return tokenIndex } }
mit
b782e15be8bdb3fc14b18401cbf35cfb
29.259259
127
0.612982
4.498623
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorCategory.kt
1
3125
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.schema.GraphQLNonNull import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategory import net.nemerosa.ontrack.extension.indicators.model.IndicatorTypeService import net.nemerosa.ontrack.extension.indicators.ui.ProjectIndicatorType import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.graphql.support.stringField import org.springframework.stereotype.Component @Component class GQLTypeIndicatorCategory( private val indicatorType: GQLTypeProjectIndicatorType, private val indicatorSource: GQLTypeIndicatorSource, private val indicatorTypeService: IndicatorTypeService, private val indicatorCategoryReportType: GQLTypeIndicatorCategoryReport, private val indicatorReportingService: GQLIndicatorReportingService, private val fieldContributors: List<GQLFieldContributor> ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Indicator category") // Core fields .stringField("id", "Indicator category ID") .stringField("name", "Indicator category name") .stringField("deprecated", "Indicator category deprecation reason if any") // Source .field { it.name(IndicatorCategory::source.name) .description("Source for this category") .type(indicatorSource.typeRef) } // List of types in this category .field { it.name("types") .description("List of indicator types belonging to this category.") .type(listType(indicatorType.typeRef)) .dataFetcher { env -> val category = env.getSource<IndicatorCategory>() indicatorTypeService.findByCategory(category).map { ProjectIndicatorType(it) } } } // Reporting for this category .field { it.name("report") .description("Reporting the indicators for the types in this category") .type(GraphQLNonNull(indicatorCategoryReportType.typeRef)) .arguments(indicatorReportingService.arguments) .dataFetcher { env -> val category = env.getSource<IndicatorCategory>() indicatorCategoryReportType.report(category, env) } } // Links .fields(IndicatorCategory::class.java.graphQLFieldContributions(fieldContributors)) // OK .build() override fun getTypeName(): String = INDICATOR_CATEGORY companion object { val INDICATOR_CATEGORY: String = IndicatorCategory::class.java.simpleName } }
mit
0aea0fb0b6b455f3d76ffee35ccc7abf
42.416667
99
0.688
5.332765
false
false
false
false
alpha-cross/ararat
library/src/main/java/org/akop/ararat/widget/Zoomer.kt
2
3428
/* * Copyright 2013 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 org.akop.ararat.widget import android.content.Context import android.os.SystemClock import android.view.animation.DecelerateInterpolator /** * A simple class that animates double-touch zoom gestures. Functionally similar to a [ ]. */ @Suppress("unused", "MemberVisibilityCanBePrivate") class Zoomer(context: Context) { /** * The interpolator, used for making zooms animate 'naturally.' */ private val interpolator = DecelerateInterpolator() /** * The total animation duration for a zoom. */ private val animationDurationMillis: Int = context.resources.getInteger( android.R.integer.config_shortAnimTime) /** * Returns whether the zoomer has finished zooming. * * @return True if the zoomer has finished zooming, false otherwise. */ var isFinished = true private set /** * The current zoom value; computed by [.computeZoom]. * * @see android.widget.Scroller.getCurrX */ var currZoom: Float = 0f private set /** * The time the zoom started, computed using [SystemClock.elapsedRealtime]. */ private var startRTC: Long = 0 /** * The destination zoom factor. */ private var endZoom: Float = 0f /** * Forces the zoom finished state to the given value. Unlike [.abortAnimation], the * current zoom value isn't set to the ending value. * * @see android.widget.Scroller.forceFinished */ fun forceFinished(finished: Boolean) { isFinished = finished } /** * Aborts the animation, setting the current zoom value to the ending value. * * @see android.widget.Scroller.abortAnimation */ fun abortAnimation() { isFinished = true currZoom = endZoom } /** * Starts a zoom from 1.0 to (1.0 + endZoom). That is, to zoom from 100% to 125%, endZoom should * by 0.25f. * * @see android.widget.Scroller.startScroll */ fun startZoom(endZoom: Float) { startRTC = SystemClock.elapsedRealtime() this.endZoom = endZoom isFinished = false currZoom = 1f } /** * Computes the current zoom level, returning true if the zoom is still active and false if the * zoom has finished. * * @see android.widget.Scroller.computeScrollOffset */ fun computeZoom(): Boolean { if (isFinished) { return false } val tRTC = SystemClock.elapsedRealtime() - startRTC if (tRTC >= animationDurationMillis) { isFinished = true currZoom = endZoom return false } val t = tRTC * 1f / animationDurationMillis currZoom = endZoom * interpolator.getInterpolation(t) return true } }
mit
ae9e0df660dc1f0dab68fb3f4e45e188
27.098361
100
0.643816
4.451948
false
false
false
false
bihe/mydms-java
Api/src/main/kotlin/net/binggl/mydms/features/filestore/amazon/S3FileService.kt
1
4088
package net.binggl.mydms.features.filestore.amazon import com.amazonaws.AmazonClientException import com.amazonaws.AmazonServiceException import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.AmazonS3ClientBuilder import com.amazonaws.services.s3.model.ObjectMetadata import net.binggl.mydms.features.filestore.FileService import net.binggl.mydms.features.filestore.model.FileItem import org.apache.commons.io.IOUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import java.io.ByteArrayInputStream import java.util.* @Service class S3FileService(@Value("\${aws.accessKey}") private val accessKey: String, @Value("\${aws.secretKey}") private val secretKey: String, @Value("\${aws.bucketName}") private val bucketName: String ) : FileService { private lateinit var s3client: AmazonS3 init { val credentials = BasicAWSCredentials( this.accessKey, this.secretKey ) this.s3client = AmazonS3ClientBuilder .standard() .withCredentials(AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.EU_CENTRAL_1) // no need to configure this one! .build() } /** * use the given file and store it in the S3 backend */ override fun saveFile(file: FileItem): Boolean { var result = false val storagePath = "${file.folderName}/${file.fileName}" try { LOG.debug("Try to upload document to $storagePath.") val meta = ObjectMetadata() meta.contentEncoding = "UTF-8" meta.contentType = file.mimeType meta.contentLength = file.payload.size.toLong() var s3result = this.s3client.putObject( this.bucketName, storagePath, ByteArrayInputStream(file.payload.toByteArray()), meta) LOG.info("Upload operation result. eTag: ${s3result.eTag}") result = true } catch (awsEx: AmazonServiceException) { LOG.info("Could not upload object $storagePath. Reason: ${awsEx.message}") } catch (awsClientEx: AmazonClientException) { LOG.error("Error during interaction with S3: ${awsClientEx.message}", awsClientEx) } return result } /** * retrieve a item from the backend store */ override fun getFile(filePath: String): Optional<FileItem> { var file = Optional.empty<FileItem>() try { LOG.debug("Try to get S3 resource from bucket: ${this.bucketName} using path $filePath.") var fileUrlPath = filePath if (fileUrlPath.startsWith("/")) { fileUrlPath = fileUrlPath.substring(1, fileUrlPath.length) } val parts = fileUrlPath.split("/") val path = parts[0] val fileName = parts[1] val s3object = this.s3client.getObject(bucketName, fileUrlPath) val inputStream = s3object.objectContent val fileObject = FileItem(fileName = fileName, folderName = path, mimeType = s3object.objectMetadata.contentType, payload = IOUtils.toByteArray(inputStream).toTypedArray()) LOG.debug("Got object $fileObject") file = Optional.of(fileObject) } catch (awsEx: AmazonServiceException) { LOG.info("Could not get object $filePath. Reason: ${awsEx.message}") } catch (awsClientEx: AmazonClientException) { LOG.error("Error during interaction with S3: ${awsClientEx.message}", awsClientEx) } return file } companion object { private val LOG = LoggerFactory.getLogger(S3FileService::class.java) } }
apache-2.0
ef4d7d0455ab2f68570f0e85558a4760
34.859649
101
0.635274
4.753488
false
false
false
false
willmadison/AdventOfCode
kotlin/src/main/kotlin/com/willmadison/adventofcode/BathroomCodeDecoder.kt
1
4404
package com.willmadison.adventofcode enum class Movement { UP, DOWN, LEFT, RIGHT, INVALID } class Keypad { private val pad = listOf( listOf(1, 2, 3), listOf(4, 5, 6), listOf(7, 8, 9) ) fun canPress(coordinate: Coordinate) = coordinate.x >= 0 && coordinate.y >= 0 && coordinate.x < pad[0].size && coordinate.y < pad.size fun press(coordinate: Coordinate) = pad[coordinate.x][coordinate.y] } fun Char.parseMovement(): Movement { return when (this) { 'U' -> Movement.UP 'D' -> Movement.DOWN 'L' -> Movement.LEFT 'R' -> Movement.RIGHT else -> Movement.INVALID } } val keypad = Keypad() fun decodeBathRoomInstructions(instructionBlock: String): Int { val instructions = instructionBlock.split("\n") val digits = mutableListOf<Int>() var fingerPosition = Coordinate(1, 1) with (keypad) { instructions.forEach { instruction -> instruction.toCharArray().forEach { step -> val position: Coordinate when (step.parseMovement()) { Movement.UP -> position = fingerPosition.copy(fingerPosition.x - 1) Movement.DOWN -> position = fingerPosition.copy(fingerPosition.x + 1) Movement.LEFT -> position = fingerPosition.copy(y = fingerPosition.y - 1) Movement.RIGHT -> position = fingerPosition.copy(y = fingerPosition.y + 1) Movement.INVALID -> position = fingerPosition } if (canPress(position)) { fingerPosition = position } } digits.add(press(fingerPosition)) } } return digits.joinToString("").toInt() } fun main(args: Array<String>) { val passcode = decodeBathRoomInstructions("""DLRURUDLULRDRUDDRLUUUDLDLDLRLRRDRRRLLLLLDDRRRDRRDRRRLRRURLRDUULRLRRDDLULRLLDUDLULURRLRLDUDLURURLDRDDULDRDRDLDLLULULLDDLRRUDULLUULRRLLLURDRLDDLDDLDRLRRLLRURRUURRRRLUDLRDDDDRDULRLLDDUURDUDRLUDULLUDLUDURRDRDUUUUDDUDLLLRLUULRUURDLRLLRRLRLLDLLRLLRRRURLRRLURRLDLLLUUDURUDDLLUURRDRDRRDLLDDLLRDRDRRLURLDLDRDLURLDULDRURRRUDLLULDUDRURULDUDLULULRRRUDLUURRDURRURRLRRLLRDDUUUUUDUULDRLDLLRRUDRRDULLLDUDDUDUURLRDLULUUDLDRDUUUDDDUDLDURRULUULUUULDRUDDLLLDLULLRLRLUDULLDLLRLDLDDDUUDURDDDLURDRRDDLDRLLRLRR RLDUDURDRLLLLDDRRRURLLLRUUDDLRDRDDDUDLLUDDLRDURLDRDLLDRULDDRLDDDRLDRDDDRLLULDURRRLULDRLRDRDURURRDUDRURLDRLURDRLUULLULLDLUDUDRDRDDLDDDDRDURDLUDRDRURUDDLLLRLDDRURLLUDULULDDLLLDLUDLDULUUDLRLURLDRLURURRDUUDLRDDDDDRLDULUDLDDURDLURLUURDLURLDRURRLDLLRRUDRUULLRLDUUDURRLDURRLRUULDDLDLDUUDDRLDLLRRRUURLLUURURRURRLLLUDLDRRDLUULULUDDULLUDRLDDRURDRDUDULUDRLRRRUULLDRDRLULLLDURURURLURDLRRLLLDRLDUDLLLLDUUURULDDLDLLRRUDDDURULRLLUDLRDLUUDDRDDLLLRLUURLDLRUURDURDDDLLLLLULRRRURRDLUDLUURRDRLRUDUUUURRURLRDRRLRDRDULLDRDRLDURDDUURLRUDDDDDLRLLRUDDDDDURURRLDRRUUUDLURUUDRRDLLULDRRLRRRLUUUD RDRURLLUUDURURDUUULLRDRLRRLRUDDUDRURLLDLUUDLRLLDDURRURLUDUDDURLURLRRURLLURRUDRUDLDRLLURLRUUURRUDDDURRRLULLLLURDLRLLDDRLDRLLRRDLURDLRDLDUDRUULLDUUUDLURRLLRUDDDUUURLURUUDRLRULUURLLRLUDDLLDURULLLDURDLULDLDDUDULUDDULLRDRURDRRLLDLDDDDRUDLDRRLLLRLLLRRULDLRLRLRLLDLRDRDLLUDRDRULDUURRDDDRLLRLDLDRDUDRULUDRDLDLDDLLRULURLLURDLRRDUDLULLDLULLUDRRDDRLRURRLDUDLRRUUDLDRLRLDRLRRDURRDRRDDULURUUDDUUULRLDRLLDURRDLUULLUDRDDDLRUDLRULLDDDLURLURLRDRLLURRRUDLRRLURDUUDRLRUUDUULLRUUUDUUDDUURULDLDLURLRURLRUDLULLULRULDRDRLLLRRDLU RRRRDRLUUULLLRLDDLULRUUURRDRDRURRUURUDUULRULULRDRLRRLURDRRRULUUULRRUUULULRDDLLUURRLLDUDRLRRLDDLDLLDURLLUDLDDRRURLDLULRDUULDRLRDLLDLRULLRULLUDUDUDDUULDLUUDDLUDDUULLLLLURRDRULURDUUUDULRUDLLRUUULLUULLLRUUDDRRLRDUDDRULRDLDLLLLRLDDRRRULULLLDLRLURRDULRDRDUDDRLRLDRRDLRRRLLDLLDULLUDDUDDRULLLUDDRLLRRRLDRRURUUURRDLDLURRDLURULULRDUURLLULDULDUDLLULDDUURRRLDURDLUDURLDDRDUDDLLUULDRRLDLLUDRDURLLDRLDDUDURDLUUUUURRUULULLURLDUUULLRURLLLUURDULLUULDRULLUULRDRUULLRUDLDDLRLURRUUDRLRRRULRUUULRULRRLDLUDRRLL ULRLDLLURDRRUULRDUDDURDDDLRRRURLDRUDDLUDDDLLLRDLRLLRRUUDRRDRUULLLULULUUDRRRDRDRUUUUULRURUULULLULDULURRLURUDRDRUDRURURUDLDURUDUDDDRLRLLLLURULUDLRLDDLRUDDUUDURUULRLLLDDLLLLRRRDDLRLUDDUULRRLLRDUDLLDLRRUUULRLRDLRDUDLLLDLRULDRURDLLULLLRRRURDLLUURUDDURLDUUDLLDDRUUDULDRDRDRDDUDURLRRRRUDURLRRUDUDUURDRDULRLRLLRLUDLURUDRUDLULLULRLLULRUDDURUURDLRUULDURDRRRLLLLLUUUULUULDLDULLRURLUDLDRLRLRLRDLDRUDULDDRRDURDDULRULDRLRULDRLDLLUDLDRLRLRUDRDDR""") println("The bathroom passcode is $passcode.") }
mit
80fec15a602f5cede704d03652bb7bb6
61.042254
567
0.813579
2.522337
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/tween/tweenbase.kt
1
8289
package com.soywiz.korge.tween import com.soywiz.klock.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import com.soywiz.korma.interpolation.* import kotlin.jvm.* import kotlin.reflect.* @Suppress("UNCHECKED_CAST") data class V2<V>( val key: KMutableProperty0<V>, var initial: V, val end: V, val interpolator: (Double, V, V) -> V, val includeStart: Boolean, val startTime: TimeSpan = 0.nanoseconds, val duration: TimeSpan = TimeSpan.NIL ) { val endTime = startTime + duration.coalesce { 0.nanoseconds } fun init() { if (!includeStart) { initial = key.get() } } fun set(ratio: Double) = key.set(interpolator(ratio, initial, end)) override fun toString(): String = "V2(key=${key.name}, range=[$initial-$end], startTime=$startTime, duration=$duration)" } @JvmName("getInt") operator fun KMutableProperty0<Int>.get(end: Int) = V2(this, this.get(), end, ::_interpolateInt, includeStart = false) @JvmName("getInt") operator fun KMutableProperty0<Int>.get(initial: Int, end: Int) = V2(this, initial, end, ::_interpolateInt, includeStart = true) @JvmName("getMutableProperty") operator fun <V : Interpolable<V>> KMutableProperty0<V>.get(end: V) = V2(this, this.get(), end, ::_interpolateInterpolable, includeStart = false) @JvmName("getMutableProperty") operator fun <V : Interpolable<V>> KMutableProperty0<V>.get(initial: V, end: V) = V2(this, initial, end, ::_interpolateInterpolable, includeStart = true) @PublishedApi internal fun _interpolate(ratio: Double, l: Double, r: Double): Double = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateInt(ratio: Double, l: Int, r: Int): Int = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun <V : Interpolable<V>> _interpolateInterpolable(ratio: Double, l: V, r: V): V = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateFloat(ratio: Double, l: Float, r: Float): Float = when { ratio < 0.0 -> l ratio >= 1.0 -> r else -> ratio.interpolate(l, r) } @PublishedApi internal fun _interpolateColor(ratio: Double, l: RGBA, r: RGBA): RGBA = RGBA.mixRgba(l, r, ratio) @PublishedApi internal fun _interpolateColorAdd(ratio: Double, l: ColorAdd, r: ColorAdd): ColorAdd = ColorAdd( ratio.interpolate(l.r, r.r), ratio.interpolate(l.g, r.g), ratio.interpolate(l.b, r.b), ratio.interpolate(l.a, r.a) ) @PublishedApi internal fun _interpolateAngle(ratio: Double, l: Angle, r: Angle): Angle = _interpolateAngleAny(ratio, l, r, minimizeAngle = true) @PublishedApi internal fun _interpolateAngleDenormalized(ratio: Double, l: Angle, r: Angle): Angle = _interpolateAngleAny(ratio, l, r, minimizeAngle = false) internal fun _interpolateAngleAny(ratio: Double, l: Angle, r: Angle, minimizeAngle: Boolean = true): Angle { if (!minimizeAngle) return Angle(_interpolate(ratio, l.radians, r.radians)) val ln = l.normalized val rn = r.normalized return when { (rn - ln).absoluteValue <= 180.degrees -> Angle(_interpolate(ratio, ln.radians, rn.radians)) ln < rn -> Angle(_interpolate(ratio, (ln + 360.degrees).radians, rn.radians)).normalized else -> Angle(_interpolate(ratio, ln.radians, (rn + 360.degrees).radians)).normalized } } @PublishedApi internal fun _interpolateTimeSpan(ratio: Double, l: TimeSpan, r: TimeSpan): TimeSpan = _interpolate(ratio, l.milliseconds, r.milliseconds).milliseconds //inline operator fun KMutableProperty0<Float>.get(end: Number) = V2(this, this.get(), end.toFloat(), ::_interpolateFloat) //inline operator fun KMutableProperty0<Float>.get(initial: Number, end: Number) = // V2(this, initial.toFloat(), end.toFloat(), ::_interpolateFloat) inline operator fun KMutableProperty0<Double>.get(end: Double) = V2(this, this.get(), end, ::_interpolate, includeStart = false) inline operator fun KMutableProperty0<Double>.get(initial: Double, end: Double) = V2(this, initial, end, ::_interpolate, true) inline operator fun KMutableProperty0<Double>.get(end: Int) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Int, end: Int) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Float) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Float, end: Float) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Long) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Long, end: Float) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<Double>.get(end: Number) = get(end.toDouble()) inline operator fun KMutableProperty0<Double>.get(initial: Number, end: Number) = get(initial.toDouble(), end.toDouble()) inline operator fun KMutableProperty0<RGBA>.get(end: RGBA) = V2(this, this.get(), end, ::_interpolateColor, includeStart = false) inline operator fun KMutableProperty0<RGBA>.get(initial: RGBA, end: RGBA) = V2(this, initial, end, ::_interpolateColor, includeStart = true) inline operator fun KMutableProperty0<ColorAdd>.get(end: ColorAdd) = V2(this, this.get(), end, ::_interpolateColorAdd, includeStart = false) inline operator fun KMutableProperty0<ColorAdd>.get(initial: ColorAdd, end: ColorAdd) = V2(this, initial, end, ::_interpolateColorAdd, includeStart = true) inline operator fun KMutableProperty0<Angle>.get(end: Angle) = V2(this, this.get(), end, ::_interpolateAngle, includeStart = false) inline operator fun KMutableProperty0<Angle>.get(initial: Angle, end: Angle) = V2(this, initial, end, ::_interpolateAngle, includeStart = true) fun V2<Angle>.denormalized(): V2<Angle> = this.copy(interpolator = ::_interpolateAngleDenormalized) inline operator fun KMutableProperty0<TimeSpan>.get(end: TimeSpan) = V2(this, this.get(), end, ::_interpolateTimeSpan, includeStart = false) inline operator fun KMutableProperty0<TimeSpan>.get(initial: TimeSpan, end: TimeSpan) = V2(this, initial, end, ::_interpolateTimeSpan, includeStart = true) fun <V> V2<V>.easing(easing: Easing): V2<V> = this.copy(interpolator = { ratio, a, b -> this.interpolator(easing(ratio), a, b) }) inline fun <V> V2<V>.delay(startTime: TimeSpan) = this.copy(startTime = startTime) inline fun <V> V2<V>.duration(duration: TimeSpan) = this.copy(duration = duration) inline fun <V> V2<V>.linear() = this inline fun <V> V2<V>.smooth() = this.easing(Easing.SMOOTH) inline fun <V> V2<V>.easeIn() = this.easing(Easing.EASE_IN) inline fun <V> V2<V>.easeOut() = this.easing(Easing.EASE_OUT) inline fun <V> V2<V>.easeInOut() = this.easing(Easing.EASE_IN_OUT) inline fun <V> V2<V>.easeOutIn() = this.easing(Easing.EASE_OUT_IN) inline fun <V> V2<V>.easeInBack() = this.easing(Easing.EASE_IN_BACK) inline fun <V> V2<V>.easeOutBack() = this.easing(Easing.EASE_OUT_BACK) inline fun <V> V2<V>.easeInOutBack() = this.easing(Easing.EASE_IN_OUT_BACK) inline fun <V> V2<V>.easeOutInBack() = this.easing(Easing.EASE_OUT_IN_BACK) inline fun <V> V2<V>.easeInElastic() = this.easing(Easing.EASE_IN_ELASTIC) inline fun <V> V2<V>.easeOutElastic() = this.easing(Easing.EASE_OUT_ELASTIC) inline fun <V> V2<V>.easeInOutElastic() = this.easing(Easing.EASE_IN_OUT_ELASTIC) inline fun <V> V2<V>.easeOutInElastic() = this.easing(Easing.EASE_OUT_IN_ELASTIC) inline fun <V> V2<V>.easeInBounce() = this.easing(Easing.EASE_IN_BOUNCE) inline fun <V> V2<V>.easeOutBounce() = this.easing(Easing.EASE_OUT_BOUNCE) inline fun <V> V2<V>.easeInOutBounce() = this.easing(Easing.EASE_IN_OUT_BOUNCE) inline fun <V> V2<V>.easeOutInBounce() = this.easing(Easing.EASE_OUT_IN_BOUNCE) inline fun <V> V2<V>.easeInQuad() = this.easing(Easing.EASE_IN_QUAD) inline fun <V> V2<V>.easeOutQuad() = this.easing(Easing.EASE_OUT_QUAD) inline fun <V> V2<V>.easeInOutQuad() = this.easing(Easing.EASE_IN_OUT_QUAD) inline fun <V> V2<V>.easeSine() = this.easing(Easing.EASE_SINE) inline fun <V> V2<V>.easeClampStart() = this.easing(Easing.EASE_CLAMP_START) inline fun <V> V2<V>.easeClampEnd() = this.easing(Easing.EASE_CLAMP_END) inline fun <V> V2<V>.easeClampMiddle() = this.easing(Easing.EASE_CLAMP_MIDDLE)
apache-2.0
632935e7032d81d16ebef459f758e1da
48.047337
155
0.713717
3.244227
false
false
false
false
izmajlowiczl/Expensive
storage/src/main/java/pl/expensive/storage/_Seeds.kt
1
1808
package pl.expensive.storage import android.database.sqlite.SQLiteDatabase import pl.expensive.storage._LabelSeeds.FOOD import pl.expensive.storage._LabelSeeds.HOUSEHOLD import pl.expensive.storage._LabelSeeds.RENT import pl.expensive.storage._LabelSeeds.TRANSPORT import pl.expensive.storage._Seeds.CHF import pl.expensive.storage._Seeds.CZK import pl.expensive.storage._Seeds.EUR import pl.expensive.storage._Seeds.GBP import pl.expensive.storage._Seeds.PLN import java.util.* object _Seeds { val EUR = CurrencyDbo("EUR", "##.##\u00a0\u20ac") val GBP = CurrencyDbo("GBP", "\u00a3##.##") val CHF = CurrencyDbo("CHF", "##.##\u00a0CHF") val PLN = CurrencyDbo("PLN", "##.##\u00a0zł") val CZK = CurrencyDbo("CZK", "##.##\u00a0K\u010d") } object _LabelSeeds { val FOOD = LabelDbo(UUID.fromString("78167ed1-a59a-431e-bfd4-57fb8dbed743"), "Food") val RENT = LabelDbo(UUID.fromString("edb24ade-2ac1-414e-9281-4d7a3b847d1b"), "Rent") val TRANSPORT = LabelDbo(UUID.fromString("7c108b80-c954-40bb-8464-0914d28426d5"), "Transportation") val HOUSEHOLD = LabelDbo(UUID.fromString("e4655b6b-3e75-4ca7-86b5-25d7e4906ada"), "Household") } fun applySeeds(db: SQLiteDatabase) { storeCurrency(db, EUR) storeCurrency(db, GBP) storeCurrency(db, CHF) storeCurrency(db, PLN) storeCurrency(db, CZK) storeLabel(db, FOOD) storeLabel(db, RENT) storeLabel(db, TRANSPORT) storeLabel(db, HOUSEHOLD) } private fun storeCurrency(db: SQLiteDatabase, currency: CurrencyDbo) { db.execSQL(String.format("INSERT INTO $tbl_currency VALUES('%s', '%s');", currency.code, currency.format)) } private fun storeLabel(db: SQLiteDatabase, label: LabelDbo) { db.execSQL(String.format("INSERT INTO $tbl_label VALUES('%s', '%s');", label.id.toString(), label.name)) }
gpl-3.0
4648d54af96408a5fd31b5cb557db93d
35.877551
110
0.720531
2.8912
false
false
false
false
ARostovsky/teamcity-rest-client
teamcity-rest-client-impl/src/test/kotlin/org/jetbrains/teamcity/rest/testUtils.kt
1
4676
package org.jetbrains.teamcity.rest import org.apache.log4j.* import java.io.File import java.io.FileInputStream import java.util.* import kotlin.reflect.KFunction import kotlin.reflect.KProperty import kotlin.reflect.full.valueParameters private val TEAMCITY_CONNECTION_FILE_PATH = "teamcity_connection.properties" //slf4j simple ignores debug output fun setupLog4jDebug() { LogManager.resetConfiguration() Logger.getRootLogger().removeAllAppenders() Logger.getRootLogger().addAppender(ConsoleAppender(PatternLayout("TEST[%d] %6p [%15.15t] - %30.30c - %m %n"))) Logger.getLogger("jetbrains").level = Level.DEBUG Logger.getLogger("org.apache.http").level = Level.ERROR } val publicInstanceUrl = "http://localhost:8111" fun publicInstance() = TeamCityInstanceFactory.guestAuth(publicInstanceUrl).withLogResponses() fun customInstance(serverUrl: String, username: String, password: String) = TeamCityInstanceFactory .httpAuth(serverUrl, username, password) .withLogResponses() fun haveCustomInstance(): Boolean = ConnectionPropertiesFileLoader(TEAMCITY_CONNECTION_FILE_PATH).validate() fun customInstanceByConnectionFile(): TeamCityInstance { val connectionPropertiesFileLoader = ConnectionPropertiesFileLoader(TEAMCITY_CONNECTION_FILE_PATH) return if (connectionPropertiesFileLoader.validate()) { val connectionConfig = connectionPropertiesFileLoader.fetch() customInstance(connectionConfig.serverUrl, connectionConfig.username, connectionConfig.password) } else { publicInstance() } } val reportProject = ProjectId("ProjectForReports") val testProject = ProjectId("TestProject") val changesBuildConfiguration = BuildConfigurationId("ProjectForSidebarCounters_MultibranchChange") val testsBuildConfiguration = BuildConfigurationId("ProjectForSidebarCounters_MultibranchTestResult") val runTestsBuildConfiguration = BuildConfigurationId("TestProject_RunTests") val dependantBuildConfiguration = BuildConfigurationId("TeamcityTestMetadataDemo_TestMetadataDemo") val pausedBuildConfiguration = BuildConfigurationId("ProjectForReports_TestPaused") val manyTestsBuildConfiguration = BuildConfigurationId("TeamcityTestData_Test") internal class ConnectionPropertiesFileLoader(filePath: String) { private val connectionFile: File? init { val classLoader = javaClass.classLoader connectionFile = classLoader.getResource(filePath)?.let { File(it.file) } } fun fetch(): ConnectionConfig { if (!validate()) { throw IllegalStateException("Properties are invalid") } val connectionProperties = Properties() connectionProperties.load(FileInputStream(connectionFile)) return ConnectionConfig( connectionProperties.getProperty(SERVER_URL), connectionProperties.getProperty(USERNAME), connectionProperties.getProperty(PASSWORD)) } fun validate(): Boolean { if (connectionFile == null || !connectionFile.exists()) return false val connectionProperties = Properties() connectionProperties.load(FileInputStream(connectionFile)) return validateConnectionProperties(connectionProperties) } private fun validateConnectionProperties(connectionProperties: Properties): Boolean { return validPropertyValue(connectionProperties.getProperty(SERVER_URL)) && validPropertyValue(connectionProperties.getProperty(USERNAME)) && validPropertyValue(connectionProperties.getProperty(PASSWORD)) } private fun validPropertyValue(value: String?): Boolean { return (value != null) && (!value.isNullOrEmpty()) } companion object { val SERVER_URL = "serverUrl" val USERNAME = "username" val PASSWORD = "password" } } internal class ConnectionConfig(val serverUrl: String, val username: String, val password: String) inline fun <reified T> callPublicPropertiesAndFetchMethods(instance: T) { instance.toString() for (member in T::class.members) { when (member) { is KProperty<*> -> { member.getter.call(instance) // println("${member.name} = ${member.getter.call(instance)}") } is KFunction<*> -> if ( member.name.startsWith("fetch") || member.name.startsWith("get")) { if (member.valueParameters.isEmpty()) { member.call(instance) // println("${member.name} = ${member.call(instance)}") } } } } }
apache-2.0
68ca06dfaa8a8a7c67a332408d3e78b7
37.966667
114
0.704876
4.990395
false
true
false
false
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/color/ColorTest.kt
1
6431
package com.sksamuel.scrimage.core.color import com.sksamuel.scrimage.color.CMYKColor import com.sksamuel.scrimage.color.Grayscale import com.sksamuel.scrimage.color.HSLColor import com.sksamuel.scrimage.color.HSVColor import com.sksamuel.scrimage.color.RGBColor import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.floats.plusOrMinus import io.kotest.matchers.shouldBe class ColorTest : WordSpec({ "color conversions" should { "convert rgb to cmyk correctly" { val rgb = RGBColor(1, 2, 3) rgb.toCMYK().c shouldBe (0.667f plusOrMinus 0.2f) rgb.toCMYK().m shouldBe (0.333f plusOrMinus 0.2f) rgb.toCMYK().y shouldBe 0f rgb.toCMYK().k shouldBe (0.988f plusOrMinus 0.2f) } "convert rgb to hsl correctly" { val hsl = RGBColor(240, 150, 200).toHSL() hsl.hue shouldBe (326.66f plusOrMinus 0.2f) hsl.saturation shouldBe (0.75f plusOrMinus 0.2f) hsl.lightness shouldBe (0.765f plusOrMinus 0.2f) } "convert achromatic rgb to hsl correctly" { val hsl = RGBColor(50, 50, 50).toHSL() hsl.hue shouldBe (0f plusOrMinus 0.02f) hsl.saturation shouldBe (0f plusOrMinus 0.021f) hsl.lightness shouldBe (0.196f plusOrMinus 0.02f) } "convert rgb to hsv correctly" { val hsl = RGBColor(255, 150, 200).toHSV() hsl.hue shouldBe (331.42f plusOrMinus 0.2f) hsl.saturation shouldBe (0.4121f plusOrMinus 0.2f) hsl.value shouldBe (1f plusOrMinus 0.2f) } "convert rgb to grayscale correctly" { val rgb = RGBColor(100, 100, 100) rgb.toGrayscale().gray shouldBe 100 } "convert cmyk to rgb correctly" { val rgb = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f).toRGB() rgb.red shouldBe 138 rgb.green shouldBe 122 rgb.blue shouldBe 107 rgb.alpha shouldBe 255 } "convert hsl to rgb correctly" { val rgb = HSLColor(100f, 0.5f, 0.3f, 1f).toRGB() rgb.red shouldBe 64 rgb.green shouldBe 115 rgb.blue shouldBe 38 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 1" { val rgb = HSVColor(150f, 0.2f, 0.3f, 1f).toRGB() rgb.red shouldBe 61 rgb.green shouldBe 77 rgb.blue shouldBe 69 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 2" { val rgb = HSVColor(2f, 0.99f, 0.61f, 1f).toRGB() rgb.red shouldBe 156 rgb.green shouldBe 7 rgb.blue shouldBe 2 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 3" { val rgb = HSVColor(99f, 0.51f, 0.61f, 1f).toRGB() rgb.red shouldBe 104 rgb.green shouldBe 156 rgb.blue shouldBe 76 rgb.alpha shouldBe 255 } "convert hsv to rgb correctly 4" { val rgb = HSVColor(99f, 0.51f, 0.62f, 1f).toRGB() rgb.red shouldBe 106 rgb.green shouldBe 158 rgb.blue shouldBe 77 rgb.alpha shouldBe 255 } "convert grayscale to rgb correctly" { val rgb = Grayscale(100, 128).toRGB() rgb.red shouldBe 100 rgb.green shouldBe 100 rgb.blue shouldBe 100 rgb.alpha shouldBe 128 } "be symmetric in rgb" { val rgb = RGBColor(1, 2, 3) rgb.toCMYK().toRGB() shouldBe rgb rgb.toHSL().toRGB() shouldBe rgb rgb.toHSV().toRGB() shouldBe rgb } "be symmetric in hsl" { val hsl = HSLColor(300f, 0.3f, 0.3f, 0.4f) hsl.toRGB().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.02f) hsl.toRGB().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toRGB().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) hsl.toHSV().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.2f) hsl.toHSV().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toHSV().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) hsl.toCMYK().toHSL().hue shouldBe (hsl.hue plusOrMinus 0.2f) hsl.toCMYK().toHSL().saturation shouldBe (hsl.saturation plusOrMinus 0.2f) hsl.toCMYK().toHSL().lightness shouldBe (hsl.lightness plusOrMinus 0.2f) } "be symmetric in HSV" { val hsv = HSVColor(300f, 0.2f, 0.3f, 0.4f) hsv.toRGB().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toRGB().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toRGB().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) hsv.toHSL().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toHSL().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toHSL().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) hsv.toCMYK().toHSV().hue shouldBe (hsv.hue plusOrMinus 0.2f) hsv.toCMYK().toHSV().saturation shouldBe (hsv.saturation plusOrMinus 0.2f) hsv.toCMYK().toHSV().value shouldBe (hsv.value plusOrMinus 0.2f) } "be symmetric in cmyk" { val cmyk = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f) cmyk.toRGB().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toRGB().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toRGB().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toRGB().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) cmyk.toHSV().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toHSV().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toHSV().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toHSV().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) cmyk.toHSL().toCMYK().c shouldBe (cmyk.c plusOrMinus 0.2f) cmyk.toHSL().toCMYK().m shouldBe (cmyk.m plusOrMinus 0.2f) cmyk.toHSL().toCMYK().y shouldBe (cmyk.y plusOrMinus 0.2f) cmyk.toHSL().toCMYK().k shouldBe (cmyk.k plusOrMinus 0.2f) } "be reflexive" { val rgb = RGBColor(1, 2, 3) rgb.toRGB() shouldBe rgb val hsl = HSLColor(0.1f, 0.2f, 0.3f, 0.4f) hsl.toHSL() shouldBe hsl val hsv = HSVColor(0.1f, 0.2f, 0.3f, 0.4f) hsv.toHSV() shouldBe hsv val cmyk = CMYKColor(0.1f, 0.2f, 0.3f, 0.4f) cmyk.toCMYK() shouldBe cmyk val gray = Grayscale(100) gray.toGrayscale() shouldBe gray } } })
apache-2.0
426cecb718fb538eba77feb5a72d09f9
38.213415
83
0.611569
3.233283
false
false
false
false
ioc1778/incubator
incubator-crypto/src/main/java/com/riaektiv/crypto/tree/Tree.kt
2
4111
package com.riaektiv.crypto.tree import org.apache.commons.codec.binary.Hex import org.bouncycastle.jcajce.provider.digest.SHA3 import java.io.UnsupportedEncodingException import java.util.* /** * Coding With Passion Since 1991 * Created: 6/26/2016, 7:31 PM Eastern Time * @author Sergey Chuykov */ abstract class Tree<E : Entity> : EntityFactory<E> { var root = Node<E>() fun path(s: String): IntArray { val hex = Hex.encodeHexString(s.toByteArray()) val encoded = IntArray(hex.length) for (i in 0..hex.length - 1) { val h = hex[i] encoded[i] = Integer.parseInt(h.toString(), 16) } return encoded } protected fun nvl(s: String?): String { return s ?: "" } fun sha3(message: String): String { val s = nvl(message) val md = SHA3.DigestSHA3(224) try { md.update(s.toByteArray(charset("UTF-8"))) } catch (ex: UnsupportedEncodingException) { md.update(s.toByteArray()) } val digest = md.digest() return Hex.encodeHexString(digest) } protected fun hash(node: Node<E>): String { return if (node.entity != null) node.entity!!.hash() else "" } protected fun message(node: Node<E>): String { val sb = StringBuilder() for (ref in node.refs) { sb.append(nvl(ref)).append(':') } sb.append(hash(node)) return sb.toString() } fun sha3(node: Node<E>): String { return sha3(message(node)) } protected fun find(n: Node<E>?, vararg path: Int): Node<E>? { var node = n for (idx in path) { node = node!!.next[idx] if (node == null) { break } } return node } fun nodes(n: Node<E>, vararg path: Int): LinkedList<Node<E>> { var node = n val nodes = LinkedList<Node<E>>() nodes.offer(node) for (idx in path) { var next: Node<E>? = node.next[idx] if (next == null) { next = Node<E>() node.next[idx] = next } node = next nodes.offer(node) } return nodes } fun find(vararg path: Int): Node<E>? { return find(root, *path) } fun get(key: String): E? { return find(*path(key))?.entity } fun put(key: String, entity: E) { val path = path(key) val nodes = nodes(root, *path) var node = nodes.pollLast() node.entity = entity node.hash = sha3(node) for (i in path.indices.reversed()) { node = nodes[i] val idx = path[i] node.setRef(idx, node.next[idx]?.hash!!) node.hash = sha3(node) } } fun validateHash(node: Node<E>?) { if (node == null) { return } val expected = sha3(node) if (expected != node.hash) { throw IllegalStateException("Invalid hash value:" + node) } } private inner class NodeCtx(var idx: Int, var node: Node<E>?) { override fun toString(): String { return "NodeCtx{" + "idx=" + idx + ", node=" + node + '}' } } @JvmOverloads fun validate(n: Node<E>? = root) { var node = n val stack = LinkedList<NodeCtx>() var i = 0 while (i < 0xF) { if (node!!.next[i] != null) { validateHash(node) val ctx = NodeCtx(i, node) println(ctx) stack.push(ctx) node = node.next[i] i = 0 } else { if (i == 0xF - 1 && !stack.isEmpty()) { if (node.entity != null) { println(node) } val ctx = stack.pop() node = ctx.node i = ctx.idx } } i++ } } }
bsd-3-clause
e2424b310ea3dd2a96eac3ae6cdbe994
23.915152
69
0.47458
3.991262
false
false
false
false