blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
c0253f4e6c50ba4294d1d0073c181e7d9bd0c376
1bdf374efdd222ef49e84171c46782c0d76ce15e
/app/src/main/java/com/yusufalicezik/drvirtual/Utils/GecmisRandevuAdapter.java
983d8eae2b0c2411558e24789c721c38d14366ad
[]
no_license
hasancerit/Dr.Virtual
a568658edf608b1b534bc3322becda4338156935
d1c6e90815c8eeeed9541e7892365825f52f2ab7
refs/heads/master
2020-05-27T19:14:43.577458
2019-05-27T02:29:15
2019-05-27T02:29:15
188,757,889
1
0
null
null
null
null
UTF-8
Java
false
false
1,730
java
package com.yusufalicezik.drvirtual.Utils; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yusufalicezik.drvirtual.R; import java.util.ArrayList; public class GecmisRandevuAdapter extends RecyclerView.Adapter<GecmisRandevuAdapter.MyHolder> { Context context; LayoutInflater inflater; ArrayList<String> gecmisRandevuList; public GecmisRandevuAdapter(Context context, ArrayList<String> gecmisRandevuList){ this.context = context; inflater = LayoutInflater.from(context); this.gecmisRandevuList = gecmisRandevuList; } @NonNull @Override public GecmisRandevuAdapter.MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v = inflater.inflate(R.layout.gecmis_randevu_satir,viewGroup,false); MyHolder viewHolder = new MyHolder(v); return viewHolder; } @Override public void onBindViewHolder(@NonNull GecmisRandevuAdapter.MyHolder myHolder, int i) { myHolder.setData(gecmisRandevuList.get(i)); } @Override public int getItemCount() { return gecmisRandevuList.size(); } public class MyHolder extends RecyclerView.ViewHolder { TextView doktorIsim,saat; public MyHolder(@NonNull View itemView) { super(itemView); doktorIsim = itemView.findViewById(R.id.doktorIsim); saat = itemView.findViewById(R.id.saat); } public void setData(String randevu){ doktorIsim.setText(randevu); } } }
0c9ebf8f1e0034ad38ea8ebfa222c3d72111bc70
1e0414638028c0b125e2e49858b4ed6d43ce8ef4
/app/src/main/java/com/example/gamer/diary/Diary.java
c127b20e3a1b0e517e5d06cee92ef73568868aad
[]
no_license
gamer2925666/Diary
75f153d6b6776f71997e19f8235c34efb9013ae4
240a317794edb621a53f40eb4f0a87a256ae066b
refs/heads/master
2021-03-30T22:18:20.234814
2018-03-25T13:14:11
2018-03-25T13:14:11
124,652,086
0
0
null
null
null
null
UTF-8
Java
false
false
1,152
java
package com.example.gamer.diary; import android.support.annotation.NonNull; import java.io.File; /** * Created by gamer on 2018/3/25. */ public class Diary { private String title; private File image; private Long date; private File textFile; private String key; public Diary(String title, File image, Long date, File textFile) { this.title = title; this.image = image; this.date = date; this.textFile = textFile; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public Long getDate() { return date; } public void setDate(Long date) { this.date = date; } public File getTextFile() { return textFile; } public void setTextFile(File textFile) { this.textFile = textFile; } }
1b4a7bae69053f5c452c07742d1776c2cbab4b20
4370971acf1f422557e3f7de83d47f7705fd3719
/ph-oton-bootstrap4/src/main/java/com/helger/photon/bootstrap4/buttongroup/BootstrapButtonToolbar.java
d7a1fe76bb416b92e2bebe949ccef4ab7eed47e5
[ "Apache-2.0" ]
permissive
phax/ph-oton
848676b328507b5ea96877d0b8ba80d286fd9fb7
6d28dcb7de123f4deb77de1bc022faf77ac37e49
refs/heads/master
2023-08-27T20:41:11.706035
2023-08-20T15:30:44
2023-08-20T15:30:44
35,175,824
5
5
Apache-2.0
2023-02-23T20:20:41
2015-05-06T18:27:20
JavaScript
UTF-8
Java
false
false
2,911
java
/* * Copyright (C) 2018-2023 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * 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.helger.photon.bootstrap4.buttongroup; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.ValueEnforcer; import com.helger.commons.url.ISimpleURL; import com.helger.commons.url.SimpleURL; import com.helger.html.EHTMLRole; import com.helger.html.js.IHasJSCode; import com.helger.photon.bootstrap4.CBootstrapCSS; import com.helger.photon.bootstrap4.base.AbstractBootstrapDiv; import com.helger.photon.bootstrap4.button.BootstrapButton; import com.helger.photon.bootstrap4.button.BootstrapSubmitButton; import com.helger.photon.core.execcontext.ILayoutExecutionContext; import com.helger.photon.uicore.html.toolbar.IButtonToolbar; import com.helger.photon.uicore.icon.IIcon; /** * Bootstrap3 button toolbar. Should only be used to group button groups and not * simple buttons. * * @author Philip Helger */ public class BootstrapButtonToolbar extends AbstractBootstrapDiv <BootstrapButtonToolbar> implements IButtonToolbar <BootstrapButtonToolbar> { private final SimpleURL m_aSelfHref; public BootstrapButtonToolbar (@Nonnull final ILayoutExecutionContext aLEC) { this (aLEC.getSelfHref ()); } public BootstrapButtonToolbar (@Nonnull final SimpleURL aSelfHref) { m_aSelfHref = ValueEnforcer.notNull (aSelfHref, "SelfHref"); addClass (CBootstrapCSS.BTN_TOOLBAR); setRole (EHTMLRole.TOOLBAR); } @Nonnull public ISimpleURL getSelfHref () { return m_aSelfHref; } @Nonnull public final BootstrapButton addAndReturnButton (@Nullable final String sCaption, @Nullable final IHasJSCode aJSCode, @Nullable final IIcon aIcon) { return addAndReturnChild (new BootstrapButton ().setIcon (aIcon).addChild (sCaption).setOnClick (aJSCode)); } @Nonnull public final BootstrapButton addAndReturnSubmitButton (@Nullable final String sCaption, @Nullable final IHasJSCode aOnClick, @Nullable final IIcon aIcon) { return addAndReturnChild (new BootstrapSubmitButton ().setIcon (aIcon).setOnClick (aOnClick).addChild (sCaption)); } }
9fc694c77b8804d92b06b05ae989795a914ffbfa
68a7acc92e7312b4db75a4adc79469473d8dcc52
/src/jgroups/SimpleChat.java
d783644d4fe898c8ae3c3b3e28bef73f25f8cbbe
[]
no_license
vasanthsubram/JavaCookBook
e83f95a9a08d6227455ebd213d216837ec1c97b5
3fb2dfc38a4bb56f21f329b0dbc8283609412840
refs/heads/master
2022-12-16T00:13:31.515018
2019-06-24T03:12:11
2019-06-24T03:12:11
30,102,351
0
0
null
2022-12-13T19:13:55
2015-01-31T04:39:51
Java
UTF-8
Java
false
false
2,617
java
package jgroups; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.View; import org.jgroups.util.Util; import java.io.*; import java.util.List; import java.util.LinkedList; /* * Sample program to simulate a jgroups cluster * * To run it in the same machine, add this VM argument and start two instances * -Djgroups.bind_addr=127.0.0.1 or set the System property * */ public class SimpleChat extends ReceiverAdapter { JChannel channel; String user_name=System.getProperty("user.name", "n/a"); final List<String> state=new LinkedList<String>(); public SimpleChat(){ System.setProperty("jgroups.bind_addr","127.0.0.1"); } public void viewAccepted(View new_view) { System.out.println("** view: " + new_view); } public void receive(Message msg) { String line=msg.getSrc() + ": " + msg.getObject(); System.out.println(line); synchronized(state) { state.add(line); } } public void getState(OutputStream output) throws Exception { synchronized(state) { Util.objectToStream(state, new DataOutputStream(output)); } } public void setState(InputStream input) throws Exception { List<String> list=(List<String>)Util.objectFromStream(new DataInputStream(input)); synchronized(state) { state.clear(); state.addAll(list); } System.out.println("received state (" + list.size() + " messages in chat history):"); for(String str: list) { System.out.println(str); } } private void start() throws Exception { channel=new JChannel(); channel.setReceiver(this); channel.connect("ChatCluster"); channel.getState(null, 10000); eventLoop(); channel.close(); } private void eventLoop() { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); while(true) { try { System.out.print("> "); System.out.flush(); String line=in.readLine().toLowerCase(); if(line.startsWith("quit") || line.startsWith("exit")) { break; } line="[" + user_name + "] " + line; Message msg=new Message(null, null, line); channel.send(msg); } catch(Exception e) { } } } public static void main(String[] args) throws Exception { new SimpleChat().start(); } }
e64565487485a5ce6b752d1190544269182d8577
be552bb4d82897cd0901176d428946894993064a
/spring-cloud-aws-example-1/src/test/java/com/srm4knowledge/springcloudawsexample1/SpringCloudAwsExample1ApplicationTests.java
7ba2d567cedea35b048a0f902b821a5e52545ad0
[]
no_license
sandeep-r-m/learning-java-technology
834cc88596aaa649ede79a7ed0e89d2d317f7f72
92e402b3056181f02352c7196eba15658db38988
refs/heads/master
2022-11-21T13:02:06.716492
2019-10-26T09:19:25
2019-10-26T09:19:25
156,517,138
0
0
null
2022-11-16T12:23:52
2018-11-07T08:51:20
Java
UTF-8
Java
false
false
374
java
package com.srm4knowledge.springcloudawsexample1; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringCloudAwsExample1ApplicationTests { @Test public void contextLoads() { } }
3822fd8cf827e644eef3f3f0534177a67dfdc8b2
244255f2c1886699838060288ec396e30fab2bd8
/2.JavaCore/src/com/javarush/task/task15/task1522/Solution.java
8fd37e24c4f537ec4164e22ed0284400d47297f2
[]
no_license
AlexManax/JavaRushTasks
fb1fe1f57d0f89a7dbe3e8b5bd879d4f4b6e9b29
7a8359699c0f917228b21473eeca5815d8fb2243
refs/heads/master
2020-04-26T21:35:45.199276
2020-03-06T19:14:57
2020-03-06T19:14:57
173,846,068
0
0
null
null
null
null
UTF-8
Java
false
false
1,089
java
package com.javarush.task.task15.task1522; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* Закрепляем паттерн Singleton */ public class Solution { public static void main(String[] args) { } public static Planet thePlanet; //add static block here - добавьте статический блок тут static { readKeyFromConsoleAndInitPlanet(); } public static void readKeyFromConsoleAndInitPlanet() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String planet = null; try { planet = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } switch (planet) { case "sun" : thePlanet = Sun.getInstance(); break; case "moon" : thePlanet = Moon.getInstance(); break; case "earth" : thePlanet = Earth.getInstance(); break; default: thePlanet = null; } } }
d98b6e0f611c968809ef2f750cbb6b0d8077241b
7ce3f11812b62313ebb8093c46b21e0619017b72
/app/src/main/java/dhbk/android/movienanodegree/ui/detailmovie/view/MovieDetailFragment.java
641e931a827e1d627b6d81d1a43bbca23f09c45c
[]
no_license
PhongHuynh93/MovieNanoDegree
a6ba26819312dc6490b1ccb74d12dbaf034a288b
b27301ea4f8a989360269d4d8ce467de3320ded5
refs/heads/master
2021-01-19T02:35:13.626967
2016-08-17T14:47:17
2016-08-17T14:47:17
64,321,812
0
0
null
null
null
null
UTF-8
Java
false
false
11,946
java
package dhbk.android.movienanodegree.ui.detailmovie.view; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.util.ArrayList; import java.util.Locale; import javax.inject.Inject; import butterknife.BindView; import dhbk.android.movienanodegree.MVPApp; import dhbk.android.movienanodegree.R; import dhbk.android.movienanodegree.dagger.detailmovie.DaggerDetailMovieViewComponent; import dhbk.android.movienanodegree.dagger.detailmovie.MovieReviewsAdapterModule; import dhbk.android.movienanodegree.dagger.detailmovie.MovieVideosAdapterModule; import dhbk.android.movienanodegree.models.DiscoverMovieResponse; import dhbk.android.movienanodegree.models.MovieReviewsResponse; import dhbk.android.movienanodegree.models.MovieVideosResponse; import dhbk.android.movienanodegree.ui.base.BaseFragment; import dhbk.android.movienanodegree.ui.detailmovie.DetailMovieContract; import dhbk.android.movienanodegree.ui.detailmovie.ItemOffsetDecoration; import dhbk.android.movienanodegree.ui.detailmovie.MovieReviewsAdapter; import dhbk.android.movienanodegree.ui.detailmovie.MovieVideosAdapter; import dhbk.android.movienanodegree.util.Constant; import hugo.weaving.DebugLog; import static com.google.common.base.Preconditions.checkNotNull; /** * A simple {@link Fragment} subclass. */ public class MovieDetailFragment extends BaseFragment implements DetailMovieContract.View { private static final String ARG_MOVIE = "arg_movie"; private DetailMovieContract.Presenter mPresenter; private DiscoverMovieResponse.DiscoverMovie mMovie; @BindView(R.id.image_movie_detail_poster) ImageView movieImagePoster; @BindView(R.id.text_movie_original_title) TextView movieOriginalTitle; @BindView(R.id.text_movie_user_rating) TextView movieUserRating; @BindView(R.id.text_movie_release_date) TextView movieReleaseDate; @BindView(R.id.text_movie_overview) TextView movieOverview; @BindView(R.id.card_movie_detail) CardView cardMovieDetail; @BindView(R.id.card_movie_overview) CardView cardMovieOverview; @BindView(R.id.card_movie_videos) CardView cardMovieVideos; @BindView(R.id.movie_videos) RecyclerView movieVideos; @BindView(R.id.card_movie_reviews) CardView cardMovieReviews; @BindView(R.id.movie_reviews) RecyclerView movieReviews; @Inject MovieVideosAdapter mMovieVideosAdapter; @Inject MovieReviewsAdapter mMovieReviewsAdapter; public MovieDetailFragment() { // Required empty public constructor } // : 8/9/2016 5 set the fragment with movie @DebugLog public static MovieDetailFragment newInstance(@NonNull DiscoverMovieResponse.DiscoverMovie movie) { checkNotNull(movie); MovieDetailFragment fragment = new MovieDetailFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_MOVIE, movie); fragment.setArguments(args); return fragment; } @Override public int getLayout() { return R.layout.fragment_movie_detail; } @Override protected boolean hasToolbar() { return false; } @Override protected void initView() { mPresenter.declareMovieDetail(); } /** * declare view */ @Override public void declareView() { } @ColorInt private int getRatingColor(double averageVote) { if (averageVote >= Constant.VOTE_PERFECT) { return ContextCompat.getColor(getContext(), R.color.vote_perfect); } else if (averageVote >= Constant.VOTE_GOOD) { return ContextCompat.getColor(getContext(), R.color.vote_good); } else if (averageVote >= Constant.VOTE_NORMAL) { return ContextCompat.getColor(getContext(), R.color.vote_normal); } else { return ContextCompat.getColor(getContext(), R.color.vote_bad); } } /** * load poster image, name of movies */ @Override public void declareMovieInfo() { // add poster image Glide.with(this) .load(Constant.POSTER_IMAGE_BASE_URL + Constant.POSTER_IMAGE_SIZE + mMovie.getPosterPath()) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(movieImagePoster); // title movieOriginalTitle.setText(mMovie.getOriginalTitle()); // user rating, auto change color depend on vote count movieUserRating.setText(String.format(Locale.US, "%.1f", mMovie.getAverageVote())); movieUserRating.setTextColor(getRatingColor(mMovie.getAverageVote())); // fixme release data, remember String.format <string name="movie_detail_release_date">%s</string>, can change to html format color String releaseDate = String.format(getString(R.string.movie_detail_release_date), mMovie.getReleaseDate()); movieReleaseDate.setText(releaseDate); // movie description movieOverview.setText(mMovie.getOverview()); } /** * declare video recyclerview */ @Override public void declareVideoList() { // : 8/9/2016 8c listen when click trailer mMovieVideosAdapter.setMOnItemClickListener((itemView, position) -> onMovieVideoClicked(position)); movieVideos.setAdapter(mMovieVideosAdapter); movieVideos.setItemAnimator(new DefaultItemAnimator()); movieVideos.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.movie_item_offset)); movieVideos.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false)); } /** * if you click a trailer among trailers in video list, this method will be called * get to youtube site via Intent * @see <a href="http://stackoverflow.com/questions/574195/android-youtube-app-play-video-intent">Tutorial</a> * @param position position in a list of video. */ @Override public void onMovieVideoClicked(int position) { // go to youtube intent with data MovieVideosResponse.MovieVideo video = mMovieVideosAdapter.getItem(position); if (video != null && video.isYoutubeVideo()) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + video.getKey())); startActivity(intent); } } /** * declare reviews recyclerview */ @Override public void declareReviewList() { // : 8/9/2016 9c listen when click the review mMovieVideosAdapter.setMOnItemClickListener((itemView, position) -> onMovieReviewClicked(position)); movieReviews.setAdapter(mMovieReviewsAdapter); movieReviews.setItemAnimator(new DefaultItemAnimator()); movieReviews.setLayoutManager(new LinearLayoutManager(getContext())); } /** * if you click one review among any reviews, call this method * pass the url to another viewer in your device via Intent to see full reviews. * @param position */ @Override public void onMovieReviewClicked(int position) { MovieReviewsResponse.MovieReview review = mMovieReviewsAdapter.getItem(position); if (review != null && review.getReviewUrl() != null) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(review.getReviewUrl())); startActivity(intent); } } @DebugLog @Override public void setPresenter(DetailMovieContract.Presenter presenter) { checkNotNull(presenter, "Presenter in MovieDetailFragment not be null"); mPresenter = presenter; } /** * setup the object graph and inject the dependencies needed on this fragment. */ @Override protected void injectDependencies() { // Create adapter DaggerDetailMovieViewComponent .builder() .movieComponent(((MVPApp) getActivity().getApplication()).getMovieComponent()) .movieVideosAdapterModule(new MovieVideosAdapterModule()) .movieReviewsAdapterModule(new MovieReviewsAdapterModule()) .build() .inject(this); } @Override protected void doThingWhenCreateApp() { getIntent(); } // : 8/9/2016 6 get the movie values @Override public void getIntent() { if (getArguments() != null) { mMovie = getArguments().getParcelable(ARG_MOVIE); } } @Override protected void doThingWhenActivityCreated() { } @Override protected void doThingWhenResumeApp() { mPresenter.start(); // : 8/9/2016 11 load list of video from network // : 8/9/2016 12 load list of reviews from network // : 8/9/2016 13 set hide or show videos // : 8/9/2016 14 set hide or show reviews } /** * see if the video adapter whether have empty datas or not, * if it has empty data, connect to network to load * * @return the state that indicate that we can load data or not */ @Override public boolean shouldLoadVideosFromNetwork() { if (mMovieVideosAdapter.getItemCount() == 0) { return true; } return false; } /** * see if the review adapter whether have empty datas or not, * if it has empty data, connect to network to load * * @return the state that indicate that we can load data or not */ @Override public boolean shouldLoadReviewsFromNetwork() { if (mMovieReviewsAdapter.getItemCount() == 0) { return true; } return false; } /** * get the id of a movie * * @return movie ID */ @Override public long getMovieId() { return mMovie.getId(); } /** * make the view adapter chagne the data * * @param movieVideos */ @Override public void makeVideoAdapterChangeData(ArrayList<MovieVideosResponse.MovieVideo> movieVideos) { mMovieVideosAdapter.setMovieVideos(movieVideos); } /** * make the review adapter change the data * * @param movieReviews */ @Override public void makeReviewAdapterChangeData(ArrayList<MovieReviewsResponse.MovieReview> movieReviews) { mMovieReviewsAdapter.setMovieReviews(movieReviews); } /** * set hide or show videos list depends on datas from video list which has download from network */ @Override public void setShowOrHideVideoList() { if (mMovieVideosAdapter == null || mMovieVideosAdapter.getItemCount() == 0) { cardMovieVideos.setVisibility(View.GONE); } else { cardMovieVideos.setVisibility(View.VISIBLE); } } /** * set hide or show reviews list depends on datas from video list which has download from network */ @Override public void setShowOrHideReviewList() { if (mMovieReviewsAdapter == null || mMovieReviewsAdapter.getItemCount() == 0) { cardMovieReviews.setVisibility(View.GONE); } else { cardMovieReviews.setVisibility(View.VISIBLE); } } @Override protected void doThingWhenPauseApp() { } @Override protected void doThingWhenDestroyApp() { } @Override protected String getTitle() { return null; } }
f9bf6a290f40eaa7ad0b2f19e31f59606989147b
ce11412173174fe680c45476f4fd0e39e81b9e2d
/src/com/dao/AccountListDAO.java
0b2d20e40ef26fd1119fb690bf64f2790936e52b
[]
no_license
yetao0707/PFinance
c0962c789c32ec809521fa20f44ac159bc6a5bd7
0a010c8209ae9e32dbe45242f8deaf6579826596
refs/heads/master
2021-01-18T03:33:50.728890
2017-05-16T01:16:56
2017-05-16T01:16:56
85,810,542
0
0
null
null
null
null
UTF-8
Java
false
false
573
java
package com.dao; import java.util.List; import com.commons.page.Page; import com.vo.fp.AccountListVO; import org.apache.ibatis.annotations.Param; public interface AccountListDAO extends BaseDao<AccountListVO> { public AccountListVO find(AccountListVO vo); public int insert(AccountListVO vo); public void update(AccountListVO vo); public void delete(AccountListVO vo); public int queryTotalNum(); public List<AccountListVO> findPageList(@Param("leftIndex") int leftIndex, @Param("rightIndex") int rightIndex); }
9bf655285e8fdede01c24db36804bb11acc035a0
716b231c89805b3e1217c6fc0a4ff9fbcdcdb688
/train_app_dev/src/com/l9e/train/channel/request/impl/ManualRequest.java
1341aa150835f5bd2ba20574ce0c5410dd597787
[]
no_license
d0l1u/train_ticket
32b831e441e3df73d55559bc416446276d7580be
c385cb36908f0a6e9e4a6ebb9b3ad737edb664d7
refs/heads/master
2020-06-14T09:00:34.760326
2019-07-03T00:30:46
2019-07-03T00:30:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
449
java
package com.l9e.train.channel.request.impl; import com.l9e.train.po.Account; import com.l9e.train.po.Order; import com.l9e.train.po.Result; import com.l9e.train.po.Worker; public class ManualRequest extends RequestImpl { public ManualRequest(Account account, Worker worker) { super(account, worker); } @Override public Result request(Order order,String weight, String logid) { result.setRetValue(Result.SUCCESS); return result; } }
[ "meizs" ]
meizs
cf16833ae6e921c6329501892895a2f7ad3a5bc3
71b7d664ee1127a7d12e87f7cbf21ca2db671855
/src/main/java/org/ednovo/gooru/client/mvp/assessments/play/resource/body/IsAssessmentsResourcePlayerMetadataView.java
7175ef09d22117213606c182a70f9166ce5be477
[ "MIT" ]
permissive
suryanarayanakb/Gooru-Web
f356594323e724f87bcea309fd11ebec1f8ebf7e
88b3bc9299183324bf7be451d662b61608d7462c
refs/heads/master
2021-01-20T11:29:51.006639
2015-08-21T06:38:31
2015-08-21T06:38:31
19,138,052
0
0
null
null
null
null
UTF-8
Java
false
false
4,097
java
/******************************************************************************* * Copyright 2013 Ednovo d/b/a Gooru. All rights reserved. * * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package org.ednovo.gooru.client.mvp.assessments.play.resource.body; import java.util.List; import java.util.Map; import org.ednovo.gooru.application.client.gin.IsViewWithHandlers; import org.ednovo.gooru.application.shared.model.content.CollectionItemDo; import org.ednovo.gooru.application.shared.model.content.ReactionDo; import org.ednovo.gooru.application.shared.model.content.ResourceTagsDo; import org.ednovo.gooru.application.shared.model.content.StarRatingsDo; import org.ednovo.gooru.client.htmltags.SectionTag; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlowPanel; import com.gwtplatform.mvp.client.proxy.PlaceRequest; public interface IsAssessmentsResourcePlayerMetadataView extends IsViewWithHandlers<AssessmentsResourcePlayerMetadataUiHandlers>{ public void showResourceWidget(CollectionItemDo collectionItemDo,PlaceRequest nextResoruceRequest,PlaceRequest previousResourceRequest); public void showResourceWidget(CollectionItemDo collectionItemDo); public void showResourceWidget(PlaceRequest previousResourceRequest); public SectionTag getResourceWidgetContainer(); public SectionTag getCollectionContainer(); public void setReaction(ReactionDo reactionDo, String gooruReactionId); public void setDefaultReaction(); public void setUserStarRatings(StarRatingsDo result, boolean showThankYouToolTip); public void setDefaultUserStarRatings(); public void removeRatingContainer(boolean flag); public void postReview(String assocGooruOId, String userReview, Integer score, boolean isUpdate); public void hideThankYouPopUp(); public void setRatingMetaData(String assocGooruOid, Integer score,String review, double average, Integer count); public void displaySuccessPopup(); public void updateRatingOnSearch(StarRatingsDo starRatingsDo); public void clearAllStarsForAnnonymous(); public void childLoggedIn(boolean isChild); public void deleteRatingsValue(); public void setGoogleDriveFileStatusCode(Integer statusCode); public void displayResourceTags(List<ResourceTagsDo> resourceTagsList); public void checkYoutubeAccessControls(Map<String, String> result); public Button getNarrationButton(); public Button getFullScreenButton(); public void clearMarginTop(); public void setMarginTop(); public void setPreviousRating(double previousRating); public double getPreviousRating(); public void setFullScreen(boolean isFullScreen,FlowPanel pnlFullScreenNarration); /** * * @function navigateToNextResource * * @created_date : 09-Jul-2015 * * @description * * * @parm(s) : @param resourceRequest * * @return : void * * @throws : <Mentioned if any exceptions> * * * * */ void navigateToNextResource(PlaceRequest resourceRequest); }
cd8a73aa21e6e622e8d86548a2beaf8e0498a3b3
49b4cb79c910a17525b59d4b497a09fa28a9e3a8
/parserValidCheck/src/main/java/com/ke/css/cimp/ffm/ffm2/Parser.java
ef9a331bbdc0264fcfc52f0d8e7c47af13432ccd
[]
no_license
ganzijo/koreanair
a7d750b62cec2647bfb2bed4ca1bf8648d9a447d
e980fb11bc4b8defae62c9d88e5c70a659bef436
refs/heads/master
2021-04-26T22:04:17.478461
2018-03-06T05:59:32
2018-03-06T05:59:32
124,018,887
0
0
null
null
null
null
UTF-8
Java
false
false
18,839
java
package com.ke.css.cimp.ffm.ffm2; /* ----------------------------------------------------------------------------- * Parser.java * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Fri Feb 23 10:52:50 KST 2018 * * ----------------------------------------------------------------------------- */ import java.util.Stack; import java.util.Properties; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.InputStream; import java.io.IOException; public class Parser { public Parser() {} static public void main(String[] args) { Properties arguments = new Properties(); String error = ""; boolean ok = args.length > 0; if (ok) { arguments.setProperty("Trace", "Off"); arguments.setProperty("Rule", "MESSAGE"); for (int i = 0; i < args.length; i++) { if (args[i].equals("-trace")) arguments.setProperty("Trace", "On"); else if (args[i].equals("-visitor")) arguments.setProperty("Visitor", args[++i]); else if (args[i].equals("-file")) arguments.setProperty("File", args[++i]); else if (args[i].equals("-string")) arguments.setProperty("String", args[++i]); else if (args[i].equals("-rule")) arguments.setProperty("Rule", args[++i]); else { error = "unknown argument: " + args[i]; ok = false; } } } if (ok) { if (arguments.getProperty("File") == null && arguments.getProperty("String") == null) { error = "insufficient arguments: -file or -string required"; ok = false; } } if (!ok) { System.out.println("error: " + error); System.out.println("usage: Parser [-rule rulename] [-trace] <-file file | -string string> [-visitor visitor]"); } else { try { Rule rule = null; if (arguments.getProperty("File") != null) { rule = parse( arguments.getProperty("Rule"), new File(arguments.getProperty("File")), arguments.getProperty("Trace").equals("On")); } else if (arguments.getProperty("String") != null) { rule = parse( arguments.getProperty("Rule"), arguments.getProperty("String"), arguments.getProperty("Trace").equals("On")); } if (arguments.getProperty("Visitor") != null) { Visitor visitor = (Visitor)Class.forName(arguments.getProperty("Visitor")).newInstance(); rule.accept(visitor); } } catch (IllegalArgumentException e) { System.out.println("argument error: " + e.getMessage()); } catch (IOException e) { System.out.println("io error: " + e.getMessage()); } catch (ParserException e) { System.out.println("parser error: " + e.getMessage()); } catch (ClassNotFoundException e) { System.out.println("visitor error: class not found - " + e.getMessage()); } catch (IllegalAccessException e) { System.out.println("visitor error: illegal access - " + e.getMessage()); } catch (InstantiationException e) { System.out.println("visitor error: instantiation failure - " + e.getMessage()); } } } static public Rule parse(String rulename, String string) throws IllegalArgumentException, ParserException { return parse(rulename, string, false); } static public Rule parse(String rulename, InputStream in) throws IllegalArgumentException, IOException, ParserException { return parse(rulename, in, false); } static public Rule parse(String rulename, File file) throws IllegalArgumentException, IOException, ParserException { return parse(rulename, file, false); } static private Rule parse(String rulename, String string, boolean trace) throws IllegalArgumentException, ParserException { if (rulename == null) throw new IllegalArgumentException("null rulename"); if (string == null) throw new IllegalArgumentException("null string"); ParserContext context = new ParserContext(string, trace); Rule rule = null; if (rulename.equalsIgnoreCase("MESSAGE")) rule = Rule_MESSAGE.parse(context); else if (rulename.equalsIgnoreCase("FFM")) rule = Rule_FFM.parse(context); else if (rulename.equalsIgnoreCase("HEADER")) rule = Rule_HEADER.parse(context); else if (rulename.equalsIgnoreCase("SMI")) rule = Rule_SMI.parse(context); else if (rulename.equalsIgnoreCase("MFH")) rule = Rule_MFH.parse(context); else if (rulename.equalsIgnoreCase("FLIGHT_NUMBER")) rule = Rule_FLIGHT_NUMBER.parse(context); else if (rulename.equalsIgnoreCase("FLIGHT_DATE")) rule = Rule_FLIGHT_DATE.parse(context); else if (rulename.equalsIgnoreCase("Grp_AIRCRAFT_REGISTRATION")) rule = Rule_Grp_AIRCRAFT_REGISTRATION.parse(context); else if (rulename.equalsIgnoreCase("Grp_First_Point_of_Arrival_Information")) rule = Rule_Grp_First_Point_of_Arrival_Information.parse(context); else if (rulename.equalsIgnoreCase("DST")) rule = Rule_DST.parse(context); else if (rulename.equalsIgnoreCase("AWB")) rule = Rule_AWB.parse(context); else if (rulename.equalsIgnoreCase("Grp_AWB")) rule = Rule_Grp_AWB.parse(context); else if (rulename.equalsIgnoreCase("AWB_NUMBER")) rule = Rule_AWB_NUMBER.parse(context); else if (rulename.equalsIgnoreCase("Grp_Quantity_Detail")) rule = Rule_Grp_Quantity_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_Volume_Detail")) rule = Rule_Grp_Volume_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_Density_Group")) rule = Rule_Grp_Density_Group.parse(context); else if (rulename.equalsIgnoreCase("Grp_Total_Consignment_Pieces")) rule = Rule_Grp_Total_Consignment_Pieces.parse(context); else if (rulename.equalsIgnoreCase("Grp_Nature_of_Goods")) rule = Rule_Grp_Nature_of_Goods.parse(context); else if (rulename.equalsIgnoreCase("Grp_Special_Handling_Requirements")) rule = Rule_Grp_Special_Handling_Requirements.parse(context); else if (rulename.equalsIgnoreCase("DIM")) rule = Rule_DIM.parse(context); else if (rulename.equalsIgnoreCase("DIMS")) rule = Rule_DIMS.parse(context); else if (rulename.equalsIgnoreCase("CMI")) rule = Rule_CMI.parse(context); else if (rulename.equalsIgnoreCase("CMIS")) rule = Rule_CMIS.parse(context); else if (rulename.equalsIgnoreCase("Grp_Onward_Routing_Detail")) rule = Rule_Grp_Onward_Routing_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_Onward_Booking_Detail")) rule = Rule_Grp_Onward_Booking_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_Movement_Priority")) rule = Rule_Grp_Movement_Priority.parse(context); else if (rulename.equalsIgnoreCase("OSI")) rule = Rule_OSI.parse(context); else if (rulename.equalsIgnoreCase("Grp_OSI_Details_1st_Line")) rule = Rule_Grp_OSI_Details_1st_Line.parse(context); else if (rulename.equalsIgnoreCase("Grp_OSI_Details_2nd_Line")) rule = Rule_Grp_OSI_Details_2nd_Line.parse(context); else if (rulename.equalsIgnoreCase("SCI")) rule = Rule_SCI.parse(context); else if (rulename.equalsIgnoreCase("ULD")) rule = Rule_ULD.parse(context); else if (rulename.equalsIgnoreCase("ULD_INFORMATION")) rule = Rule_ULD_INFORMATION.parse(context); else if (rulename.equalsIgnoreCase("Grp_ULD_Position_Information")) rule = Rule_Grp_ULD_Position_Information.parse(context); else if (rulename.equalsIgnoreCase("Grp_ULD_Remarks")) rule = Rule_Grp_ULD_Remarks.parse(context); else if (rulename.equalsIgnoreCase("UMI")) rule = Rule_UMI.parse(context); else if (rulename.equalsIgnoreCase("UMIS")) rule = Rule_UMIS.parse(context); else if (rulename.equalsIgnoreCase("Grp_ULD_Onward_Routing_Detail")) rule = Rule_Grp_ULD_Onward_Routing_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_ULD_Onward_Booking_Detail")) rule = Rule_Grp_ULD_Onward_Booking_Detail.parse(context); else if (rulename.equalsIgnoreCase("Grp_ULD_Utilisation_Detail")) rule = Rule_Grp_ULD_Utilisation_Detail.parse(context); else if (rulename.equalsIgnoreCase("MCI")) rule = Rule_MCI.parse(context); else if (rulename.equalsIgnoreCase("STANDARD_MESSAGE_IDENTIFIER")) rule = Rule_STANDARD_MESSAGE_IDENTIFIER.parse(context); else if (rulename.equalsIgnoreCase("MId_MFH")) rule = Rule_MId_MFH.parse(context); else if (rulename.equalsIgnoreCase("MId_DIM")) rule = Rule_MId_DIM.parse(context); else if (rulename.equalsIgnoreCase("MId_OSI")) rule = Rule_MId_OSI.parse(context); else if (rulename.equalsIgnoreCase("MId_SCI")) rule = Rule_MId_SCI.parse(context); else if (rulename.equalsIgnoreCase("MId_ULD")) rule = Rule_MId_ULD.parse(context); else if (rulename.equalsIgnoreCase("IF_HUB_REFERENCE_KEY")) rule = Rule_IF_HUB_REFERENCE_KEY.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_TYPE")) rule = Rule_MESSAGE_TYPE.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_SUBTYPE")) rule = Rule_MESSAGE_SUBTYPE.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_RECEIVER")) rule = Rule_MESSAGE_RECEIVER.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_SENDER")) rule = Rule_MESSAGE_SENDER.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_TYPE_VERSION_NUMBER")) rule = Rule_MESSAGE_TYPE_VERSION_NUMBER.parse(context); else if (rulename.equalsIgnoreCase("MESSAGE_SEQUENCE_NUMBER")) rule = Rule_MESSAGE_SEQUENCE_NUMBER.parse(context); else if (rulename.equalsIgnoreCase("Sub_Day_of_Scheduled_Departure")) rule = Rule_Sub_Day_of_Scheduled_Departure.parse(context); else if (rulename.equalsIgnoreCase("Sub_Month_of_Scheduled_Departure")) rule = Rule_Sub_Month_of_Scheduled_Departure.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CODE_OF_LOADING")) rule = Rule_AIRPORT_CODE_OF_LOADING.parse(context); else if (rulename.equalsIgnoreCase("AIRCRAFT_REGISTRATION")) rule = Rule_AIRCRAFT_REGISTRATION.parse(context); else if (rulename.equalsIgnoreCase("ISO_COUNTRY_CODE")) rule = Rule_ISO_COUNTRY_CODE.parse(context); else if (rulename.equalsIgnoreCase("DAY_OF_SCHEDULED_ARRIVAL")) rule = Rule_DAY_OF_SCHEDULED_ARRIVAL.parse(context); else if (rulename.equalsIgnoreCase("MONTH_OF_SCHEDULED_ARRIVAL")) rule = Rule_MONTH_OF_SCHEDULED_ARRIVAL.parse(context); else if (rulename.equalsIgnoreCase("TIME_OF_SCHEDULED_ARRIVAL")) rule = Rule_TIME_OF_SCHEDULED_ARRIVAL.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CITY_CODE_OF_ARRV")) rule = Rule_AIRPORT_CITY_CODE_OF_ARRV.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CODE_OF_UNLOADING")) rule = Rule_AIRPORT_CODE_OF_UNLOADING.parse(context); else if (rulename.equalsIgnoreCase("NIL_CARGO_CODE")) rule = Rule_NIL_CARGO_CODE.parse(context); else if (rulename.equalsIgnoreCase("DAY_OF_SCHEDULED_DPRT")) rule = Rule_DAY_OF_SCHEDULED_DPRT.parse(context); else if (rulename.equalsIgnoreCase("MONTH_OF_SCHEDULED_DPRT")) rule = Rule_MONTH_OF_SCHEDULED_DPRT.parse(context); else if (rulename.equalsIgnoreCase("TIME_OF_SCHEDULED_DPRT")) rule = Rule_TIME_OF_SCHEDULED_DPRT.parse(context); else if (rulename.equalsIgnoreCase("Sub_AWB_Prefix")) rule = Rule_Sub_AWB_Prefix.parse(context); else if (rulename.equalsIgnoreCase("Sub_AWB_SerialNum")) rule = Rule_Sub_AWB_SerialNum.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CITY_CODE_OF_ORIGIN")) rule = Rule_AIRPORT_CITY_CODE_OF_ORIGIN.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CITY_CODE_OF_DEST")) rule = Rule_AIRPORT_CITY_CODE_OF_DEST.parse(context); else if (rulename.equalsIgnoreCase("SHIPMENT_DESCRIPTION_CODE")) rule = Rule_SHIPMENT_DESCRIPTION_CODE.parse(context); else if (rulename.equalsIgnoreCase("NUMBER_OF_PIECES")) rule = Rule_NUMBER_OF_PIECES.parse(context); else if (rulename.equalsIgnoreCase("WEIGHT_CODE")) rule = Rule_WEIGHT_CODE.parse(context); else if (rulename.equalsIgnoreCase("WEIGHT")) rule = Rule_WEIGHT.parse(context); else if (rulename.equalsIgnoreCase("VOLUME_CODE")) rule = Rule_VOLUME_CODE.parse(context); else if (rulename.equalsIgnoreCase("VOLUME_AMOUNT")) rule = Rule_VOLUME_AMOUNT.parse(context); else if (rulename.equalsIgnoreCase("Hid_Density_Indicator")) rule = Rule_Hid_Density_Indicator.parse(context); else if (rulename.equalsIgnoreCase("DENSITY_GROUP")) rule = Rule_DENSITY_GROUP.parse(context); else if (rulename.equalsIgnoreCase("Hid_Shipment_Description_Code_T")) rule = Rule_Hid_Shipment_Description_Code_T.parse(context); else if (rulename.equalsIgnoreCase("NUMBER_OF_TOTAL_PIECES")) rule = Rule_NUMBER_OF_TOTAL_PIECES.parse(context); else if (rulename.equalsIgnoreCase("MANIFEST_DESC_OF_GOODS")) rule = Rule_MANIFEST_DESC_OF_GOODS.parse(context); else if (rulename.equalsIgnoreCase("SPECIAL_HANDLING_CODE")) rule = Rule_SPECIAL_HANDLING_CODE.parse(context); else if (rulename.equalsIgnoreCase("MEASUREMENT_UNIT_CODE")) rule = Rule_MEASUREMENT_UNIT_CODE.parse(context); else if (rulename.equalsIgnoreCase("LENGTH_DIMENSION")) rule = Rule_LENGTH_DIMENSION.parse(context); else if (rulename.equalsIgnoreCase("WIDTH_DIMENSION")) rule = Rule_WIDTH_DIMENSION.parse(context); else if (rulename.equalsIgnoreCase("HEIGHT_DIMENSION")) rule = Rule_HEIGHT_DIMENSION.parse(context); else if (rulename.equalsIgnoreCase("NUMBERS_OF_PIECES")) rule = Rule_NUMBERS_OF_PIECES.parse(context); else if (rulename.equalsIgnoreCase("AIRPORT_CODE_OF_NEXT_DEST")) rule = Rule_AIRPORT_CODE_OF_NEXT_DEST.parse(context); else if (rulename.equalsIgnoreCase("CARRIER_CODE")) rule = Rule_CARRIER_CODE.parse(context); else if (rulename.equalsIgnoreCase("MOVEMENT_PRIORITY_CODE")) rule = Rule_MOVEMENT_PRIORITY_CODE.parse(context); else if (rulename.equalsIgnoreCase("OTHER_SERVICE_INFORMATION_1")) rule = Rule_OTHER_SERVICE_INFORMATION_1.parse(context); else if (rulename.equalsIgnoreCase("OTHER_SERVICE_INFORMATION_2")) rule = Rule_OTHER_SERVICE_INFORMATION_2.parse(context); else if (rulename.equalsIgnoreCase("Hid_Customs_Reference")) rule = Rule_Hid_Customs_Reference.parse(context); else if (rulename.equalsIgnoreCase("CUSTOMS_ORIGIN_CODE")) rule = Rule_CUSTOMS_ORIGIN_CODE.parse(context); else if (rulename.equalsIgnoreCase("Sub_ULD_Type")) rule = Rule_Sub_ULD_Type.parse(context); else if (rulename.equalsIgnoreCase("Sub_ULD_Serial_Number")) rule = Rule_Sub_ULD_Serial_Number.parse(context); else if (rulename.equalsIgnoreCase("Sub_ULD_Owner_Code")) rule = Rule_Sub_ULD_Owner_Code.parse(context); else if (rulename.equalsIgnoreCase("ULD_LOADING_INDICATOR")) rule = Rule_ULD_LOADING_INDICATOR.parse(context); else if (rulename.equalsIgnoreCase("ULD_REMARKS")) rule = Rule_ULD_REMARKS.parse(context); else if (rulename.equalsIgnoreCase("ULD_VOLUME_AVAILABLE_CODE")) rule = Rule_ULD_VOLUME_AVAILABLE_CODE.parse(context); else if (rulename.equalsIgnoreCase("END_OF_MESSAGE_CODE")) rule = Rule_END_OF_MESSAGE_CODE.parse(context); else if (rulename.equalsIgnoreCase("Sep_CRLF")) rule = Rule_Sep_CRLF.parse(context); else if (rulename.equalsIgnoreCase("CR")) rule = Rule_CR.parse(context); else if (rulename.equalsIgnoreCase("LF")) rule = Rule_LF.parse(context); else if (rulename.equalsIgnoreCase("Sep_Slant")) rule = Rule_Sep_Slant.parse(context); else if (rulename.equalsIgnoreCase("Sep_Bar")) rule = Rule_Sep_Bar.parse(context); else if (rulename.equalsIgnoreCase("Typ_Alpha")) rule = Rule_Typ_Alpha.parse(context); else if (rulename.equalsIgnoreCase("Typ_Numeric")) rule = Rule_Typ_Numeric.parse(context); else if (rulename.equalsIgnoreCase("Typ_Decimal")) rule = Rule_Typ_Decimal.parse(context); else if (rulename.equalsIgnoreCase("Typ_Mixed")) rule = Rule_Typ_Mixed.parse(context); else if (rulename.equalsIgnoreCase("Typ_Text")) rule = Rule_Typ_Text.parse(context); else throw new IllegalArgumentException("unknown rule"); if (rule == null) { throw new ParserException( "rule \"" + (String)context.getErrorStack().peek() + "\" failed", context.text, context.getErrorIndex(), context.getErrorStack()); } if (context.text.length() > context.index) { ParserException primaryError = new ParserException( "extra data found", context.text, context.index, new Stack<String>()); if (context.getErrorIndex() > context.index) { ParserException secondaryError = new ParserException( "rule \"" + (String)context.getErrorStack().peek() + "\" failed", context.text, context.getErrorIndex(), context.getErrorStack()); primaryError.initCause(secondaryError); } throw primaryError; } return rule; } static private Rule parse(String rulename, InputStream in, boolean trace) throws IllegalArgumentException, IOException, ParserException { if (rulename == null) throw new IllegalArgumentException("null rulename"); if (in == null) throw new IllegalArgumentException("null input stream"); int ch = 0; StringBuffer out = new StringBuffer(); while ((ch = in.read()) != -1) out.append((char)ch); return parse(rulename, out.toString(), trace); } static private Rule parse(String rulename, File file, boolean trace) throws IllegalArgumentException, IOException, ParserException { if (rulename == null) throw new IllegalArgumentException("null rulename"); if (file == null) throw new IllegalArgumentException("null file"); BufferedReader in = new BufferedReader(new FileReader(file)); int ch = 0; StringBuffer out = new StringBuffer(); while ((ch = in.read()) != -1) out.append((char)ch); in.close(); return parse(rulename, out.toString(), trace); } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
[ "wrjo@wrjo-PC" ]
wrjo@wrjo-PC
95a14a1aca0dd2c4e01fa3115f8dcfd0f029e7bd
81a2b6bd194b9de917936dcc3c0d3ad8c264a207
/src/main/java/org/davidmoten/kool/internal/util/StreamUtils.java
0a7211f30142343e123a794c0db63480db59a079
[ "Apache-2.0" ]
permissive
MaTriXy/kool
fbe24cf1195c1bb2a62c0419546df062abce5862
501a014a54c89ac00b868ac1964bd1b28cbf46c7
refs/heads/master
2020-04-10T12:29:43.393477
2018-12-07T22:31:14
2018-12-07T22:31:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
990
java
package org.davidmoten.kool.internal.util; import java.util.Collections; import org.davidmoten.kool.Stream; import org.davidmoten.kool.StreamIterable; import org.davidmoten.kool.StreamIterator; import org.davidmoten.kool.function.Function; import com.github.davidmoten.guavamini.Preconditions; public final class StreamUtils { private StreamUtils() { // prevent instantiation } public static final class EmptyHolder { public static final Stream<Object> EMPTY = Stream.create(Collections.emptyList()); } public static final class FunctionIdentityHolder { public static final Function<Object, Object> IDENTITY = x -> x; } public static <T> StreamIterator<T> iterator(StreamIterable<T> iter) { return Preconditions.checkNotNull(iter.iterator(), "iterator cannot be null"); } public static <T> T next(StreamIterator<T> it) { return Preconditions.checkNotNull(it.next(), "upstream cannot emit null"); } }
8ada487a96e667a11d622c307ca4ef286ce147aa
f76f1f306c7f68c34e8edc0225a1d404a0aa3897
/app/src/main/java/com/googlecode/javacpp/annotation/NoOffset.java
f59c14d45304845e8b8919a4469bb80c31b1f892
[]
no_license
Bingle-labake/Vine15
b8a2852bf43e295a63c976d2fa263b301036807d
b75665ff848df0d526ec0f26d64516629c150b33
refs/heads/master
2016-09-01T05:59:05.804172
2015-10-31T07:40:04
2015-10-31T07:40:04
45,291,739
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package com.googlecode.javacpp.annotation; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD}) public @interface NoOffset { } /* Location: /Users/dantheman/src/android/decompiled/vine-decompiled/dex2jar/classes-dex2jar.jar * Qualified Name: com.googlecode.javacpp.annotation.NoOffset * JD-Core Version: 0.6.2 */
b2f3b7cf1b4d2739904e4dcc08274e5e8ce0d49a
2c2f2fd0f1ba7015eb1a598909919a6101419247
/ModernTechniques/DataStructures/01-Rational/Rational.java
86a8366c10062fb6754e0d663f77d37d73a7cd41
[]
no_license
immortalkrazy/ModernTechniques
fc30735e32c39522ec36a98eaf334bacdad71cbd
3975a818ec3cba6a35c24f1df05a03f71b3e61f7
refs/heads/master
2022-01-24T20:20:46.298453
2022-01-13T04:05:06
2022-01-13T04:05:06
188,884,801
0
0
null
null
null
null
UTF-8
Java
false
false
1,542
java
public class Rational implements Comparable<Rational> { private int numer; private int denom; public Rational(int numer, int denom) { this.numer = numer; this.denom = denom; int divisor = Rational.gcd(numer, denom); this.numer /= divisor; this.denom /= divisor; } public Rational(int numer) { this(numer, 1); } public int getNumer() { return numer; } public int getDenom() { return denom; } public String toString() { return numer +(denom==1?"" : "/" + denom); } public Rational multiply(Rational another) { int newNumer = this.numer * another.numer; int newDenom = this.denom * another.denom; return new Rational(newNumer, newDenom); } public boolean equals(Object obj) { if( ! (obj instanceof Rational)) return false; Rational another = (Rational)obj; return this.compareTo(another)==0; } public int compareTo(Rational another) { int numer1 = this.numer * another.denom; int numer2 = another.numer * this.denom; return numer1 - numer2; } private static int gcd(int a, int b) { return b==0? a : gcd(b, a%b); } public static void main(String[] args) { Rational r1 = new Rational(2,4); System.out.println(r1); Rational r2 = new Rational(50,10); System.out.println(r2); Rational r3 = new Rational(2); System.out.println(r3.compareTo(r1)); Comparable<Rational> comp= new Rational(1); Rational r4 = ((Rational)comp).multiply(r1); System.out.println(r4); } }
0c2cec4f38f43fc496467df9ed576e1915a818fc
9aae6311f137303f76e43122aaf11429547efed5
/toughenlib/src/main/java/com/toughen/libs/http/OkHttpManager.java
c273bd11603c914622148204c3111617215be6e7
[]
no_license
Tracy-MacGrady/Toughen
9725edee38a697c8ca1035e1369aea781648bcb5
733ff8935160c27f3060f094f6bbb8564c1cc066
refs/heads/master
2020-03-09T15:29:00.562415
2019-01-16T09:15:09
2019-01-16T09:15:09
117,214,033
0
0
null
null
null
null
UTF-8
Java
false
false
6,013
java
package com.toughen.libs.http; import android.content.Context; import com.toughen.libs.tools.LogUtils; import com.toughen.libs.tools.NetworkUtils; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by lijianjian on 2018/4/8. */ public class OkHttpManager { private static final long CONNECT_TIME_OUT = 5;//连接超时限定值 private static final long READ_TIME_OUT = 5;//请求超时限定值 private static volatile OkHttpManager instance; private OkHttpManager() { } public static OkHttpManager getInstance() { if (instance == null) synchronized (OkHttpManager.class) { if (instance == null) instance = new OkHttpManager(); } return instance; } public void getRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, CookieJar cookieJar, ResponseDataDispatchInterface dispatchListener) { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).cookieJar(cookieJar).build(); initGetRequest(context, requestPath, params, headerMap, dispatchListener, client); } public void getRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, ResponseDataDispatchInterface dispatchListener) { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).build(); initGetRequest(context, requestPath, params, headerMap, dispatchListener, client); } private void initGetRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, ResponseDataDispatchInterface dispatchListener, OkHttpClient client) { if (!NetworkUtils.getInstance().checkNet(context)) { if (dispatchListener != null) dispatchListener.onFailure("请检查您的网络!"); return; } Headers.Builder headerBuilder = new Headers.Builder(); if (params != null && params.size() > 0) { StringBuffer paramsStr = new StringBuffer(); Iterator<String> iterator = params.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = params.get(key); paramsStr.append("&"); paramsStr.append(key); paramsStr.append("="); paramsStr.append(value); } requestPath = requestPath + "?" + paramsStr.toString().trim().substring(1); } if (headerMap != null && headerMap.size() > 0) { Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String key = headerIterator.next(); String value = headerMap.get(key); headerBuilder.add(key, value); } } LogUtils.e("REQUEST_PATH", requestPath); Request request = new Request.Builder().url(requestPath).headers(headerBuilder.build()).get().build(); Call call = client.newCall(request); call.enqueue(new ToughenLibOKHttpCallback(dispatchListener)); } public void postRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, CookieJar cookieJar, ResponseDataDispatchInterface dispatchListener) { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).cookieJar(cookieJar).build(); initPostRequest(context, requestPath, params, headerMap, dispatchListener, client); } public void postRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, ResponseDataDispatchInterface dispatchListener) { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).build(); initPostRequest(context, requestPath, params, headerMap, dispatchListener, client); } private void initPostRequest(Context context, String requestPath, HashMap<String, String> params, HashMap<String, String> headerMap, ResponseDataDispatchInterface dispatchListener, OkHttpClient client) { if (!NetworkUtils.getInstance().checkNet(context)) { if (dispatchListener != null) dispatchListener.onFailure("请检查您的网络!"); return; } Headers.Builder builder = new Headers.Builder(); FormBody.Builder bodyBuilder = new FormBody.Builder(); if (params != null && params.size() > 0) { Iterator<String> iterator = params.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = params.get(key); bodyBuilder.add(key, value); } } if (headerMap != null && headerMap.size() > 0) { Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String key = headerIterator.next(); String value = headerMap.get(key); builder.add(key, value); } } LogUtils.e("REQUEST_PATH", requestPath); Request request = new Request.Builder().url(requestPath).headers(builder.build()).post(bodyBuilder.build()).build(); Call call = client.newCall(request); call.enqueue(new ToughenLibOKHttpCallback(dispatchListener)); } }
02ed1a3a192176ed438b420e691ca6e9f4cc0d1e
833192eb6353744e07b909bb8ba761d2bc9d0649
/room-reservation-service/src/main/java/com/bezio/my/roomreservationservice/GuestClient.java
f5cc104aefe6d404bd9b8256dead7d8f633b460e
[]
no_license
Beziu/spring-cloud
dbcd86b83b4a62065047750c463a7ea44e7a847a
05f37a0e91c52da1319fc1be34f11c1a64eda44c
refs/heads/master
2023-07-30T13:56:29.555703
2021-10-04T19:39:55
2021-10-04T19:39:55
413,322,086
0
0
null
null
null
null
UTF-8
Java
false
false
453
java
package com.bezio.my.roomreservationservice; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @FeignClient("guestservices") public interface GuestClient { @GetMapping("/guests") List<Guest> getAllGuests(); @GetMapping("/guests/{id}") Guest getGuest(@PathVariable("id") long id); }
1b4620b52ad2bf725b895f4e924590c5e561d6e0
b4d5d3071bc0f781d46275577aa0e7b277f3689f
/SwitchCastEx/src/kr/co/ezen/MainEx.java
11956931d5b49aceadc62aec26c67525606bdde8
[]
no_license
woneeseo/javastudy
f388b3171bff81c812fc94b009c745ee4ba39499
de96d7a975bc63ad2b1268dce7dae7fc5b7e9c83
refs/heads/main
2023-01-28T17:03:59.012947
2020-12-07T08:43:40
2020-12-07T08:43:40
303,949,640
0
0
null
null
null
null
WINDOWS-1252
Java
false
false
559
java
package kr.co.ezen; import com.naver.Test; public class MainEx { public static void main(String[] args) { // TODO Auto-generated method stub Test t1 = new Test(); t1.me1(3); t1.me1(4); t1.me1(0); System.out.println(); t1.me2(3); t1.me2(4); System.out.println(); t1.me3(100); t1.me3(24); System.out.println(); t1.me6(6); System.out.println(); t1.me7(100); System.out.println(); System.out.println(); System.out.println(); t1.me8("¾È³ç", "¹Ý°¡"); t1.me9(1); t1.me9(2); t1.me9(3); } }
e4618b622a06276336c339b8ffeed9eb259b3f48
ee507d52f82399101dd0c9ec60707ae633f29d9c
/src/main/java/com/ballistic/velocity/model/dto/EmailDto.java
69e7453408702253a78244e27c2acda401bf8829
[]
no_license
NABEEL-AHMED-JAMIL/velocity
4035140a50b9393a2e38348c9eea3e357c430064
5371daf2b063de602a96a3954c8f8ab3350527f1
refs/heads/master
2020-04-10T05:43:03.765547
2019-02-11T12:17:32
2019-02-11T12:17:32
160,835,404
0
0
null
null
null
null
UTF-8
Java
false
false
1,440
java
package com.ballistic.velocity.model.dto; import com.ballistic.velocity.model.pojo.Document; import com.google.gson.Gson; import java.util.Set; public class EmailDto<T> { private Set<String> sendTo; private Set<String> ccTo; private String subject; private T field; private Document document; public EmailDto() {} public EmailDto(Set<String> sendTo, String subject, Document document) { this.sendTo = sendTo; this.subject = subject; this.document = document; } public EmailDto(Set<String> sendTo, Set<String> ccTo, String subject, Document document) { this.sendTo = sendTo; this.ccTo = ccTo; this.subject = subject; this.document = document; } public Set<String> getSendTo() { return sendTo; } public void setSendTo(Set<String> sendTo) { this.sendTo = sendTo; } public Set<String> getCcTo() { return ccTo; } public void setCcTo(Set<String> ccTo) { this.ccTo = ccTo; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public T getField() { return field; } public void setField(T field) { this.field = field; } public Document getDocument() { return document; } public void setDocument(Document document) { this.document = document; } @Override public String toString() { return new Gson().toJson(this); } }
9a46527b18c515e7d7715b21901546679eb60d06
181e5a35eea5180f7c097cef06ea45bb7ae40bff
/src/main/java/am/jsl/personalfinances/domain/reminder/Reminder.java
237db242ceb3548fe361a3850e72bf4ecdc5a563
[ "Apache-2.0" ]
permissive
hamletbarsamyan/personalfinances
7f39ce33446d977d4d0a74df04659dad24c41924
edd746560568376fbb54bb71bfbbfdccfcd5aad0
refs/heads/master
2022-11-20T15:27:24.356155
2021-12-19T13:49:55
2021-12-19T13:49:55
162,909,573
7
1
Apache-2.0
2022-11-16T01:40:19
2018-12-23T17:08:45
Java
UTF-8
Java
false
false
6,399
java
package am.jsl.personalfinances.domain.reminder; import am.jsl.personalfinances.domain.Descriptive; import am.jsl.personalfinances.domain.transaction.TransactionType; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; /** * The reminder domain object. * The reminders will be processed by reminder job based on reminder's due date * and transaction(s) will be created based this reminder configuration: * account, category, amount, transaction type, contact. * * @author hamlet */ public class Reminder extends Descriptive implements Serializable { /** * The status of reminder * @see ReminderStatus */ private byte status; /** * The due date of reminder */ private LocalDateTime dueDate; /** * The account id of reminder */ private long accountId; /** * The category id of reminder */ private long categoryId; /** * The amount of this reminder which will be used for creating transactions */ private double amount; /** * The transaction type of reminder(expense, income, transfer) * @see TransactionType */ private byte transactionType; /** * The contact id of reminder */ private long contactId; /** * If auto charge is true then a transaction will be created automatically */ private boolean autoCharge; /** * If repeat is true then this reminder will be processed repeatedly on each reminder job execution * @see ReminderRepeat */ private byte repeat; /** * Transfer transaction details * @see ReminderTransfer */ private ReminderTransfer reminderTransfer = null; /** * Returns true if the transaction type is transfer. * * @return true if the transaction type is transfer. */ public boolean isTransfer() { return transactionType == TransactionType.TRANSFER.getValue(); } /** * Getter for property 'status'. * * @return Value for property 'status'. */ public byte getStatus() { return status; } /** * Setter for property 'status'. * * @param status Value to set for property 'status'. */ public void setStatus(byte status) { this.status = status; } /** * Getter for property 'accountId'. * * @return Value for property 'accountId'. */ public long getAccountId() { return accountId; } /** * Setter for property 'accountId'. * * @param accountId Value to set for property 'accountId'. */ public void setAccountId(long accountId) { this.accountId = accountId; } /** * Getter for property 'categoryId'. * * @return Value for property 'categoryId'. */ public long getCategoryId() { return categoryId; } /** * Setter for property 'categoryId'. * * @param categoryId Value to set for property 'categoryId'. */ public void setCategoryId(long categoryId) { this.categoryId = categoryId; } /** * Getter for property 'amount'. * * @return Value for property 'amount'. */ public double getAmount() { return amount; } /** * Setter for property 'amount'. * * @param amount Value to set for property 'amount'. */ public void setAmount(double amount) { this.amount = amount; } /** * Getter for property 'transactionType'. * * @return Value for property 'transactionType'. */ public byte getTransactionType() { return transactionType; } /** * Setter for property 'transactionType'. * * @param transactionType Value to set for property 'transactionType'. */ public void setTransactionType(byte transactionType) { this.transactionType = transactionType; } /** * Getter for property 'contactId'. * * @return Value for property 'contactId'. */ public long getContactId() { return contactId; } /** * Setter for property 'contactId'. * * @param contactId Value to set for property 'contactId'. */ public void setContactId(long contactId) { this.contactId = contactId; } /** * Getter for property 'autoCharge'. * * @return Value for property 'autoCharge'. */ public boolean isAutoCharge() { return autoCharge; } /** * Setter for property 'autoCharge'. * * @param autoCharge Value to set for property 'autoCharge'. */ public void setAutoCharge(boolean autoCharge) { this.autoCharge = autoCharge; } /** * Getter for property 'repeat'. * * @return Value for property 'repeat'. */ public byte getRepeat() { return repeat; } /** * Setter for property 'repeat'. * * @param repeat Value to set for property 'repeat'. */ public void setRepeat(byte repeat) { this.repeat = repeat; } /** * Getter for property 'dueDate'. * * @return Value for property 'dueDate'. */ public LocalDateTime getDueDate() { return dueDate; } /** * Setter for property 'dueDate'. * * @param dueDate Value to set for property 'dueDate'. */ public void setDueDate(LocalDateTime dueDate) { this.dueDate = dueDate; } /** * Gets reminder transfer. * * @return the reminder transfer */ public ReminderTransfer getReminderTransfer() { return reminderTransfer; } /** * Sets reminder transfer. * * @param reminderTransfer the reminder transfer */ public void setReminderTransfer(ReminderTransfer reminderTransfer) { this.reminderTransfer = reminderTransfer; } @Override public int hashCode() { return Objects.hash(getId()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } final Reminder other = (Reminder) obj; return Objects.equals(this.getId(), other.getId()); } }
7d21d932b9596f2762510cb1dbc672b15b06a66f
68fd726d624ca6d9c79a2f7e85c4f20615b75713
/interpreter.pom/src/main/java/gov/nist/drmf/interpreter/pom/common/tests/AssumeMLPAvailabilityCondition.java
3be32a863e3b21b77e407dbd4e30efe10d3f3b40
[ "MIT" ]
permissive
gipplab/LaCASt
8d4a37d56fc8786c923503927a8c7311acb4129e
4b43b38eb639a09415f8531be059396f027f0129
refs/heads/master
2023-05-25T11:52:54.259189
2022-11-21T09:55:23
2022-11-21T09:55:23
71,908,351
4
0
MIT
2023-05-23T01:28:45
2016-10-25T14:58:33
Java
UTF-8
Java
false
false
763
java
package gov.nist.drmf.interpreter.pom.common.tests; import gov.nist.drmf.interpreter.pom.common.meta.AssumeMLPAvailability; import gov.nist.drmf.interpreter.common.tests.AssumeToolAvailabilityCondition; import gov.nist.drmf.interpreter.pom.MLPWrapper; /** * This class checks if MLP is available to run tests. * * @author Andre Greiner-Petter */ public class AssumeMLPAvailabilityCondition extends AssumeToolAvailabilityCondition<AssumeMLPAvailability> { @Override public Class<AssumeMLPAvailability> getInterface() { return AssumeMLPAvailability.class; } @Override public boolean isToolAvailable() { return MLPWrapper.isMLPPresent(); } @Override public String getToolName() { return "MLP"; } }
e546411ebc87f497deb4c98600dddd089ca34762
541bdf88436c63f8e53100d9151c0aed9d679f9f
/dataportal/src/main/java/com/boedq/modules/sys/controller/AbstractController.java
ab40da6f2864ae73ccb6ff886b76193656e3299b
[]
no_license
Gabine321/boewebproject
45404b7e0021cca51027a891d173a192abe782d1
ca5c65d31ef2cb6a205be6b0910ddf61647d70ad
refs/heads/master
2020-04-20T06:18:34.040587
2019-02-01T10:23:58
2019-02-01T10:23:58
168,679,410
0
0
null
null
null
null
UTF-8
Java
false
false
478
java
package com.boedq.modules.sys.controller; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.boedq.modules.sys.entity.SysUserEntity; public abstract class AbstractController { protected Logger logger = LoggerFactory.getLogger(getClass()); protected SysUserEntity getUser() { return (SysUserEntity) SecurityUtils.getSubject().getPrincipal(); } protected Long getUserId() { return getUser().getUserId(); } }
48ba52d61a4cb433d2f297c7d3a420d3db491e14
8e27306e811c6d4977406efb92356f86b034672c
/src/test/java/com/junranhuigu/simpleJson/JsonUtilTest.java
fcfb043bb1f2886c9f6c4af1fba82f7977006cbf
[]
no_license
junranhuigu/simpleJson
c9b77b4a91029bfa5ffcb28a2feb35b0328189cd
26413aa834cf38e337c25f9c29254c73a36ec375
refs/heads/master
2020-12-02T16:15:46.374899
2017-07-31T17:30:22
2017-07-31T17:30:22
96,525,935
0
0
null
null
null
null
UTF-8
Java
false
false
8,263
java
package com.junranhuigu.simpleJson; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.junit.BeforeClass; import org.junit.Test; public class JsonUtilTest { private static String json; @BeforeClass public static void begin(){ json = "{\"cardList\":[{\"id\":70045,\"number\":0,\"pieceNumber\":0},{\"id\":70002,\"number\":1,\"pieceNumber\":0},{\"id\":70051,\"number\":0,\"pieceNumber\":0},{\"id\":70058,\"number\":3,\"pieceNumber\":0},{\"id\":70048,\"number\":0,\"pieceNumber\":0},{\"id\":70028,\"number\":0,\"pieceNumber\":0},{\"id\":70010,\"number\":0,\"pieceNumber\":0},{\"id\":70052,\"number\":0,\"pieceNumber\":0},{\"id\":70012,\"number\":0,\"pieceNumber\":0},{\"id\":70053,\"number\":0,\"pieceNumber\":0},{\"id\":70055,\"number\":0,\"pieceNumber\":0},{\"id\":70024,\"number\":1,\"pieceNumber\":0}],\"charmList\":[],\"clothNew\":80001,\"clouthList\":[{\"id\":80001,\"isWear\":1}],\"eightList\":[{\"level\":20,\"stage\":1,\"stageexp\":0,\"type\":1,\"valueList\":[[1,53]],\"valueList2\":[[6,18]]},{\"level\":2,\"stage\":0,\"stageexp\":0,\"type\":2,\"valueList\":[[3,204]],\"valueList2\":[]},{\"level\":20,\"stage\":1,\"stageexp\":0,\"type\":3,\"valueList\":[[2,77]],\"valueList2\":[[8,14]]},{\"level\":2,\"stage\":0,\"stageexp\":0,\"type\":4,\"valueList\":[[4,11]],\"valueList2\":[]},{\"level\":17,\"stage\":1,\"stageexp\":0,\"type\":5,\"valueList\":[[5,168]],\"valueList2\":[[0,0]]},{\"level\":9,\"stage\":0,\"stageexp\":0,\"type\":6,\"valueList\":[[6,42]],\"valueList2\":[]},{\"level\":20,\"stage\":1,\"stageexp\":0,\"type\":7,\"valueList\":[[7,200]],\"valueList2\":[[7,22]]},{\"level\":1,\"stage\":0,\"stageexp\":0,\"type\":8,\"valueList\":[[8,0]],\"valueList2\":[]}],\"id\":\"2210095328662901\",\"itemList\":[{\"itemId\":50040,\"num\":10}],\"piece\":[{\"itemId\":91004,\"num\":2},{\"itemId\":92006,\"num\":8},{\"itemId\":92007,\"num\":4},{\"itemId\":91002,\"num\":5},{\"itemId\":91003,\"num\":3}],\"soulList\":[{\"breakLevel\":2,\"id\":21044,\"mosaicPosition\":0,\"skillPosition\":1,\"strengthLevel\":21,\"uuid\":\"yCJOt\"},{\"breakLevel\":2,\"id\":21035,\"mosaicPosition\":0,\"skillPosition\":6,\"strengthLevel\":21,\"uuid\":\"NDsOk\"},{\"breakLevel\":2,\"id\":21040,\"mosaicPosition\":0,\"skillPosition\":2,\"strengthLevel\":21,\"uuid\":\"3B7rH\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"WNjjG\"},{\"breakLevel\":2,\"id\":21033,\"mosaicPosition\":0,\"skillPosition\":7,\"strengthLevel\":21,\"uuid\":\"KcMbM\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Hrp7l\"},{\"breakLevel\":2,\"id\":21003,\"mosaicPosition\":0,\"skillPosition\":8,\"strengthLevel\":21,\"uuid\":\"QXN5Q\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"4PU3Q\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"VhqW9\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"aff2i\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"8330z\"},{\"breakLevel\":0,\"id\":21039,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Yk7Qc\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"T5IXN\"},{\"breakLevel\":2,\"id\":21014,\"mosaicPosition\":0,\"skillPosition\":3,\"strengthLevel\":21,\"uuid\":\"QQqYr\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"1p8Sp\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Jv7JD\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"ZqKO6\"},{\"breakLevel\":0,\"id\":21040,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"ELie1\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"1Nsk8\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"PTtLO\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"24CtR\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Dwm7z\"},{\"breakLevel\":0,\"id\":21039,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"FCj6Y\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"XHXA5\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"gstGi\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"OIdrC\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Kkfbd\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"Fvddd\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"NKlKX\"},{\"breakLevel\":0,\"id\":21013,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"etuxT\"},{\"breakLevel\":0,\"id\":21001,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"rXtkv\"},{\"breakLevel\":0,\"id\":21012,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"bK0rB\"},{\"breakLevel\":0,\"id\":21013,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"rhRsv\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"1jH5h\"},{\"breakLevel\":0,\"id\":21042,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"ehkBX\"},{\"breakLevel\":1,\"id\":21006,\"mosaicPosition\":0,\"skillPosition\":4,\"strengthLevel\":19,\"uuid\":\"CQDdz\"},{\"breakLevel\":0,\"id\":21038,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"ZrwAn\"},{\"breakLevel\":0,\"id\":21029,\"mosaicPosition\":0,\"skillPosition\":0,\"strengthLevel\":0,\"uuid\":\"YX5HZ\"}],\"weaponList\":[{\"exp\":0,\"isOk\":-1,\"isWear\":0,\"level\":8,\"skillId\":10358,\"valueList\":[[1,210],[4,20],[5,26],[6,19]],\"weaponId\":10001},{\"exp\":0,\"isOk\":-1,\"isWear\":1,\"level\":8,\"skillId\":10359,\"valueList\":[[1,373],[4,34],[5,44],[6,33]],\"weaponId\":10002}],\"weaponNew\":10002,\"wearCharmList\":[]}"; } @Test public void testJsonStructure() { try { String structureInfo = JsonUtil.jsonStructure(this.json); System.out.println(structureInfo); assertNotNull(structureInfo); } catch (Exception e) { e.printStackTrace(); } } @Test public void testSelectStringString() { List<Integer> values = JsonUtil.select("root.soulList.id", json, Integer.class); System.out.println(values); assertNotNull(values); } @Test public void testSelectListOfStringString() { List<String> commands = new ArrayList<>(); commands.add("root.soulList.id > 21020"); commands.add("root.soulList[0]"); commands.add("root.soulList[0].id"); commands.add("root.soulList where .id < 21010 && .skillPosition > 0"); Map<String, List<Object>> values = JsonUtil.select(commands, json); Iterator<Entry<String, List<Object>>> ite = values.entrySet().iterator(); while(ite.hasNext()){ Entry<String, List<Object>> entry = ite.next(); System.out.println(entry.getKey() + " " + entry.getValue()); assertNotNull(entry.getValue()); } } @Test public void testIsAttr() { try { assertTrue(JsonUtil.isAttr("root.soulList.id > 21020", json)); assertFalse(JsonUtil.isAttr("root.soulList", json)); assertFalse(JsonUtil.isAttr("root.soulList[0]", json)); assertTrue(JsonUtil.isAttr("root.soulList[0].id", json)); assertTrue(JsonUtil.isAttr("root.charmList", json)); } catch (Exception e) { e.printStackTrace(); } } }
44d0511457ba26c3040b1491751ce06ebcb14494
9d6089379238e00c0a5fb2949c1a6e7c19b50958
/bin/ext-accelerator/b2bacceleratorfacades/src/de/hybris/platform/b2bacceleratorfacades/order/populators/B2BBudgetReversePopulator.java
75a31f8be4e1432c010bf1ff013332a5321ac4d6
[]
no_license
ChintalaVenkat/learning_hybris
55ce582b4796a843511d0ea83f4859afea52bd88
6d29f59578512f9fa44a3954dc67d0f0a5216f9b
refs/heads/master
2021-06-18T17:47:12.173132
2021-03-26T11:00:09
2021-03-26T11:00:09
193,689,090
0
0
null
2019-06-25T10:46:40
2019-06-25T10:46:39
null
UTF-8
Java
false
false
2,497
java
/* * [y] hybris Platform * * Copyright (c) 2000-2013 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package de.hybris.platform.b2bacceleratorfacades.order.populators; import de.hybris.platform.b2b.model.B2BBudgetModel; import de.hybris.platform.b2b.model.B2BCustomerModel; import de.hybris.platform.b2b.model.B2BUnitModel; import de.hybris.platform.b2b.services.B2BUnitService; import de.hybris.platform.b2bacceleratorfacades.order.data.B2BBudgetData; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.c2l.CurrencyModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.servicelayer.i18n.CommonI18NService; import de.hybris.platform.util.StandardDateRange; import org.springframework.beans.factory.annotation.Required; /** * Populates {@link B2BBudgetData} with {@link B2BBudgetModel}. */ public class B2BBudgetReversePopulator implements Populator<B2BBudgetData, B2BBudgetModel> { private B2BUnitService<B2BUnitModel, B2BCustomerModel> b2BUnitService; private CommonI18NService commonI18NService; @Override public void populate(final B2BBudgetData source, final B2BBudgetModel target) throws ConversionException { target.setCode(source.getCode()); target.setName(source.getName()); target.setBudget(source.getBudget()); final B2BUnitModel b2BUnitModel = getB2BUnitService().getUnitForUid(source.getUnit().getUid()); if (b2BUnitModel != null) { target.setUnit(b2BUnitModel); } final CurrencyModel currencyModel = getCommonI18NService().getCurrency(source.getCurrency().getIsocode()); target.setCurrency(currencyModel); target.setDateRange(new StandardDateRange(source.getStartDate(), source.getEndDate())); } public B2BUnitService<B2BUnitModel, B2BCustomerModel> getB2BUnitService() { return b2BUnitService; } @Required public void setB2BUnitService(final B2BUnitService<B2BUnitModel, B2BCustomerModel> b2bUnitService) { b2BUnitService = b2bUnitService; } public CommonI18NService getCommonI18NService() { return commonI18NService; } @Required public void setCommonI18NService(final CommonI18NService commonI18NService) { this.commonI18NService = commonI18NService; } }
dfc7f2c71bf0324d80d0bcaee3fa1280b8e1a06d
7fafc4955bd02f787fea93f7596467fd8153327c
/app/src/main/java/se/newton/chatapp/service/ThemeChanger.java
9d795047ffa3d2e7a03b6a17ed0813ac771d1b18
[]
no_license
theslof/ChatApp
1d3edf9e0d0c621a5e0ba381990fe5e22147a836
3066b1a4068bf4d8e555c96c1c8228b6855a1925
refs/heads/developer
2023-01-10T20:24:34.742817
2019-02-20T10:03:32
2019-02-21T16:12:39
121,249,919
3
5
null
2023-01-09T11:23:58
2018-02-12T13:28:42
Java
UTF-8
Java
false
false
1,233
java
package se.newton.chatapp.service; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AppCompatDelegate; import se.newton.chatapp.R; /** * Created by Martin on 2018-03-07. */ public class ThemeChanger { public static void changeTheme(SharedPreferences sharedPreferences, Context context) { //sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String appTheme = sharedPreferences.getString("themeChanger", "App theme"); if (appTheme.equals("App theme")) { context.setTheme(R.style.AppTheme_NoActionBar); } else if (appTheme.equals("Dragomir")) { context.setTheme(R.style.Dragomir); } else if (appTheme.equals("Elias 1")) { context.setTheme(R.style.Elias1); } else if (appTheme.equals("Elias 2")) { context.setTheme(R.style.Elias2); } else if (appTheme.equals("Jonas")) { context.setTheme(R.style.Jonas); } else if (appTheme.equals("Day and Night")) { context.setTheme(R.style.DayNight); AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_AUTO); } } }
ae0b92c4860b0e697451654ac1ad13001d730eef
c0db989d00c8af73371412af954d3130b082cde3
/test/quize/number01/DaewonRankingServiceTest.java
07dd1e5498f11099059b27eaa702cc989f69fd2a
[]
no_license
spring-sprout/telepathy
b48986203d010c487ff7462bf708413a95725fa3
d7bb5c523acf4806c44dc7d6fd272712b50010e2
refs/heads/master
2021-01-02T08:45:40.652627
2018-04-18T21:36:31
2018-04-18T21:36:31
3,435,402
5
23
null
2020-10-13T10:13:47
2012-02-13T23:48:52
Java
UTF-8
Java
false
false
607
java
package quize.number01; import org.junit.Assert; import org.junit.Test; public class DaewonRankingServiceTest { DaewonRankingService rankingService = new DaewonRankingService(); @Test public void testGetRanking() { int[] scores = new int[] { 80, 80, 60, 100 }; int[] ranking = rankingService.rank(scores); Assert.assertEquals(2, ranking[0]); Assert.assertEquals(2, ranking[1]); Assert.assertEquals(4, ranking[2]); Assert.assertEquals(1, ranking[3]); } @Test public void testPringRanking() { int[] scores = new int[] { 80, 80, 60, 100 }; rankingService.printRanking(scores); } }
ef0c7a87918c28e01ca596bd01fb5a04bbde053b
ebec64c07d7e186f80300a2d458d6689afea697e
/src/test/br/ufsc/testes/gerenciador/Funcionario.java
84810f539b1aebd9fc4032d01f730e14c431742e
[]
no_license
LeonardoEichs/gerenciadorOcorrencias
61574c8fb86e5091f2a6eabb18d4f6e1d5ac2840
ac327d277eb6ab00f2a018bc6a0042d078318277
refs/heads/master
2021-07-17T22:44:05.389603
2017-10-26T13:00:21
2017-10-26T13:00:21
108,411,831
1
0
null
null
null
null
UTF-8
Java
false
false
417
java
package test.br.ufsc.testes.gerenciador; import java.util.LinkedList; public class Funcionario { private String nome; private LinkedList<Integer> ocorrencias; public Funcionario(String nome) { this.nome = nome; ocorrencias = new LinkedList<Integer>(); } public void adicionarOcorrencia(Integer key) { ocorrencias.add(key); } public int obterNumeroOcorrencias() { return ocorrencias.size(); } }
f953d161aeda5f1ae178e895add9a86b1a2c2c41
e1e5bd6b116e71a60040ec1e1642289217d527b0
/H5/L2jReunion/L2jReunion_2014_07_14/L2J_ReunionProject_Core/java/l2r/gameserver/model/conditions/ConditionTargetNpcRace.java
c2191c59236a1830d85e5424df9f8dae3b0f10e4
[]
no_license
serk123/L2jOpenSource
6d6e1988a421763a9467bba0e4ac1fe3796b34b3
603e784e5f58f7fd07b01f6282218e8492f7090b
refs/heads/master
2023-03-18T01:51:23.867273
2020-04-23T10:44:41
2020-04-23T10:44:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,498
java
/* * Copyright (C) 2004-2014 L2J Server * * This file is part of L2J Server. * * L2J Server 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. * * L2J Server 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 l2r.gameserver.model.conditions; import java.util.Set; import l2r.gameserver.enums.NpcRace; import l2r.gameserver.model.actor.L2Npc; import l2r.gameserver.model.stats.Env; /** * Condition that checks target NPC race. * @author Nos */ public class ConditionTargetNpcRace extends Condition { private final Set<NpcRace> _races; /** * Instantiates a new condition target NPC race * @param races the races */ public ConditionTargetNpcRace(Set<NpcRace> races) { _races = races; } @Override public boolean testImpl(Env env) { final L2Npc npc = env.getTarget() instanceof L2Npc ? (L2Npc) env.getTarget() : null; return (npc != null) && _races.contains(npc.getTemplate().getRace()); } }
4cb183e781d3317aff29a30ea1cdcc8b067dc745
6900a915cc2e5de114a43fecbef2b64a1d41ea30
/BunnyMarket/src/main/java/com/kh/bunny/common/MailHandler.java
ffabb308c9f71b59bec3a7248934c57945221bad
[]
no_license
BunnyMarket/BunnyMarketSpring
19068ecfb8215cbe722361d90dd7a33f7d8d8da3
66585f548c8c2e55194b517ec61f45998e76144e
refs/heads/develop
2022-12-07T19:43:05.329269
2020-08-09T15:42:38
2020-08-09T15:42:38
281,345,211
0
0
null
2020-08-09T01:30:22
2020-07-21T08:50:00
CSS
UTF-8
Java
false
false
1,792
java
package com.kh.bunny.common; import java.io.UnsupportedEncodingException; import javax.activation.DataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; public class MailHandler { private JavaMailSender mailSender; private MimeMessage message; private MimeMessageHelper messageHelper; public MailHandler(JavaMailSender mailSender) throws MessagingException { this.mailSender = mailSender; message = this.mailSender.createMimeMessage(); messageHelper = new MimeMessageHelper(message, true, "UTF-8"); } public void setSubject(String subject) throws MessagingException { messageHelper.setSubject(subject); // 이메일 타이틀 } public void setText(String htmlContent) throws MessagingException { messageHelper.setText(htmlContent, true); // 이메일 TEXT 부분 } public void setFrom(String email, String name) throws UnsupportedEncodingException, MessagingException { messageHelper.setFrom(email, name); // 보내는 사람 이메일 } public void setTo(String email) throws MessagingException { messageHelper.setTo(email); //받는 사람 이메일 } public void addInline(String contentId, DataSource dataSource) throws MessagingException { messageHelper.addInline(contentId, dataSource); } public void send() { try { mailSender.send(message); }catch (Exception e) { e.printStackTrace(); } } }
3941855277768efad1047bbd31037b4c7988f38e
8e17056410ca4d362e126b2e9b4c2c6a61b29b28
/Tonight/src/com/hangzhou/tonight/uikit/MMAlert.java
5ba4a67b99c8b9be88e7728ba119548cfec0f1d8
[]
no_license
biglongteam/buyecheng2
2f21eb1f4ddc9fc171f5fc09e0474887e652b1fd
b02038d2de783ad4cf8531af7f4f0e99ac10c9db
refs/heads/master
2021-01-10T14:15:03.122456
2015-10-30T01:20:08
2015-10-30T01:20:08
43,888,296
2
2
null
2015-10-30T01:20:09
2015-10-08T12:56:51
Java
UTF-8
Java
false
false
14,119
java
package com.hangzhou.tonight.uikit; import java.util.ArrayList; import java.util.List; import com.hangzhou.tonight.R; import com.hangzhou.tonight.Util; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public final class MMAlert { public interface OnAlertSelectId { void onClick(int whichButton); } private MMAlert() { } public static AlertDialog showAlert(final Context context, final String msg, final String title) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton(R.string.app_ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final int msgId, final int titleId) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(titleId); builder.setMessage(msgId); builder.setPositiveButton(R.string.app_ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final int msgId, final int titleId, final DialogInterface.OnClickListener l) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(titleId); builder.setMessage(msgId); builder.setPositiveButton(R.string.app_ok, l); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String msg, final String title, final DialogInterface.OnClickListener l) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton(R.string.app_ok, l); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final int msgId, final int titleId, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(titleId); builder.setMessage(msgId); builder.setPositiveButton(R.string.app_ok, lOk); builder.setNegativeButton(R.string.app_cancel, lCancel); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final int msg, final int title, final int yes, final int no, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton(yes, lOk); builder.setNegativeButton(no, lCancel); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String msg, final String title, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton(R.string.app_ok, lOk); builder.setNegativeButton(R.string.app_cancel, lCancel); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String msg, final String title, final String yes, final String no, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.ic_dialog_alert); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton(yes, lOk); builder.setNegativeButton(no, lCancel); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String title, final View view, final DialogInterface.OnClickListener lOk) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setView(view); builder.setPositiveButton(R.string.app_ok, lOk); // builder.setCancelable(true); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String title, final View view, final String ok, final String cancel, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setView(view); builder.setPositiveButton(ok, lOk); builder.setNegativeButton(cancel, lCancel); // builder.setCancelable(false); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String title, final String ok, final View view, final DialogInterface.OnClickListener lOk) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setView(view); builder.setPositiveButton(ok, lOk); // builder.setCancelable(true); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String title, final String msg, final View view, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(msg); builder.setView(view); builder.setPositiveButton(R.string.app_ok, lOk); builder.setNegativeButton(R.string.app_cancel, lCancel); // builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (lCancel != null) { lCancel.onClick(dialog, 0); } } }); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static AlertDialog showAlert(final Context context, final String title, final View view, final DialogInterface.OnCancelListener lCancel) { if (context instanceof Activity && ((Activity) context).isFinishing()) { return null; } final Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setView(view); // builder.setCancelable(true); builder.setOnCancelListener(lCancel); final AlertDialog alert = builder.create(); alert.show(); return alert; } public static ProgressDialog showProgressDlg(final Context context, final String title, final String message, final boolean indeterminate, final boolean cancelable, final OnCancelListener lCancel) { return ProgressDialog.show(context, title, message, indeterminate, cancelable, new DialogInterface.OnCancelListener() { @Override public void onCancel(final DialogInterface dialog) { if (lCancel != null) { lCancel.onCancel(dialog); } } }); } public static AlertDialog showWebAlert(final Context context, final String title, final String rawUrl, final WebViewClient client, final DialogInterface.OnClickListener lOk, final DialogInterface.OnDismissListener lDismiss) { final View view = View.inflate(context, R.layout.webalert, null); final AlertDialog alert = showAlert(context, title, view, lOk); alert.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (lDismiss != null) { lDismiss.onDismiss(dialog); } } }); final WebView info = (WebView) view.findViewById(R.id.info_wv); info.loadUrl(rawUrl); if (client != null) { info.setWebViewClient(client); } return alert; } public static AlertDialog showWebAlert(final Context context, final String title, final String rawUrl, final WebViewClient client, final String ok, final String cancel, final DialogInterface.OnClickListener lOk, final DialogInterface.OnClickListener lCancel, final DialogInterface.OnDismissListener lDismiss) { final View view = View.inflate(context, R.layout.webalert, null); final AlertDialog alert = showAlert(context, title, view, ok, cancel, lOk, lCancel); alert.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (lDismiss != null) { lDismiss.onDismiss(dialog); } } }); final WebView info = (WebView) view.findViewById(R.id.info_wv); info.loadUrl(rawUrl); if (client != null) { info.setWebViewClient(client); } return alert; } } class AlertAdapter extends BaseAdapter { // private static final String TAG = "AlertAdapter"; public static final int TYPE_BUTTON = 0; public static final int TYPE_TITLE = 1; public static final int TYPE_EXIT = 2; public static final int TYPE_CANCEL = 3; private List<String> items; private int[] types; // private boolean isSpecial = false; private boolean isTitle = false; // private boolean isExit = false; private Context context; public AlertAdapter(Context context, String title, String[] items, String exit, String cancel) { if (items == null || items.length == 0) { this.items = new ArrayList<String>(); } else { this.items = Util.stringsToList(items); } this.types = new int[this.items.size() + 3]; this.context = context; if (title != null && !title.equals("")) { types[0] = TYPE_TITLE; this.isTitle = true; this.items.add(0, title); } if (exit != null && !exit.equals("")) { // this.isExit = true; types[this.items.size()] = TYPE_EXIT; this.items.add(exit); } if (cancel != null && !cancel.equals("")) { // this.isSpecial = true; types[this.items.size()] = TYPE_CANCEL; this.items.add(cancel); } } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return 0; } @Override public boolean isEnabled(int position) { if (position == 0 && isTitle) { return false; } else { return super.isEnabled(position); } } @Override public View getView(int position, View convertView, ViewGroup parent) { final String textString = (String) getItem(position); ViewHolder holder; int type = types[position]; if (convertView == null || ((ViewHolder) convertView.getTag()).type != type) { holder = new ViewHolder(); if (type == TYPE_CANCEL) { convertView = View.inflate(context, R.layout.alert_dialog_menu_list_layout_cancel, null); } else if (type == TYPE_BUTTON) { convertView = View.inflate(context, R.layout.alert_dialog_menu_list_layout, null); } else if (type == TYPE_TITLE) { convertView = View.inflate(context, R.layout.alert_dialog_menu_list_layout_title, null); } else if (type == TYPE_EXIT) { convertView = View.inflate(context, R.layout.alert_dialog_menu_list_layout_special, null); } // holder.view = (LinearLayout) convertView.findViewById(R.id.popup_layout); holder.text = (TextView) convertView.findViewById(R.id.popup_text); holder.type = type; convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(textString); return convertView; } static class ViewHolder { // LinearLayout view; TextView text; int type; } }
4a9502750269ff3449f7d65b7154a4a2e709b51b
e298f56ddc47a3010d7b0862e857397e0817c172
/app/src/main/java/com/cc/carmanager/activity/CarSeriesPicActivity.java
873599f33e7ac28127c42cec1f659b2b8f460559
[]
no_license
Brucechen13/carmanager
f2a25e9ee62ab6998be4fd7bb7d207c7b37863e6
a8853098d3b12a52e8de49f26700019146942e56
refs/heads/master
2021-09-11T16:52:17.272917
2018-04-10T00:42:45
2018-04-10T00:42:45
112,202,735
0
0
null
null
null
null
UTF-8
Java
false
false
3,813
java
package com.cc.carmanager.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import com.cc.carmanager.R; import com.cc.carmanager.activity.base.BarBaseActivity; import com.cc.carmanager.bean.CarPicBean; import com.cc.carmanager.bean.CarPicSeriesBean; import com.cc.carmanager.net.VolleyInstance; import com.cc.carmanager.net.VolleyResult; import com.cc.carmanager.util.NetUrlsSet; import com.cc.carmanager.util.ToastUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.lzy.ninegrid.ImageInfo; import com.lzy.ninegrid.NineGridView; import com.lzy.ninegrid.preview.NineGridViewClickAdapter; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Created by chenc on 2018/3/22. */ public class CarSeriesPicActivity extends BarBaseActivity { private NineGridView[] nineGrids = new NineGridView[4]; List<List<ImageInfo>> imageInfos = new ArrayList<>(); private int size = 4; private int carId, seriesId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_car_seriespic); nineGrids[0] = (NineGridView) findViewById(R.id.nineGrid0); nineGrids[1] = (NineGridView) findViewById(R.id.nineGrid1); nineGrids[2] = (NineGridView) findViewById(R.id.nineGrid2); nineGrids[3] = (NineGridView) findViewById(R.id.nineGrid3); initData(); setHeader("车型配置"); } private void initData() { String url_news = String.format(Locale.CHINA, NetUrlsSet.URL_SERIES_PIC, 9, 30); VolleyInstance.getVolleyInstance().startRequest(url_news, new VolleyResult() { @Override public void success(String resultStr) { Gson gson = new Gson(); CarPicSeriesBean mRecommendBean = gson.fromJson(resultStr, CarPicSeriesBean.class); if (mRecommendBean.isSuccess()) { for (int i = 0; i < size; i++) { imageInfos.add(new ArrayList<ImageInfo>()); Gson gson2 = new Gson(); java.lang.reflect.Type type = new TypeToken<ArrayList<String>>() { }.getType(); String json_str = mRecommendBean.getPicJson().getTypeVal(i); List<String> jsonMap = gson2.fromJson(json_str, type); if (jsonMap != null) { for (String pic : jsonMap) { pic = "http://img.pcauto.com.cn/images/pcautogallery/modle/article/201710/29/15092917392405740_660.webp"; ImageInfo info = new ImageInfo(); info.setThumbnailUrl(pic); info.setBigImageUrl(pic); imageInfos.get(i).add(info); } } } initGridView(); } else { ToastUtils.makeShortText("未查询到车型图片", CarSeriesPicActivity.this); } } @Override public void failure() { Log.d("car", "推荐界面下的推荐网络数据解析失败"); } }); } private void initGridView() { for (int i = 0; i < size; i++) { nineGrids[i].setAdapter(new NineGridViewClickAdapter(this, imageInfos.get(i))); if (imageInfos.get(i) != null && imageInfos.get(i).size() == 1) { nineGrids[i].setSingleImageRatio(1); } } } @Override public void onClick(View view) { super.onClick(view); } }
98ef8e51aada90036884309860b0814bb5243bfa
99ee919a31db0560556bcc27bd8afaa3169b8482
/Server/mapas/src/main/java/gob/siap/mapas/models/Estado.java
904906e6f38ffc74297961bb51352ff07d76b691
[]
no_license
jmanuelc87/mapas-dinamicos
25aa389f8e424177f567e164062a50bac7e86ee9
8d933e988aff8e3a57f1a7e58d68b9e0a837a110
refs/heads/master
2021-04-06T20:20:25.698743
2018-09-08T04:50:10
2018-09-08T04:50:10
125,442,606
1
0
null
null
null
null
UTF-8
Java
false
false
643
java
package gob.siap.mapas.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * * @author ssocial.dsg */ @Entity(name = "") @Table(name = "cat_estado") public class Estado { @Id @Column(name = "idestado") private Long id; @Column(name = "nomestado") private String nombre; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
7807bf815d04777a685c2972d484d30859fa4aea
7352f959d0ebb37cd75cc1da87b95d2aad7e327e
/java/parser/src/main/java/gov/lbl/parser/domain/Element.java
5b37d2806f85297af264da462e9d411269d61b20
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lbl-srg/modelica-json
fbac58a486c4389b1d4738aa74b2f900e60b8ccb
2f006e0f7900e267307feb39228758c42237a6ef
refs/heads/master
2023-08-31T05:18:21.015536
2023-07-27T18:21:13
2023-07-27T18:21:13
121,715,552
21
18
NOASSERTION
2023-08-30T23:17:06
2018-02-16T04:42:39
JavaScript
UTF-8
Java
false
false
1,217
java
package gov.lbl.parser.domain; public class Element { private Import_clause import_clause; private Extends_clause extends_clause; private Boolean redeclare; private Boolean is_final; private Boolean inner; private Boolean outer; private Boolean replaceable; private Constraining_clause constraining_clause; private Class_definition class_definition; private Component_clause component_clause; private Comment comment; public Element(Import_clause import_clause, Extends_clause extends_clause, Boolean redeclare, Boolean is_final, Boolean inner, Boolean outer, Boolean replaceable, Constraining_clause constraining_clause, Class_definition class_definition, Component_clause component_clause, Comment comment) { this.import_clause = import_clause; this.extends_clause = extends_clause; this.redeclare = redeclare; this.is_final = is_final; this.inner = inner; this.outer = outer; this.replaceable = replaceable; this.constraining_clause = constraining_clause; this.class_definition = class_definition; this.component_clause = component_clause; this.comment = comment; } }
ee3d317754ab9de53e34efc78334df53f7e5e5b6
18138ce7c57912d29952c01a2850212dd3398b11
/RobotGUI/appClientModule/com/joshu/dnsdynamic/ClientGUI/MainPanel.java
f76e4b4386507ff07d57e2ebc790aa0df02a4ed0
[]
no_license
joshu0991/Robot
08e40a161879de066aa0cdff4926b5786edb58c4
249abbfce8fa7e903776e56efaca48d69eee9a67
refs/heads/master
2016-09-10T12:36:16.278158
2014-08-23T21:44:31
2014-08-23T21:44:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,845
java
package com.joshu.dnsdynamic.ClientGUI; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import com.joshu.dnsdynamic.ClientGUI.Logic.ClientLogics; public class MainPanel extends JPanel implements ActionListener{ private static final long serialVersionUID = 1L; private JButton forward; private JButton back; private JButton left; private JButton right; private JButton breaks; //////////////////////////////////////////////////////////////////////////// private JRadioButton high; private JRadioButton med; private JRadioButton low; private JRadioButton stop; //////////////////////////////////////////////////////////////////////////// private JPanel westPan; private JPanel eastPan; private JPanel centerPan; private JPanel northPan; private JPanel southPan; //////////////////////////////////////////////////////////////////////////// private ButtonGroup group; private JPanel radioPanel; private JLabel speed; private ImageIcon upIm; private ImageIcon downIm; private ImageIcon leftIm; private ImageIcon rightIm; private JLabel tempLab; private JLabel date; private JLabel dis; private JTextField tempField; private JTextField dateField; private JTextField distance; //////////////////////////////////////////////////////////////////////////// private String [] addr; private ClientLogics temp; private Thread dataThread; public MainPanel() { setLayout(new BorderLayout()); createComponents(); addComponentsWest(); addComponentsSouth(); add(southPan, BorderLayout.SOUTH); add(westPan, BorderLayout.WEST); } //////////////////////////////////////////////////////////////////////////// private void createComponents(){ //Button images upIm = loadImages("Img/up.jpg");//loadImages("Img/up.jpg"); downIm = loadImages("Img/down.jpg"); rightIm = loadImages("Img/right.jpg"); leftIm = loadImages("Img/left.jpg"); //directional buttons forward = new JButton("Forward", upIm); forward.setEnabled(false); forward.setIcon(upIm); forward.setMnemonic(KeyEvent.VK_W); forward.addActionListener(this); back = new JButton("Back", downIm); back.setEnabled(false); back.addActionListener(this); back.setMnemonic(KeyEvent.VK_S); left = new JButton("Left", leftIm); left.setEnabled(false); left.addActionListener(this); left.setMnemonic(KeyEvent.VK_A); right = new JButton("Right", rightIm); right.setEnabled(false); right.addActionListener(this); right.setMnemonic(KeyEvent.VK_D); breaks = new JButton("Break"); breaks.setEnabled(false); breaks.setMnemonic(KeyEvent.VK_E); breaks.addActionListener(this); //radio speed buttons speed = new JLabel("Speed"); high = new JRadioButton("High"); high.setEnabled(false); high.addActionListener(this); med = new JRadioButton("Med"); med.setEnabled(false); med.addActionListener(this); low = new JRadioButton("Low"); low.setEnabled(false); low.addActionListener(this); stop = new JRadioButton("Stop"); stop.setEnabled(false); stop.addActionListener(this); group = new ButtonGroup();//group the radio buttons group.add(high); group.add(med); group.add(low); group.add(stop); radioPanel = new JPanel(new GridLayout(0, 1));//create a panel for radio buttons radioPanel.add(speed); radioPanel.add(high); radioPanel.add(med); radioPanel.add(low); radioPanel.add(stop); //Text fields tempLab = new JLabel("Temperature:"); date = new JLabel("Date Updated:"); dis = new JLabel("Distance"); tempField = new JTextField(); tempField.setSize(100, 30); dateField = new JTextField(); distance = new JTextField(); //fit buttons and on the west section westPan = new JPanel(); eastPan = new JPanel(); northPan = new JPanel(); southPan = new JPanel(); centerPan = new JPanel(); westPan.setLayout(new GridLayout(6, 1)); //southPan.setLayout(new GridLayout(2, 6)); } //////////////////////////////////////////////////////////////////////////// public void buildAddr(String url){ addr = new String[2]; int colenLoc = url.indexOf(':'); String port = url.substring(colenLoc + 1); String ipAddr = url.substring(0, colenLoc); addr[0] = ipAddr ; addr[1] = port; } public void connect(){ String url = JOptionPane.showInputDialog(this, "Enter the the location", "example.location.com:9454"); buildAddr(url); forward.setEnabled(true); back.setEnabled(true); left.setEnabled(true); right.setEnabled(true); breaks.setEnabled(true); high.setEnabled(true); med.setEnabled(true); low.setEnabled(true); stop.setEnabled(true); temp = new ClientLogics(addr[0], addr[1], "Temp"); dataThread = new Thread(temp); dataThread.start(); } //add components to the westPanel private void addComponentsWest(){ westPan.add(forward); westPan.add(back); westPan.add(right); westPan.add(left); westPan.add(breaks); westPan.add(radioPanel); } /////////////////////////////////////////////////////////////////////////// protected void addComponentsSouth(){ Path path = Paths.get("DataFile.txt"); String data = readFile(path); if(data.length() > 0){ tempField.setSize(100, 30); tempField.setText(data);//index where temps will be dateField.setText(data);//where date will be dateField.setSize(100, 30); } southPan.add(tempLab); southPan.add(tempField); southPan.add(date); southPan.add(dateField); southPan.add(dis); southPan.add(distance); } //////////////////////////////////////////////////////////////////////////// protected String readFile(Path path){ Charset charset = Charset.forName("US-ASCII"); String al = ""; try (BufferedReader reader = Files.newBufferedReader(path, charset)) { String s = null; while ((s = reader.readLine()) != null) { al = s; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return al; } //////////////////////////////////////////////////////////////////////////// //this doesn't work yet private ImageIcon loadImages(String path) { java.net.URL imgURL = MainPanel.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); }else{ System.err.println("Cannot open " + path); return null; } } public void close(){ temp.makeRequest("Close"); } ////////////////////////////////////////////////////////////////////////////// @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand() != null){ addComponentsSouth(); if(e.getActionCommand().equals("Forward")){ //request move forward temp.makeRequest("forward"); System.out.println(e.getActionCommand()); }else if(e.getActionCommand().equals("Back")){ //request move back temp.makeRequest("back"); System.out.println(e.getActionCommand()); }else if(e.getActionCommand().equals("Left")){ //request move left temp.makeRequest("left"); System.out.println(e.getActionCommand()); }else if(e.getActionCommand().equals("Right")){ //request move forward temp.makeRequest("right"); System.out.println(e.getActionCommand()); } //always update temp and distance temp.makeRequest("Temp"); temp.makeRequest("distance"); } } } //to do //make texts fields size appropriatly
a630a4f3b19a9b366b54eed212a0ee9ee6970c89
03b6f2228d92bccfbf45520acb03075100f0d7ac
/src/main/java/br/com/alelo/consumer/consumerpat/domain/service/Impl/CardCalculatorFactory.java
a0dc2b14f89e86271976a874bfe13420d64d5554
[]
no_license
lucasmiranda2711/consumer-pat
142f0539ce6785a6057cea9413efc7f419d910ac
22dc9249cbb2d513cf14aada7302b3a611831cbf
refs/heads/main
2023-06-03T14:49:30.259658
2021-06-24T20:03:26
2021-06-24T20:03:26
379,046,594
0
0
null
2021-06-21T19:51:17
2021-06-21T19:51:17
null
UTF-8
Java
false
false
707
java
package br.com.alelo.consumer.consumerpat.domain.service.Impl; import br.com.alelo.consumer.consumerpat.domain.service.CardCalculatorStrategy; import br.com.alelo.consumer.consumerpat.enums.EstablishmentType; public class CardCalculatorFactory { public static CardCalculatorStrategy getCardCalculator(EstablishmentType establishmentType){ switch (establishmentType){ case Drugstore: return new CardDrugstoreCalculator(); case Food: return new CardFoodCalculator(); case Fuel: return new CardFuelCalculator(); default: throw new UnsupportedOperationException(); } } }
bca328610a51165355f5c0e108e7af4c60127c07
ec7942c929e1fcd16ae302a0b5e0e59378364afa
/core-base/core-base/src/main/java/org/nanotek/entities/BaseReleaseLabelCatalogEntity.java
06cdf77918bdd74f511355a01391697c6d4b023c
[ "Apache-2.0" ]
permissive
JoseCanova/repository-spring-core
16e2df2f50efb4d8a9268aa42031d9fae6b15ad1
10dd4a39b674180e522f4dd53155e1b2f456298c
refs/heads/master
2022-12-20T23:48:24.257644
2022-05-22T17:10:04
2022-05-22T17:10:04
249,253,054
2
1
Apache-2.0
2022-06-22T18:37:11
2020-03-22T19:04:30
Java
UTF-8
Java
false
false
146
java
package org.nanotek.entities; import org.nanotek.MutatorSupport; public interface BaseReleaseLabelCatalogEntity<K> extends MutatorSupport<K>{ }
25a29d066a72d58e374fd7187a101529167b301d
af41861d0aaa9d815df97c53ed78d55ed0e1a9ba
/SpringJDBC_Integration/src/com/service/impl/BookServiceImpl.java
d97db89bdc347ec056266e6a4e149b28f6c8f525
[]
no_license
33priya/Spring-MVC-BOOT-REST
0613002c068dc7f265f9d44c8db8f8d853127c41
5aad3acf80fdfd7ebcd1fd3028ef6dd39ae369ee
refs/heads/master
2020-05-17T07:53:51.363807
2019-05-06T18:32:51
2019-05-06T18:32:51
183,590,547
0
0
null
null
null
null
UTF-8
Java
false
false
1,050
java
package com.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.beans.Book; import com.dao.BookDAO; import com.service.BookService; @Service(value = "bookServiceImpl") public class BookServiceImpl implements BookService { @Autowired @Qualifier(value = "bookDAO_JdbcTempateImpl") private BookDAO bookDAO; @Override @Transactional(readOnly = true) public int addBook(Book book) { return bookDAO.addBook(book); } @Override @Transactional(readOnly = true) public int updateBook(long ISBN, double price) { return bookDAO.updateBook(ISBN, price); } @Override public boolean deleteBook(long ISBN) { return bookDAO.deleteBook(ISBN); } @Override public Book getBook(long ISBN) { return bookDAO.getBook(ISBN); } @Override public List<Book> getBooks() { return bookDAO.getBooks(); } }
e0aeca212f481ca994f194205cb7c842649269fb
89853df9ca1bfff1b32132195b31e085a1d833a0
/Proy_FormRightNow/src/com/rightnow/ws/nullfields/ProductNotificationNullFields.java
1c4b3601fac635757418480db5b43c41d3132790
[]
no_license
WSebastian/Proy_RightNow_Soap
88ca135b26e4812cb750adbbbc45baf37d6dc9b5
9bd68a4cfd622efd5e37ee5f2e3f64749f1c54db
refs/heads/master
2021-03-12T23:29:46.950775
2015-10-28T20:46:18
2015-10-28T20:46:18
42,743,575
0
1
null
null
null
null
UTF-8
Java
false
false
19,106
java
/** * ProductNotificationNullFields.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.rightnow.ws.nullfields; /** * ProductNotificationNullFields bean class */ public class ProductNotificationNullFields implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = ProductNotificationNullFields Namespace URI = urn:nullfields.ws.rightnow.com/v1_2 Namespace Prefix = ns3 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("urn:nullfields.ws.rightnow.com/v1_2")){ return "ns3"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for Interface * This was an Attribute! */ protected boolean localInterface = org.apache.axis2.databinding.utils.ConverterUtil.convertToBoolean("false"); /** * Auto generated getter method * @return boolean */ public boolean getInterface(){ return localInterface; } /** * Auto generated setter method * @param param Interface */ public void setInterface(boolean param){ this.localInterface=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { ProductNotificationNullFields.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"urn:nullfields.ws.rightnow.com/v1_2"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":ProductNotificationNullFields", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "ProductNotificationNullFields", xmlWriter); } } if (true) { writeAttribute("", "Interface", org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localInterface), xmlWriter); } xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); attribList.add( new javax.xml.namespace.QName("","Interface")); attribList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localInterface)); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static ProductNotificationNullFields parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ ProductNotificationNullFields object = new ProductNotificationNullFields(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"ProductNotificationNullFields".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (ProductNotificationNullFields)com.rightnow.ws.generic.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); // handle attribute "Interface" java.lang.String tempAttribInterface = reader.getAttributeValue(null,"Interface"); if (tempAttribInterface!=null){ java.lang.String content = tempAttribInterface; object.setInterface( org.apache.axis2.databinding.utils.ConverterUtil.convertToBoolean(tempAttribInterface)); } else { } handledAttributes.add("Interface"); reader.next(); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
ac87b1e414d810f0da2a7380b66b8b8cc9c5ab5f
bcbb1edc357eece2164b15976458b7cc8e2dd577
/tindev-api/src/main/java/fr/squirtles/tindev/domain/Authority.java
28b48a87db01c8efcbe119c84cbb3c671079e4dd
[]
no_license
landschootl/tindev
35f0e585c1360db98f66a9bec5b49790b888d96c
fd94d086ba37a187d7d8e02cdf39fa3204b216e3
refs/heads/master
2022-07-21T17:08:36.156512
2017-07-03T12:53:12
2017-07-03T12:53:13
165,263,000
0
0
null
2022-07-07T01:51:32
2019-01-11T15:10:45
TypeScript
UTF-8
Java
false
false
1,359
java
package fr.squirtles.tindev.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; /** * An authority (a security role) used by Spring Security. */ @Entity @Table(name = "jhi_authority") public class Authority implements Serializable { private static final long serialVersionUID = 1L; @NotNull @Size(min = 0, max = 50) @Id @Column(length = 50) private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Authority authority = (Authority) o; if (name != null ? !name.equals(authority.name) : authority.name != null) { return false; } return true; } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } @Override public String toString() { return "Authority{" + "name='" + name + '\'' + "}"; } }
70542522a367c4787d2a9c2694b6be3785ab5c87
08c2c0bbf28492623960cf8220da2a50de31e36f
/Лабораторные/laba13/src/ua/khpi/oop/gorianckiy09/LinkedContainer.java
20644e2631fb5c9279c7b737af16ff98c39d0aa2
[]
no_license
Ivan1108/Laboratorniye
8e12954fde76a6ebf973a8dcced58bfd512b054c
b03518535a2a8aa7d08e3168a0f35cbff8ea61ef
refs/heads/master
2020-07-29T01:10:46.218014
2020-05-08T12:54:50
2020-05-08T12:54:50
209,609,185
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
9,019
java
package ua.khpi.oop.gorianckiy09; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LinkedContainer<T extends Directory> implements Linked<T>, Iterable<T>,DescendingIterator<T> { //конструктор инициализации private class Node<T> { private T currElem; //текущий private Node<T> prevElem; //предыдущий private Node<T> nextElem; //следущий //конструктор копирования Node( T currElem, Node<T> prevElem, Node<T> nextElem) { this.currElem = currElem; this.prevElem = prevElem; this.nextElem = nextElem; } //геттеры и сеттеры public T getCurrentElem() { return currElem; } public void setCurrentElem( T currentElem) { this.currElem = currentElem; } public Node<T> getPrevElem() { return prevElem; } public void setPrevElem(Node<T> prevElem) { this.prevElem = prevElem; } public Node<T> getNextElem() { return nextElem; } public void setNextElem(Node<T> nextElem) { this.nextElem = nextElem; } } private Node<T> fstNode; private Node<T> lstNode; private int size = 0; public LinkedContainer() { fstNode = new Node<T>(null,null,lstNode); lstNode = new Node<T>(null,fstNode,null); fstNode = new Node<T>(null,null,lstNode); } @Override public Iterator<T> iterator() { return new Iterator<T>() { private int position = 0; @Override public boolean hasNext() { return position < size; } @Override public T next() { if (this.hasNext()) { return getElementByIndex(position++); } else { throw new NoSuchElementException(); } } }; } @Override public Iterator<T> descendingIterator() { return new Iterator<T>() { int position = size - 1; @Override public boolean hasNext() { return position >= 0; } @Override public T next() { if (this.hasNext()) { position--; return getElementByIndex(position--); } else { throw new NoSuchElementException(); } } }; } @Override public void clear() { for (Node<T> x = fstNode; x != null; ) { Node<T> next = x.nextElem; x.currElem = null; x.nextElem = null; x.prevElem = null; x = next; } fstNode = null; lstNode = null; lstNode = new Node<>(null, fstNode, null); fstNode = new Node<>(null, null, lstNode); size = 0; } @Override public void add(final T t) { addLast(t); } @Override public void toFile() { try { File file = new File("File.txt"); if(!file.exists()) file.createNewFile(); PrintWriter pw = new PrintWriter(file); Directory temp ; System.out.println(); pw.println(size); for(int i=0;i<size;i++) { temp =(Directory)getElementByIndex(i); pw.println(temp.getName()); pw.println(temp.getAddress()); pw.println(temp.getSpecial()); pw.println(temp.getPhone()); pw.println(temp.getTime() ); pw.println(temp.getTime1()); } pw.close(); } catch(IOException e){ System.out.print("Error: " + e); } } @Override public void readAll() { try (BufferedReader br = new BufferedReader(new FileReader("File1.txt"))) { Object temp; String line; line = br.readLine(); int count = Integer.parseInt(line); for (int i = 0; i < count; i++) { line = br.readLine(); temp = line; add((T) temp); } } catch (IOException ex) { ex.printStackTrace(); } } @Override public void FromFile() throws ParseException { BufferedReader br = null; Directory temp = new Directory(); try { br = new BufferedReader(new FileReader("C:\\Users\\User\\eclipse-workspace\\laba11\\File1.txt")); String Line; Line = br.readLine(); int count = Integer.parseInt(Line); for(int i =0;i<count;i++){ Pattern pat = Pattern.compile("^[a-zA-Z]{3,10}[0-9]{0,2}|[a-zA-Z]{3,10}\\s[a-zA-Z]{3,10}[0-9]{0,2}"); Matcher mat3 = null; do { System.out.println("Enter name of outlet"); Line = br.readLine(); mat3 = pat.matcher(Line); }while(!mat3.matches()); temp.setName(Line); Pattern patt = Pattern.compile("^[a-zA-Z]{3,10}[0-9]{0,2}|[a-zA-Z]{3,10}\\s[0-9]{0,2}|[a-zA-Z]{3,10}\\s[a-zA-Z]{3,10}[0-9]{0,2}"); Matcher mat4 = null; do { System.out.println("Enter Address"); Line = br.readLine(); mat4 = patt.matcher(Line); }while(!mat4.matches()); temp.setAddress(Line); Pattern patter = Pattern.compile("^[a-zA-Z]{3,10}|[a-zA-Z]{3,10}\\s[a-zA-Z]{3,10}"); Matcher mat5 = null; do { System.out.println("Enter Specialization"); Line = br.readLine(); mat5 = patter.matcher(Line); }while(!mat5.matches()); temp.setSpecial(Line); Pattern pattern = Pattern.compile("\\d{10,12}"); Matcher m = null; do { System.out.println("Enter Phone number"); Line = br.readLine(); m = pattern.matcher(Line); }while(!m.matches()); temp.setPhone(Line); Pattern pattern1 = Pattern.compile("[0-9]{2}:[0-9]{2}"); Matcher mat1 = null; do { System.out.println("Enter StartTime:"); Line = br.readLine(); mat1 = pattern1.matcher(Line); }while(!mat1.matches()); temp.setTime(Line); Pattern pattern2 = Pattern.compile("[0-9]{2}:[0-9]{2}"); Matcher mat2 = null; do { System.out.println("Enter EndTime:"); Line = br.readLine(); mat2 = pattern2.matcher(Line); }while(!mat2.matches()); temp.setTime1(Line); add((T) new Directory(temp)); } }catch(IOException e) { System.out.print("Error: " + e); }finally { try { br.close(); }catch(IOException e ) { System.out.print("Error: " + e); } } } public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node<T> temp = fstNode; i < size; temp = temp.nextElem) { result[i++] = temp.currElem; } return result; } @Override public String toString() { return Arrays.toString(toArray()); } @Override public void addLast(final T obj) { Node<T> prev = lstNode; //сохранение данных хвоста prev.setCurrentElem((T)new Directory(obj)); //установка значения lstNode = new Node<>(null, prev, null); //изменение указателя хвоста prev.setNextElem(lstNode); //установка указателя на хвост size++; //увелечение размера списка } @Override public void addFirst(final T obj) { Node<T> next = fstNode; next.setCurrentElem(obj); fstNode = new Node<>(null, null, next); next.setPrevElem(fstNode); size++; } @Override public int size() { return size; } @Override public T getElementByIndex(final int index) { Node<T> target = fstNode.getNextElem(); //след элемент первого узла for (int i = 0; i < index; i++) { target = getNextElement(target); } return target.getCurrentElem(); } private Node<T> getNextElement(final Node<T> index) { return index.getNextElem(); } @Override public void DelAll() { fstNode = null; lstNode = null; lstNode = new Node<>(null, fstNode, null); fstNode = new Node<>(null, null, lstNode); size = 0; } @Override public void toFileAll() { try { File file = new File("File.txt"); if(!file.exists()) file.createNewFile(); PrintWriter pw = new PrintWriter(file); System.out.println(); pw.println(size); for(int i=0;i<size;i++) { pw.println(getElementByIndex(i)); } pw.close(); } catch(IOException e){ System.out.print("Error: " + e); } } @Override public void checkEmptiness() { if(size >0) { System.out.println("Container is not empty"); }else { System.out.println("Conteiner is empty"); } } }
ba5118b83deb3a122d8b00be995ef6dcb97aa37f
1a1e61e51e3c7d336b17db89bbb657156990fe19
/src/main/java/ro/sci/ems/domain/Title.java
c3d6134c0f342fc36f70d09c3d5d45e3a19016c0
[]
no_license
ionutmpopa/Employee-Management-System-App
e123e5ba3b9b630725ddac2fc4296313984c1cb6
67f598a335d7a31da270b87f51f7cce5def0f79d
refs/heads/master
2022-10-14T07:18:44.849999
2019-09-03T17:44:16
2019-09-03T17:44:16
178,268,561
0
0
null
2022-09-22T18:40:14
2019-03-28T19:22:59
Java
UTF-8
Java
false
false
77
java
package ro.sci.ems.domain; public enum Title { JUNIOR, MEDIUM, SENIOR }
[ "I.m. Popa@DESKTOP-P5HEJEF" ]
I.m. Popa@DESKTOP-P5HEJEF
c83ceaa4fc3216dd25f436705d2eef20dbbbf989
8b29ebf21cde7c055bf9f9411a3155e2290e8af7
/Tuan5/QLSanpham/src/Proccess/LoaiSP.java
572a47624d445ff1a1cace91939195f207d08903
[]
no_license
vii2309/TH_java
987776073dfbc7c962b11df332bc947a41664257
227de5b94ee7ebfc356ed9cb94d1274d73e0fb0d
refs/heads/main
2023-04-16T07:32:35.471005
2021-04-24T03:46:59
2021-04-24T03:46:59
348,281,735
0
0
null
null
null
null
UTF-8
Java
false
false
1,611
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Proccess; import java.sql.*; import Database.Connect; public class LoaiSP { public Connect cn= new Connect(); //Truy van tat ca du lieu trong Table LoaiSP public ResultSet ShowLoaiSP() throws SQLException{ cn.connectSQL(); String sql = "SELECT * FROM LoaiSP"; return cn.LoadData(sql); } //Truy van cac dong du lieu trong Table LoaiSP theo Maloai public ResultSet ShowLoaiSP(String ml) throws SQLException{ String sql = "SELECT * FROM LoaiSP where Maloai='" + ml +"'"; return cn.LoadData(sql); } //Theo moi 1 dong du lieu vao table LoaiSP public void InsertData(String ml, String tl) throws SQLException{ String sql = "INSERT INTO LoaiSP values('" + ml +"',N'" + tl +"')"; cn.UpdateData(sql); } //Dieu chinh 1 dong du lieu vao table LoaiSP public void EditData(String ml, String tl) throws SQLException{ String sql = "Update LoaiSP set Tenloai=N'" + tl + "' where Maloai='" + ml +"'"; cn.UpdateData(sql); } //Xoa 1 dong du lieu vao table LoaiSP public void DeleteData(String ml) throws SQLException{ String sql = "Delete from LoaiSP where Maloai='" + ml +"'"; cn.UpdateData(sql); } }
0c06a1c2f723209abac46722988eac5d130323e1
b1a7cbbaee8e1d66bb47ec86abf885e89bc04055
/src/main/java/com/akhil/twitter/controller/TwitterController.java
a885cf83e609f69871d9c4dc867a43fecd0da5cd
[]
no_license
akhilbabu868/twitter
0a7adbd198dff449d2dbfbca4ab2f07be97a8f1e
b720964d860f538c37c8acce01087eb511695fb1
refs/heads/master
2023-01-05T22:47:16.757703
2020-09-29T17:17:14
2020-09-29T17:17:14
299,369,554
0
0
null
null
null
null
UTF-8
Java
false
false
2,601
java
package com.akhil.twitter.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.tomcat.util.buf.Ascii; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.social.twitter.api.SearchParameters; import org.springframework.social.twitter.api.SearchResults; import org.springframework.social.twitter.api.Tweet; import org.springframework.social.twitter.api.Twitter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import com.akhil.twitter.model.searchresult; import com.akhil.twitter.model.tweets; import com.akhil.twitter.service.SearchService; import com.akhil.twitter.service.tweetsservice; @RestController public class TwitterController { @Autowired private Twitter twitter; @Autowired private tweetsservice service; @Autowired private SearchService searchservice; public TwitterController(Twitter twitter, tweetsservice service, SearchService seachservice) { this.twitter = twitter; this.service = service; this.searchservice = searchservice; } // function return index page @GetMapping("/") public ModelAndView mv() { ModelAndView mv = new ModelAndView("index"); return mv; } // function returns Search Result by followers and #hashtag @PostMapping("/tweets") public List<searchresult> nameList(@RequestParam("keyword") String keyword, HttpSession session) { SearchParameters params = new SearchParameters(keyword); SearchResults results = twitter.searchOperations().search(params); List<Tweet> Searchresult = results.getTweets(); for (Tweet tweet : Searchresult) { searchresult objResult = new searchresult(0, tweet.getText(), tweet.getProfileImageUrl(),tweet.getFromUser()); searchservice.saveSearchresult(objResult); } List<searchresult> searchlist = searchservice.listAll(); return searchlist; } //function which returns followers tweets @PostMapping("/timeline") public List<tweets> timelineList() { List<Tweet> timeline = twitter.timelineOperations().getHomeTimeline(); for (Tweet tweet : timeline) { tweets objTweets = new tweets(0, tweet.getText(), tweet.getProfileImageUrl(), tweet.getFromUser()); service.saveTweets(objTweets); } List<tweets> home = service.listAll(); return home; } }
513e72aa144bb62ca3e0d454b4524467d736fbdb
2c80ac63a11cc2c6518bf958d097b9aacb5f86dc
/src/main/java/com/bkenterprises/inventory/dao/InventoryRepository.java
8c8eed6b698f2e1d3f273e04ae0ceee56a73934e
[]
no_license
vincentdu101/bk-enterprises-inventory
6bd2dd2f4af5b9f2172287e02ebce9990dd88eac
1968c5055d922d0d753e237a58bcc4a38708ea4c
refs/heads/master
2023-06-17T00:32:39.700942
2021-07-09T07:09:12
2021-07-09T07:09:12
383,385,682
0
0
null
null
null
null
UTF-8
Java
false
false
239
java
package com.bkenterprises.inventory.dao; import com.bkenterprises.inventory.model.Inventory; import org.springframework.data.jpa.repository.JpaRepository; public interface InventoryRepository extends JpaRepository<Inventory, String> { }
fc53370034bd339228051288a8ff86dbb9cb115f
c977392aaf18f10e1ed1957b8bb5a683fc701b45
/app/src/androidTest/java/id/dedegunawan/myapplication/ExampleInstrumentedTest.java
17124af263ea34f9ff8b3e45db393063b1cd0375
[]
no_license
dedegunawan/android-kalkulator-sederhana
8083a743912a33bcf1f91e3cc1243adc7791ffef
53316ad65f9fc3780e9babe877d1277ff602964e
refs/heads/master
2021-08-28T04:17:57.029972
2017-12-11T06:51:38
2017-12-11T06:51:38
113,820,715
0
0
null
null
null
null
UTF-8
Java
false
false
757
java
package id.dedegunawan.myapplication; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("id.dedegunawan.myapplication", appContext.getPackageName()); } }
216fe9a462acc0033124ee740fcdc2f338282793
da9367ce3de3f391954a3208058722ff2e65c194
/src/main/java/com/qf/authen/dao/SubjectDao.java
0c357c21ae2bb979db7a685a52f5d2593b3d68db
[]
no_license
kimlonger/IdeaObject
550c7452068e630b820e6e293ec3434b68fa14cc
981bb1216a0e66d9d6a6f244d3554292214404fa
refs/heads/master
2022-06-23T01:14:06.795450
2020-05-12T15:46:28
2020-05-12T15:46:28
263,375,084
0
0
null
2020-05-12T16:00:36
2020-05-12T15:23:38
JavaScript
UTF-8
Java
false
false
325
java
package com.qf.authen.dao; import com.qf.authen.entity.Subject; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface SubjectDao { //查询所有subject List<Subject>findAll(); //三表联查 Subject queryAllInfo(Integer id); //查询所有 // }
0113fe4796761116ee9bfc36fbfef4e033376f4d
2bcf35f20402c7be2f3eff2113549db619271227
/shoppingbackend/src/main/java/com/shuler/shoppingbackend/dto/Category.java
73fdfdf732aafb1bb75fd612ccc479d1dbf9feea
[]
no_license
gbshuler/online-shopping
a2e26badcc10e08d7088e84eea124cd08a988128
272d3d5c53adac828c1a4fc447359b2be76c6352
refs/heads/master
2021-01-18T20:47:41.084494
2017-10-31T00:03:25
2017-10-31T00:03:25
100,549,579
0
0
null
null
null
null
UTF-8
Java
false
false
1,499
java
package com.shuler.shoppingbackend.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * Hibernate note * The name of the entity is "Category" by default. * We could have changed that with annotation: * Entity(name="categoryNameForJPA") * If the table name is not category we could specify annotation: * Table(name="CAT_TABLE") * At signs left off so we don't hit these with reflection */ @Entity public class Category { @Override public String toString() { return name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String description; @Column(name = "image_url") private String imageURL; @Column(name = "is_active") private boolean active = true; // For admin to activate }
4bd2c6042d2e2c49da5d1ace0c78886a1c708f1e
27b7b01ea3a335b9dcc988c7a42267fd1c8b84bd
/src/main/java/be/vdab/jms/JmsConfig.java
e0298e152f7377935c3475fb62d450f43360552b
[]
no_license
filiphamakers/groenetenen
eab07aef756fa5a26b7625e18118750056290802
6860612c14fd864942bbb3ecda89fde5cb0df73a
refs/heads/master
2021-09-03T00:54:05.380155
2018-01-04T10:49:04
2018-01-04T10:49:04
113,830,189
0
0
null
null
null
null
UTF-8
Java
false
false
1,787
java
package be.vdab.jms; import org.apache.activemq.spring.ActiveMQConnectionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.core.JmsMessagingTemplate; @Configuration @ComponentScan @PropertySource("classpath:/jms.properties") @EnableJms public class JmsConfig { final static String QUEUE_NAME = "nieuwFiliaalQueue"; @Bean static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public ActiveMQConnectionFactory connectionFactory(@Value("${messageBroker.url}") String messageBrokerUrl) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL(messageBrokerUrl); return connectionFactory; } @Bean public JmsMessagingTemplate jmsMessagingTemplate(ActiveMQConnectionFactory connectionFactory) { JmsMessagingTemplate template = new JmsMessagingTemplate(connectionFactory); template.setDefaultDestinationName(QUEUE_NAME); return template; } @Bean public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ActiveMQConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); return factory; } }
5e18d01fe4ce22542b956e18070b5554b0d856a9
95deb75d2429ec4a8017e16465c2c5bb5fc0f4cd
/quickstart/src/main/java/annotation/HelloApp.java
a1e8dfb73d2dbbe88fbefe2fbdb5a6fb0a7a043e
[]
no_license
InvaderCM/spring-study
6b8ed9a973e139ecf38c3c1ac44d01dd4f15bb58
4f11ce148133374b751d44c802df7934edb82c61
refs/heads/master
2020-04-26T15:26:53.069772
2019-03-14T03:16:03
2019-03-14T03:16:03
173,647,280
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
package annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; /** * @ComponentScan用于寻找用component注解标注的bean */ @ComponentScan public class HelloApp { public static void main(String[] args) { //1 通过注解创建上下文对象 ApplicationContext context =new AnnotationConfigApplicationContext(HelloApp.class); //2 读取bean Hello hello=context.getBean(Hello.class); //3 运行 System.out.println(hello.getHello()); } }
8ba94148dcb12cca896374028de9deb42a31cf50
8823c96d433605e7c13679b027a697e6a647cf9c
/src/main/java/com/lzhlyle/leetcode/recite/no589/Node.java
1c62784aa2377da2f80837ab92ef987b7891458d
[ "MIT" ]
permissive
lzhlyle/leetcode
62278bf6e949f802da335e8de2d420440f578c2f
8f053128ed7917c231fd24cfe82552d9c599dc16
refs/heads/master
2022-07-14T02:28:11.082595
2020-11-16T14:28:20
2020-11-16T14:28:20
215,598,819
2
0
MIT
2022-06-17T02:55:41
2019-10-16T16:52:05
Java
UTF-8
Java
false
false
286
java
package com.lzhlyle.leetcode.recite.no589; import java.util.List; class Node { public int val; public List<Node> children; public Node() { } public Node(int _val, List<Node> _children) { val = _val; children = _children; } };
be25ecd2f230f8f41c888badc2e56b8bb669d48c
e7cfbf3df865d01796609c3ee421197b616cc34e
/nbt-injector/src/main/java/de/tr7zw/nbtinjector/NBTInjector.java
30f94c7c799ea9ed41d6dfc972f82fca4b48b6ce
[ "MIT" ]
permissive
jyhsu2000/Item-NBT-API
90dd1b2f63895cdf3d3d33238e72f45f666f4f4d
96d6164d99c79975b52c90b39f98194adb2f40a3
refs/heads/master
2020-06-03T11:18:20.886497
2019-06-10T21:31:12
2019-06-10T21:31:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,471
java
package de.tr7zw.nbtinjector; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import de.tr7zw.changeme.nbtapi.ClassWrapper; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTContainer; import de.tr7zw.changeme.nbtapi.NBTEntity; import de.tr7zw.changeme.nbtapi.NBTReflectionUtil; import de.tr7zw.changeme.nbtapi.NBTTileEntity; import de.tr7zw.changeme.nbtapi.NbtApiException; import de.tr7zw.changeme.nbtapi.ObjectCreator; import de.tr7zw.changeme.nbtapi.ReflectionMethod; import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; import javassist.ClassPool; public class NBTInjector { static Logger logger = Logger.getLogger("NBTInjector"); /** * Replaces the vanilla classes with Wrapped classes that support custom NBT. * This method needs to be called during onLoad so classes are replaced before worlds load. * If your plugin adds a new Entity(probably during onLoad) recall this method so it's class gets Wrapped. */ public static void inject() { try { ClassPool classPool = ClassPool.getDefault(); logger.info("[NBTINJECTOR] Injecting Entity classes..."); if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { for (Map.Entry<String, Class<?>> entry : new HashSet<>(Entity.getCMap().entrySet())) { try { if (INBTWrapper.class.isAssignableFrom(entry.getValue())) { continue; }//Already injected int entityId = Entity.getFMap().get(entry.getValue()); Class<?> wrapped = ClassGenerator.wrapEntity(classPool, entry.getValue(), "__extraData"); Entity.getCMap().put(entry.getKey(), wrapped); Entity.getDMap().put(wrapped, entry.getKey()); Entity.getEMap().put(entityId, wrapped); Entity.getFMap().put(wrapped, entityId); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + entry.getKey(), e); } } } else { Object registry = Entity.getRegistry(); Map<Object, Object> inverse = new HashMap<>(); Set<?> it = new HashSet<>((Set<?>) ReflectionMethod.REGISTRY_KEYSET.run(registry)); for(Object mckey : it) { Class<?> tileclass = (Class<?>) ReflectionMethod.REGISTRY_GET.run(registry, mckey); inverse.put(tileclass, mckey); try { if (INBTWrapper.class.isAssignableFrom(tileclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapEntity(classPool, tileclass, "__extraData"); ReflectionMethod.REGISTRY_SET.run(registry, mckey, wrapped); inverse.put(wrapped, mckey); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } Field inverseField = registry.getClass().getDeclaredField("b"); setFinal(registry, inverseField, inverse); } logger.info("[NBTINJECTOR] Injecting Tile Entity classes..."); if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { for (Map.Entry<String, Class<?>> entry : new HashSet<>(TileEntity.getFMap().entrySet())) { try { if (INBTWrapper.class.isAssignableFrom(entry.getValue())) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapTileEntity(classPool, entry.getValue(), "__extraData"); TileEntity.getFMap().put(entry.getKey(), wrapped); TileEntity.getGMap().put(wrapped, entry.getKey()); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + entry.getKey(), e); } } } else { Object registry = TileEntity.getRegistry(); Map<Object, Object> inverse = new HashMap<>(); Set<?> it = new HashSet<>((Set<?>) ReflectionMethod.REGISTRY_KEYSET.run(registry)); for(Object mckey : it) { Class<?> tileclass = (Class<?>) ReflectionMethod.REGISTRY_GET.run(registry, mckey); inverse.put(tileclass, mckey); try { if (INBTWrapper.class.isAssignableFrom(tileclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapTileEntity(classPool, tileclass, "__extraData"); ReflectionMethod.REGISTRY_SET.run(registry, mckey, wrapped); inverse.put(wrapped, mckey); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } Field inverseField = registry.getClass().getDeclaredField("b"); setFinal(registry, inverseField, inverse); } } catch (Exception e) { throw new RuntimeException(e); } } private static NBTCompound getNbtData(Object object) { if (object instanceof INBTWrapper) { return ((INBTWrapper) object).getNbtData(); } return null; } /** * Entities that have just been spawned(from plugins or natually) may use the wrong(Vanilla) class. * Calling this method removes the wrong entity and respawns it using the correct class. It also tries * to keep all data of the original entity, but some stuff like passengers will probably cause problems. * Recalling this method on a patched Entity doesn nothing and returns the Entity instance. * * WARNING: This causes the entity to get a new Bukkit Entity instance. For other plugins the entity will * be a dead/removed entity, even if it's still kinda there. Bestcase you spawn an Entity and directly replace * your instance with a patched one. * Also, for players ingame the entity will quickly flash, since it's respawned. * * @param entity Entity to respawn with the correct class. * @return Entity The new instance of the entity. */ public static org.bukkit.entity.Entity patchEntity(org.bukkit.entity.Entity entity){ if (entity == null) { return null; } try { Object ent = NBTReflectionUtil.getNMSEntity(entity); if (!(ent instanceof INBTWrapper)) {//Replace Entity with custom one Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(entity.getWorld()); Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); NBTContainer oldNBT = new NBTContainer(new NBTEntity(entity).getCompound()); Method create = ClassWrapper.NMS_ENTITYTYPES.getClazz().getMethod("a", ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), ClassWrapper.NMS_WORLD.getClazz()); String id = ""; if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { id = Entity.getBackupMap().get(ent.getClass()); }else { id = ReflectionMethod.REGISTRY_GET_INVERSE.run(Entity.getRegistry(), ent.getClass()).toString(); } oldNBT.setString("id", id); oldNBT.removeKey("UUIDMost"); oldNBT.removeKey("UUIDLeast"); entity.remove(); Object newEntity = create.invoke(null, oldNBT.getCompound(), nmsworld); Method spawn = ClassWrapper.NMS_WORLD.getClazz().getMethod("addEntity", ClassWrapper.NMS_ENTITY.getClazz()); spawn.invoke(nmsworld, newEntity); Method asBukkit = newEntity.getClass().getMethod("getBukkitEntity"); return (org.bukkit.entity.Entity) asBukkit.invoke(newEntity); } } catch (Exception e) { throw new NbtApiException("Error while patching an Entity '" + entity + "'", e); } return entity; } /** * Gets the persistant NBTCompound from a given entity. If the Entity isn't yet patched, * this method will return null. * * @param entity Entity to get the NBTCompound from * @return NBTCompound instance */ public static NBTCompound getNbtData(org.bukkit.entity.Entity entity) { if (entity == null) { return null; } try { Object ent = NBTReflectionUtil.getNMSEntity(entity); /*if (!(ent instanceof INBTWrapper)) {//Replace Entity with custom one entity = patchEntity(entity); System.out.println("Autopatched Entity: " + entity); return getNbtData(NBTReflectionUtil.getNMSEntity(entity)); return null; // For now don't do anything, just return null. }*/ return getNbtData(ent); } catch (Exception e) { throw new NbtApiException("Error while getting the NBT from an Entity '" + entity + "'.", e); } } /** * Gets the persistant NBTCompound from a given TileEntity. If the Tile isn't yet patched, * this method will autopatch it. This will unlink the given BlockState, so calling block.getState() * again may be necessary. This behavior may change in the future. * * @param tile TileEntity to get the NBTCompound from * @return NBTCompound instance */ public static NBTCompound getNbtData(org.bukkit.block.BlockState tile) { if (tile == null) { return null; } try { Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ()); Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld()); Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); Object tileEntity = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos); if(tileEntity == null) { // Not a tile block return null; } if (!(tileEntity instanceof INBTWrapper)) { //Loading Updated Tile Object tileEntityUpdated; if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_9_R1) { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD_LEGACY191.run(null, null, new NBTTileEntity(tile).getCompound()); } else if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_8_R3 || MinecraftVersion.getVersion() == MinecraftVersion.MC1_9_R2) { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD_LEGACY183.run(null, new NBTTileEntity(tile).getCompound()); } else { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD.run(null, nmsworld, new NBTTileEntity(tile).getCompound()); } ReflectionMethod.NMS_WORLD_REMOVE_TILEENTITY.run(nmsworld, pos); ReflectionMethod.NMS_WORLD_SET_TILEENTITY.run(nmsworld, pos, tileEntityUpdated); return getNbtData(tileEntityUpdated); } return getNbtData(tileEntity); } catch (Exception e) { throw new RuntimeException(e); } } private static void setFinal(Object obj, Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(obj, newValue); } private static Field getAccessable(Field field) { field.setAccessible(true); return field; } static class Entity { private static Map<Class<?>, String> backupMap = new HashMap<>(); static { try { if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { backupMap.putAll(getDMap()); } } catch (ReflectiveOperationException e) { e.printStackTrace(); } } static Object getRegistry() throws ReflectiveOperationException { return getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("b")).get(null); } static Map<Class<?>, String> getBackupMap() throws ReflectiveOperationException { return backupMap; } static Map<String, Class<?>> getCMap() throws ReflectiveOperationException { return (Map<String, Class<?>>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("c")).get(null); } static Map<Class<?>, String> getDMap() throws ReflectiveOperationException { return (Map<Class<?>, String>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("d")).get(null); } static Map<Integer, Class<?>> getEMap() throws ReflectiveOperationException { return (Map<Integer, Class<?>>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("e")).get(null); } static Map<Class<?>, Integer> getFMap() throws ReflectiveOperationException { return (Map<Class<?>, Integer>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("f")).get(null); } } static class TileEntity { static Object getRegistry() throws ReflectiveOperationException { return getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("f")).get(null); } static Map<String, Class<?>> getFMap() throws ReflectiveOperationException { return (Map<String, Class<?>>) getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("f")).get(null); } static Map<Class<?>, String> getGMap() throws ReflectiveOperationException { return (Map<Class<?>, String>) getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("g")).get(null); } } }
568e6bf1a28679963781bda685774b381b0d574f
66a094dc6b84871efb0d96dc335a4eda86b4431a
/Printer.java
06bc5617cf6a547f9ef0466dce0ad11bc5179e8f
[]
no_license
AssaadHalabi/programmingLanguages
043ab7245b7409e9f8abc01874fc5f5904e40e37
f6bff9333881fd8bb402e65e3ab3a19894e9967e
refs/heads/main
2023-03-18T23:10:29.111646
2021-03-19T02:00:44
2021-03-19T02:00:44
349,265,915
0
0
null
null
null
null
UTF-8
Java
false
false
143
java
package programmingLanguages; /** * Printer */ public interface Printer { boolean print(int numPages); void replenishToner(int t); }
d8c61121a9491bc75185af749aab31fe5de88a3a
abc013917d9f306a7272fca33a17517b3e4f5cf8
/案例7:Redis常见数据类型-Hash散列存储/fastPower/src/main/java/com/power/config/RabbitmqConfig.java
f551b4509d6db97d915c431efbc19158da871fca
[]
no_license
yanchao00551/springboot-redis
8fcd1104082a22b15ecc6b48ce42b4cf5069bbc0
af3175069294b8e7f05818bf61b571ec337b1531
refs/heads/master
2023-05-23T10:29:03.763500
2021-06-14T11:57:41
2021-06-14T11:57:41
376,798,990
0
0
null
null
null
null
UTF-8
Java
false
false
8,361
java
package com.power.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.support.CorrelationData; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; /** * RabbitMQ自定义注入配置Bean相关组件 */ @Configuration public class RabbitmqConfig { //定义日志 private static final Logger log = LoggerFactory.getLogger(RabbitmqConfig.class); //自动装配RabbitMQ的链接工厂实例 @Autowired private CachingConnectionFactory connectionFactory; //自动装配消息监听器所在的容器工厂配置类实例 @Autowired private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer; //定义读取配置文件的环境变量实例 @Autowired private Environment env; /** 创建简单的消息模型:队列、交换机和路由 **/ //创建队列 @Bean(name = "basicQueue") public Queue basicQueue(){ return new Queue(env.getProperty("mq.basic.info.queue.name"),true); } //创建交换机:在这里以DirectExchange为例 @Bean public DirectExchange basicExchange(){ return new DirectExchange(env.getProperty("mq.basic.info.exchange.name"),true,false); } //创建绑定 @Bean public Binding basicBinding(){ return BindingBuilder.bind(basicQueue()).to(basicExchange()).with(env.getProperty("mq.basic.info.routing.key.name")); } /** 创建简单的消息模型:队列、交换机和路由 发送对象消息 **/ //创建队列 @Bean(name = "objectQueue") public Queue objectQueue(){ return new Queue(env.getProperty("mq.object.info.queue.name"),true); } //创建交换机:在这里以DirectExchange为例 @Bean public DirectExchange objectExchange(){ return new DirectExchange(env.getProperty("mq.object.info.exchange.name"),true,false); } //创建绑定 @Bean public Binding objectBinding(){ return BindingBuilder.bind(objectQueue()).to(objectExchange()).with(env.getProperty("mq.object.info.routing.key.name")); } /** 创建消息模型 - fanoutExchange **/ //创建队列1 @Bean(name = "fanoutQueueOne") public Queue fanoutQueueOne(){ return new Queue(env.getProperty("mq.fanout.queue.one.name"),true); } //创建队列2 @Bean(name = "fanoutQueueTwo") public Queue fanoutQueueTwo(){ return new Queue(env.getProperty("mq.fanout.queue.two.name"),true); } //创建交换机 @Bean public FanoutExchange fanoutExchange(){ return new FanoutExchange(env.getProperty("mq.fanout.exchange.name"),true,false); } //创建绑定1 @Bean public Binding fanoutBindingOne(){ return BindingBuilder.bind(fanoutQueueOne()).to(fanoutExchange()); } //创建绑定2 @Bean public Binding fanoutBindingTwo(){ return BindingBuilder.bind(fanoutQueueTwo()).to(fanoutExchange()); } /**创建消息模型-topicExchange **/ //创建交换机-topicExchange @Bean public TopicExchange topicExchange(){ return new TopicExchange(env.getProperty("mq.topic.exchange.name")); } //创建队列1 @Bean(name = "topicQueueOne") public Queue topicQueueOne(){ return new Queue(env.getProperty("mq.topic.queue.one.name"),true); } //创建队列2 @Bean(name = "topicQueueTwo") public Queue topicQueueTwo(){ return new Queue(env.getProperty("mq.topic.queue.two.name"),true); } //创建绑定-通配符为*的路由 @Bean public Binding topicBindingOne(){ return BindingBuilder.bind(topicQueueOne()).to(topicExchange()).with(env.getProperty("mq.topic.routing.key.one.name")); } //创建绑定-通配符为#的路由 @Bean public Binding topicBindingTwo(){ return BindingBuilder.bind(topicQueueTwo()).to(topicExchange()).with(env.getProperty("mq.topic.routing.key.two.name")); } /** * 下面为单一消费者实例的配置 * @return */ @Bean(name = "singleListenerContainer") public SimpleRabbitListenerContainerFactory listenerContainer(){ //定义消息监听器所在的容器工厂 SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); //设置容器工厂所用的实例 factory.setConnectionFactory(connectionFactory); //设置消息在传输中的格式,在这里采用JSON的格式进行传输 factory.setMessageConverter(new Jackson2JsonMessageConverter()); //设置并发消费者实例的初始数量。在这里为1个 factory.setConcurrentConsumers(1); //设置并发消费者实例的最大数量。在这里为1个 factory.setMaxConcurrentConsumers(1); //设置并发消费者实例中每个实例拉取的消息数量-在这里为1个 factory.setPrefetchCount(1); return factory; } /** * 下面为多个消费者实例的配置,主要是针对高并发业务场景的配置 * @return */ @Bean(name = "multiListenerContainer") public SimpleRabbitListenerContainerFactory multiListenerContainer(){ //定义消息监听器所在的容器工厂 SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); //设置容器工厂所用的实例 factoryConfigurer.configure(factory,connectionFactory); //设置消息在传输中的格式,在这里采用JSON的格式进行传输 factory.setMessageConverter(new Jackson2JsonMessageConverter()); //设置消息的确认消费模式。在这里为NONE,表示不需要确认消费 factory.setAcknowledgeMode(AcknowledgeMode.NONE); //设置并发消费者实例的初始数量。在这里为10个 factory.setConcurrentConsumers(10); //设置并发消费者实例的最大数量。在这里为15个 factory.setMaxConcurrentConsumers(15); //设置并发消费者实例中每个实例拉取的消息数量。在这里为10个 factory.setPrefetchCount(10); return factory; } //自定义配置RabbitMQ发送消息的操作组件 RabbitTemplate @Bean public RabbitTemplate rabbitTemplate(){ //设置“发送消息后进行确认” connectionFactory.setPublisherConfirms(true); //设置“发送消息后返回确认信息" connectionFactory.setPublisherReturns(true); //构造发送消息组件实例对象 RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMandatory(true); //发送消息成功后,如果发送成功,则输出“消息发送成功”的反馈信息 rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { log.info("消息发送成功:correlationData({}),ack({}),cause({})",correlationData,ack,cause); } }); //发送消息后,如果发送失败,则输出“消息发送失败-消息丢失”的反馈信息 rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() { @Override public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) { log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}",exchange,routingKey,replyCode,replyText,message); } }); //最终返回RabbitMQ的操作组件实例RabbitTemplate return rabbitTemplate; } }
47a7bc92aaa8e31668337807a42222890a353a08
c694e4f47e16c45e6e29c35e90888922c2250429
/de.xwic.etlgine.core/src/de/xwic/etlgine/trigger/TriggerList.java
350be55977d40ae6bf844b42941bec21047621c6
[]
no_license
xwic/etlgine
0da1cac91c77e5c91c3f4adafbaa6aeef53ca247
a48611331e9915144e1397dc89bffda57747a894
refs/heads/master
2023-09-02T04:03:40.970392
2019-05-10T11:22:52
2019-05-10T11:22:52
8,337,869
8
1
null
2019-05-10T10:58:50
2013-02-21T15:26:19
Java
UTF-8
Java
false
false
2,809
java
/** * */ package de.xwic.etlgine.trigger; import java.util.ArrayList; import java.util.Collection; import de.xwic.etlgine.ITrigger; /** * @author jbornema * * Wraps one or more ITrigger. * * Also ensures that when a job starts execution the original isDue() state persists till notifyJobFinished(boolean). * This behavior enables during job executing to check for the original isDue() state. * The general use is to implement different behavior when the job was manually enqueued (then isDue() is false). */ public class TriggerList implements ITrigger { protected Collection<ITrigger> triggers = new ArrayList<ITrigger>(); protected ITrigger dueTrigger = null; protected Boolean due = null; /** * */ public TriggerList() { } /** * * @param triggers */ public TriggerList(ITrigger... triggers) { for (ITrigger trigger : triggers) { this.triggers.add(trigger); } } /** * Adds trigger to list of triggers checked. * @param trigger * @return */ public ITrigger addTrigger(ITrigger trigger) { triggers.add(trigger); return trigger; } /** * Removes the trigger from list. * @param trigger * @return */ public ITrigger removeTrigger(ITrigger trigger) { if (triggers.remove(trigger)) { if (dueTrigger == trigger) { dueTrigger = null; } return trigger; } return null; } /** * @return the triggers */ public Collection<ITrigger> getTriggers() { return triggers; } /** * @param triggers the triggers to set */ public void setTriggers(Collection<ITrigger> triggers) { this.triggers = triggers; } /* (non-Javadoc) * @see de.xwic.etlgine.ITrigger#isDue() */ @Override public boolean isDue() { if (due != null) { return due; } for (ITrigger trigger : triggers) { if (trigger.isDue()) { setDueTrigger(trigger); return true; } } return false; } /* (non-Javadoc) * @see de.xwic.etlgine.ITrigger#notifyJobStarted() */ @Override public void notifyJobStarted() { ITrigger trigger = getDueTrigger(); if (trigger != null) { due = trigger.isDue(); trigger.notifyJobStarted(); } else { due = null; } } /* (non-Javadoc) * @see de.xwic.etlgine.ITrigger#notifyJobFinished(boolean) */ @Override public void notifyJobFinished(boolean withErrors) { due = null; ITrigger trigger = getDueTrigger(); if (trigger != null) { trigger.notifyJobFinished(withErrors); } } /** * @return the dueTrigger */ public ITrigger getDueTrigger() { return dueTrigger; } /** * @param dueTrigger the dueTrigger to set */ public void setDueTrigger(ITrigger dueTrigger) { this.dueTrigger = dueTrigger; } }
887836b340ab528730567be225364c19e4a384ec
d67fa999fdb9958c00167cab01048189290c48fc
/src/OknoLogowania.java
f1be60ae65d886a59cacff57701154de8c7473e0
[ "MIT" ]
permissive
xKomi/App-for-a-telecom
b2ff1578377e99bf112b6f6ba10f1351e8fad6e5
7ca33f283542ad0ba77ad3477bcd693a9290b32e
refs/heads/main
2023-01-23T16:44:25.922903
2020-12-12T20:40:03
2020-12-12T20:40:03
320,917,386
0
0
null
null
null
null
UTF-8
Java
false
false
566
java
package wbd_vol2; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class OknoLogowania extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("OknoLogowania.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Operator telekomunikacyjny"); stage.setResizable(false); stage.show(); } }
d502f07719b0ec97fafcba94c664d2f5a6061150
dbef3d5cdcc5152a0e743500c1a110d7932db55d
/JavaOOP/src/Quadrato.java
613db2609542ab915741ab6b31b2053ba07cd515
[]
no_license
salvoemme/Java---Workspace
051376db6831e3a754715372e02e819e52ba88cf
5a3e862ee04e03e866c845b25a98c3d7072e0d41
refs/heads/master
2021-01-10T03:58:52.802264
2015-06-02T05:02:18
2015-06-02T05:02:18
36,685,144
0
0
null
null
null
null
UTF-8
Java
false
false
216
java
public class Quadrato extends Rettangolo{ public Quadrato(int x, int y, int lato){ super(x,y,lato,lato); } public double perimetro(){ return base*4; } public double area(){ return super.area(); } }
773653c17951404ade83f21ac2a4e77e67bf1fa2
1a58c178773f6aeab14a58cb4d853710aac3eea9
/modules/lwjgl/opengles/src/generated/java/org/lwjgl/opengles/EXTTessellationShader.java
8313d669f8503f7987b673957f4f923870af0e5c
[ "LicenseRef-scancode-khronos", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
CRKatri/lwjgl3
12343871fd3eab7e5584a0b4a1e6bf82381b2f5d
139988556d4f1e45b3a73b799f9bf54014778b8a
refs/heads/master
2023-08-15T15:25:28.770018
2021-10-20T18:36:00
2021-10-20T18:36:00
383,857,413
11
2
BSD-3-Clause
2021-07-07T16:14:39
2021-07-07T16:14:38
null
UTF-8
Java
false
false
9,189
java
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengles; import org.lwjgl.system.*; /** * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_tessellation_shader.txt">EXT_tessellation_shader</a> extension. * * <p>This extension introduces new tessellation stages and two new shader types to the OpenGL ES primitive processing pipeline. These pipeline stages * operate on a new basic primitive type, called a patch. A patch consists of a fixed-size collection of vertices, each with per-vertex attributes, plus a * number of associated per-patch attributes. Tessellation control shaders transform an input patch specified by the application, computing per-vertex and * per-patch attributes for a new output patch. A fixed-function tessellation primitive generator subdivides the patch, and tessellation evaluation * shaders are used to compute the position and attributes of each vertex produced by the tessellator.</p> * * <p>When tessellation is active, it begins by running the optional tessellation control shader. This shader consumes an input patch and produces a new * fixed-size output patch. The output patch consists of an array of vertices, and a set of per-patch attributes. The per-patch attributes include * tessellation levels that control how finely the patch will be tessellated. For each patch processed, multiple tessellation control shader invocations * are performed -- one per output patch vertex. Each tessellation control shader invocation writes all the attributes of its corresponding output patch * vertex. A tessellation control shader may also read the per-vertex outputs of other tessellation control shader invocations, as well as read and write * shared per-patch outputs. The tessellation control shader invocations for a single patch effectively run as a group. A built-in barrier() function is * provided to allow synchronization points where no shader invocation will continue until all shader invocations have reached the barrier.</p> * * <p>The tessellation primitive generator then decomposes a patch into a new set of primitives using the tessellation levels to determine how finely * tessellated the output should be. The primitive generator begins with either a triangle or a quad, and splits each outer edge of the primitive into a * number of segments approximately equal to the corresponding element of the outer tessellation level array. The interior of the primitive is tessellated * according to elements of the inner tessellation level array. The primitive generator has three modes: "triangles" and "quads" split a triangular or * quad-shaped patch into a set of triangles that cover the original patch; "isolines" splits a quad-shaped patch into a set of line strips running across * the patch horizontally. Each vertex generated by the tessellation primitive generator is assigned a (u,v) or (u,v,w) coordinate indicating its relative * location in the subdivided triangle or quad.</p> * * <p>For each vertex produced by the tessellation primitive generator, the tessellation evaluation shader is run to compute its position and other * attributes of the vertex, using its (u,v) or (u,v,w) coordinate. When computing final vertex attributes, the tessellation evaluation shader can also * read the attributes of any of the vertices of the patch written by the tessellation control shader. Tessellation evaluation shader invocations are * completely independent, although all invocations for a single patch share the same collection of input vertices and per-patch attributes.</p> * * <p>The tessellator operates on vertices after they have been transformed by a vertex shader. The primitives generated by the tessellator are passed * further down the OpenGL ES pipeline, where they can be used as inputs to geometry shaders, transform feedback, and the rasterizer.</p> * * <p>The tessellation control and evaluation shaders are both optional. If neither shader type is present, the tessellation stage has no effect. However, if * either a tessellation control or a tessellation evaluation shader is present, the other must also be present.</p> * * <p>Not all tessellation shader implementations have the ability to write the point size from a tessellation shader. Thus a second extension string and * shading language enable are provided for implementations which do support tessellation shader point size.</p> * * <p>This extension relies on the EXT_shader_io_blocks extension to provide the required functionality for declaring input and output blocks and interfacing * between shaders.</p> * * <p>This extension relies on the EXT_gpu_shader5 extension to provide the 'precise' and 'fma' functionality which are necessary to ensure crack-free * tessellation.</p> * * <p>Requires {@link GLES31 GLES 3.1}.</p> */ public class EXTTessellationShader { static { GLES.initialize(); } /** Accepted by the {@code mode} parameter of DrawArrays, DrawElements, and other commands which draw primitives. */ public static final int GL_PATCHES_EXT = 0xE; /** Accepted by the {@code pname} parameter of PatchParameteriEXT, GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v. */ public static final int GL_PATCH_VERTICES_EXT = 0x8E72; /** Accepted by the {@code pname} parameter of GetProgramiv. */ public static final int GL_TESS_CONTROL_OUTPUT_VERTICES_EXT = 0x8E75, GL_TESS_GEN_MODE_EXT = 0x8E76, GL_TESS_GEN_SPACING_EXT = 0x8E77, GL_TESS_GEN_VERTEX_ORDER_EXT = 0x8E78, GL_TESS_GEN_POINT_MODE_EXT = 0x8E79; /** Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE_EXT. */ public static final int GL_ISOLINES_EXT = 0x8E7A, GL_QUADS_EXT = 0x7; /** Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING_EXT. */ public static final int GL_FRACTIONAL_ODD_EXT = 0x8E7B, GL_FRACTIONAL_EVEN_EXT = 0x8E7C; /** Accepted by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv, and GetInteger64v. */ public static final int GL_MAX_PATCH_VERTICES_EXT = 0x8E7D, GL_MAX_TESS_GEN_LEVEL_EXT = 0x8E7E, GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_EXT = 0x8E7F, GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT = 0x8E80, GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_EXT = 0x8E81, GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_EXT = 0x8E82, GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_EXT = 0x8E83, GL_MAX_TESS_PATCH_COMPONENTS_EXT = 0x8E84, GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_EXT = 0x8E85, GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_EXT = 0x8E86, GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_EXT = 0x8E89, GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_EXT = 0x8E8A, GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_EXT = 0x886C, GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_EXT = 0x886D, GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_EXT = 0x8E1E, GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT = 0x8E1F, GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_EXT = 0x92CD, GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_EXT = 0x92CE, GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_EXT = 0x92D3, GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_EXT = 0x92D4, GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_EXT = 0x90CB, GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_EXT = 0x90CC, GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_EXT = 0x90D8, GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_EXT = 0x90D9, GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED = 0x8221; /** Accepted by the {@code props} parameter of GetProgramResourceiv. */ public static final int GL_IS_PER_PATCH_EXT = 0x92E7, GL_REFERENCED_BY_TESS_CONTROL_SHADER_EXT = 0x9307, GL_REFERENCED_BY_TESS_EVALUATION_SHADER_EXT = 0x9308; /** * Accepted by the {@code type} parameter of CreateShader, by the {@code pname} parameter of GetProgramPipelineiv, and returned by the {@code params} * parameter of GetShaderiv. */ public static final int GL_TESS_EVALUATION_SHADER_EXT = 0x8E87, GL_TESS_CONTROL_SHADER_EXT = 0x8E88; /** Accepted by the {@code stages} parameter of UseProgramStages. */ public static final int GL_TESS_CONTROL_SHADER_BIT_EXT = 0x8, GL_TESS_EVALUATION_SHADER_BIT_EXT = 0x10; protected EXTTessellationShader() { throw new UnsupportedOperationException(); } // --- [ glPatchParameteriEXT ] --- public static native void glPatchParameteriEXT(@NativeType("GLenum") int pname, @NativeType("GLint") int value); }
2bfe422094b811e75b4ca879a5535ef11df30c94
13a1f35e001b864b8ac277e43c7569c9fe88d145
/src/main/java/com/fun/Statement.java
679a33e6fcdfb6a630903bf8cac96c6086add006
[]
no_license
DuzzleDug/pineapple-java
19931818e382914acdd9981a16358b03335e4acb
d1c62b6697b2a2d59a9da5483bbe91821f1bba67
refs/heads/main
2023-02-17T11:49:00.748055
2021-01-20T09:27:41
2021-01-20T09:27:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
93
java
package com.fun; /** * empty interface marked statement */ public interface Statement { }
a7026dd6c74ce918cae3c758d60137056da64d34
7414bc380830ad858d0d7e368b23ff37fba1c2e5
/src/main/java/com/example/chapter05/mybatis/BooksController.java
2414946eaf39ba59eedcc2bb32fbf10b2feda99e
[]
no_license
orgain1/myrepository1
61db009a027e881897f896f326eef0719759acd1
653235605cf1588665528e4c720b72222f431854
refs/heads/master
2022-12-11T04:56:44.855772
2020-08-19T02:50:51
2020-08-19T02:50:51
288,616,289
0
0
null
null
null
null
UTF-8
Java
false
false
1,244
java
package com.example.chapter05.mybatis; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import java.util.List; @Controller public class BooksController { @Resource private BooksService booksService; @RequestMapping(value = "/getAllBooks") public ModelAndView getAllBooks( @RequestParam(value = "pageNum",defaultValue = "0") int pageNum, @RequestParam(value = "size", defaultValue = "2") int size){ ModelAndView view = new ModelAndView(); PageHelper.startPage(pageNum,size," id desc "); List<Books> booksList = booksService.getAllBooks(); PageInfo<Books> pageInfo = new PageInfo<>(booksList); //view.addObject("booksList",booksList); view.addObject("pageInfo",pageInfo); view.setViewName("list"); return view; } }
e765c568e021dac9b17de083514f1be11ca03efe
514c91e53907e60cf185cbc2bbffedb467591277
/SAD/src/es/cj/script/tarea1_6.java
3aab38fe6364a4144ffcaa721b1e9ec06adec039
[ "MIT" ]
permissive
raframmed/raframmed_iaw
fae88e7545829d5fda11ee5e406195b2c515ce42
b97e60ff70530be3725c887d52ea8de378b23a44
refs/heads/master
2020-03-29T19:20:36.229018
2019-02-27T22:28:29
2019-02-27T22:28:29
150,258,206
0
0
null
null
null
null
ISO-8859-1
Java
false
false
4,811
java
package es.cj.script; import java.io.IOException; import java.util.Scanner; public class tarea1_6 { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws IOException { int opc=0; do{ System.out.println("****** Menú ******\n"); System.out.println("1.- Encriptar \n"); System.out.println("2.- Desencriptar \n"); System.out.println("3.- Salir \n"); System.out.println("Elija una opción:"); opc = sc.nextInt(); switch(opc) { case 1: System.out.println("Introduzca el texto a ecriptar seprados por '_':"); String palabra = sc.next(); System.out.println("\n"); for (int i = 0; i <palabra.length (); i++) { char c = palabra.charAt(i); switch(c) { case 'a': c = 'z'; break; case 'b': c = 'y'; break; case 'c': c = 'x'; break; case 'd': c = 'w'; break; case 'e': c = 'v'; break; case 'f': c = 'u'; break; case 'g': c = 't'; break; case 'h': c = 's'; break; case 'i': c = 'r'; break; case 'j': c = 'q'; break; case 'k': c = 'p'; break; case 'l': c = 'o'; break; case 'm': c = 'n'; break; case 'n': c = 'm'; break; case 'o': c = 'l'; break; case 'p': c = 'k'; break; case 'q': c = 'j'; break; case 'r': c = 'i'; break; case 's': c = 'h'; break; case 't': c = 'g'; break; case 'u': c = 'f'; break; case 'v': c = 'e'; break; case 'w': c = 'd'; break; case 'x': c = 'c'; break; case 'y': c = 'b'; break; case 'z': c = 'a'; break; case 'ñ': c = '2'; break; default: c = '1'; break; } System.out.print(c); } System.out.println("\n\n\n\n"); break; case 2: System.out.println("Introduzca el texto a desencriptar:"); String palabra_des = sc.next(); System.out.println("\n"); for (int i = 0; i <palabra_des.length (); i++) { char c = palabra_des.charAt(i); switch(c) { case 'a': c = 'z'; break; case 'b': c = 'y'; break; case 'c': c = 'x'; break; case 'd': c = 'w'; break; case 'e': c = 'v'; break; case 'f': c = 'u'; break; case 'g': c = 't'; break; case 'h': c = 's'; break; case 'i': c = 'r'; break; case 'j': c = 'q'; break; case 'k': c = 'p'; break; case 'l': c = 'o'; break; case 'm': c = 'n'; break; case 'n': c = 'm'; break; case 'o': c = 'l'; break; case 'p': c = 'k'; break; case 'q': c = 'j'; break; case 'r': c = 'i'; break; case 's': c = 'h'; break; case 't': c = 'g'; break; case 'u': c = 'f'; break; case 'v': c = 'e'; break; case 'w': c = 'd'; break; case 'x': c = 'c'; break; case 'y': c = 'b'; break; case 'z': c = 'a'; break; case '2': c = 'ñ'; break; case '1': c = ' '; break; default: c = '1'; break; } System.out.print(c); } System.out.println("\n\n\n\n"); break; } System.out.flush(); }while(opc!=3); System.out.println("Programa terminado"); } }
[ "rafra@Rafa" ]
rafra@Rafa
314c5d2c53694e4569cf80e671ba1823372765be
d7aaf1fc60b6a064b638d58b227536680df1e6b8
/demoapp/src/test/java/com/demo/demoapp/DemoappApplicationTests.java
d4520426715161a75f0c63bd4a71fd8b4107bb58
[ "MIT" ]
permissive
GitsAndGlamour/Demo-App-Java
9729421c35a668c208373228e3acc5b3eca1f89a
c01209c49019ec6108517e5c272d12b27ec56335
refs/heads/master
2020-03-24T16:58:00.854852
2018-07-30T13:03:12
2018-07-30T13:03:12
142,844,497
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
package com.demo.demoapp; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoappApplicationTests { @Test public void contextLoads() { } }
581803f336c003dc3d9344f112fa0b3987e9f0a1
6c7e279a45b37d597297f999d5ee0c5adde8a29e
/src/main/java/com/alipay/api/domain/AlipayMarketingCardOpenModel.java
9ee209a03c468a5f79aab2ff15734bc7c28e0731
[]
no_license
tomowork/alipay-sdk-java
a09fffb8a48c41561b36b903c87bdf5e881451f6
387489e4a326c27a7b9fb6d38ee0b33aa1a3568f
refs/heads/master
2021-01-18T03:55:00.944718
2017-03-22T03:52:16
2017-03-22T03:59:16
85,776,800
1
2
null
2017-03-22T03:59:18
2017-03-22T02:37:45
Java
UTF-8
Java
false
false
1,828
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 会员卡开卡接口 * * @author auto create * @since 1.0, 2016-12-22 10:41:08 */ public class AlipayMarketingCardOpenModel extends AlipayObject { private static final long serialVersionUID = 2361685987126525791L; /** * 外部卡信息(biz_card_no无需填写) */ @ApiField("card_ext_info") private MerchantCard cardExtInfo; /** * 支付宝分配的卡模板Id(卡模板创建接口返回的模板ID) */ @ApiField("card_template_id") private String cardTemplateId; /** * 发卡用户信息 */ @ApiField("card_user_info") private CardUserInfo cardUserInfo; /** * 商户会员信息 */ @ApiField("member_ext_info") private MerchantMenber memberExtInfo; /** * 外部商户流水号(商户需要确保唯一性控制,类似request_id唯一请求标识) */ @ApiField("out_serial_no") private String outSerialNo; public MerchantCard getCardExtInfo() { return this.cardExtInfo; } public void setCardExtInfo(MerchantCard cardExtInfo) { this.cardExtInfo = cardExtInfo; } public String getCardTemplateId() { return this.cardTemplateId; } public void setCardTemplateId(String cardTemplateId) { this.cardTemplateId = cardTemplateId; } public CardUserInfo getCardUserInfo() { return this.cardUserInfo; } public void setCardUserInfo(CardUserInfo cardUserInfo) { this.cardUserInfo = cardUserInfo; } public MerchantMenber getMemberExtInfo() { return this.memberExtInfo; } public void setMemberExtInfo(MerchantMenber memberExtInfo) { this.memberExtInfo = memberExtInfo; } public String getOutSerialNo() { return this.outSerialNo; } public void setOutSerialNo(String outSerialNo) { this.outSerialNo = outSerialNo; } }
b79fbd06cc0e87f48444747c49921900b7ef351d
ac4fd4943fc33dd75eb9ca5bd4700f4a08d9326a
/app/src/main/java/com/example/sampleconstratintlayout/MainActivity.java
56037dcd93c4c6f52fbc960ac872064c479904cc
[]
no_license
DwikyOktaReza/SampleFrameLayout
beca523c6d9b269f88872a4acd35d2e764dd2c39
275ac980fca312526dd608ee511bb041dfc3b952
refs/heads/master
2023-03-18T13:44:09.047623
2021-03-08T16:21:38
2021-03-08T16:21:38
345,718,040
0
0
null
null
null
null
UTF-8
Java
false
false
348
java
package com.example.sampleconstratintlayout; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
2f46fd50a444762218cb3ccb71a385f69ef96025
aafff9731c4fdc6d8256cb8b346da2225a7366e4
/BaekJoon/src/insertbox_1965/INSERTBOX_1965.java
8cab747c5516d783735a13ba13f3485d71f95c07
[]
no_license
omakasekim/algorithm_log
11b4ed50036de6979d349aaad1e44b6d0cb3d739
d8cbdf4ac8d31b6609a441ba6263071a69a530fc
refs/heads/master
2023-07-15T19:08:21.432587
2021-08-28T11:18:25
2021-08-28T11:18:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,801
java
package insertbox_1965; import java.util.*; import java.io.*; public class INSERTBOX_1965 { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter((System.out))); static int[] inputValue; static int[] maxDP; static int numberOfBoxes; static StringTokenizer splitBySpacing; static int answer; private static void createArray(int numberOfBoxes){ inputValue = new int[numberOfBoxes]; maxDP = new int[numberOfBoxes]; } public static void main(String[] args) throws IOException { getInput(); createArray(numberOfBoxes); getResult(splitBySpacing, numberOfBoxes); printResult(); } private static void getInput() throws IOException { numberOfBoxes = Integer.parseInt(reader.readLine()); splitBySpacing = new StringTokenizer(reader.readLine()); } private static void getResult(StringTokenizer splitBySpacing, int numberOfBoxes) { int INITIALIZE_VALUE = 1; //update inputValue and initialize maxDP array for (int index = 0; index < numberOfBoxes; index++) { inputValue[index] = Integer.parseInt(splitBySpacing.nextToken()); maxDP[index] = INITIALIZE_VALUE; checkBeforeDPAmount(index); } } private static void printResult() throws IOException { writer.write(String.valueOf(answer)); writer.flush(); writer.close(); } private static void checkBeforeDPAmount(int currentIndex){ for (int beforeIndex = 0; beforeIndex < currentIndex; beforeIndex++){ if (inputValue[beforeIndex] < inputValue[currentIndex]){ maxDP[currentIndex] = Math.max(maxDP[currentIndex], maxDP[beforeIndex] + 1); } } answer = Arrays.stream(maxDP).max().getAsInt(); } }
f1500183b7b90eb9fc12ffe378e3204329172ff1
0c74d37381b1b30154a10dd71d2a184b26f40155
/BackEnd/src/main/java/net/javaguides/springboot/model/transfer.java
6d69d91a540f1c148cb99f5ed1825c98e5209368
[]
no_license
mhuy25/ReactJS-SpringBoot
2f1b095df38dea2184fa82125baeeb3a4c58c3e7
8321b8c14cce5cc60b58b70bb23eec9693f327f1
refs/heads/master
2023-06-18T15:07:06.334726
2021-07-12T14:29:14
2021-07-12T14:29:14
381,744,971
0
0
null
null
null
null
UTF-8
Java
false
false
1,366
java
package net.javaguides.springboot.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "transfer") public class transfer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name ="customerid") private int customerid; @Column(name ="total") private String total; @Column(name ="time") private String time; @Column(name ="branch") private String branch; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCustomerid() { return customerid; } public void setCustomerid(int customerid) { this.customerid = customerid; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public transfer() { } public transfer(int customerid, String total, String time, String branch) { super(); this.customerid = customerid; this.total = total; this.time = time; this.branch = branch; } }
c7302b295797669e656e6081559054e4a93716f6
fd81223df7cd008fd2ade062711e87efbeb84fe6
/src/main/java/commandrmoose/master/blocks/ElectricBarBlock.java
c63c5a7b40c19e9d7ae938ce8d988544e0b95001
[]
no_license
CommandrMoose/Masters-Delight
efad00409c2ad679aad3130ed3edd6f442f4605b
b732867234ca696d034ae941d5fce70513b21583
refs/heads/master
2023-06-30T17:44:07.878464
2021-08-03T02:58:00
2021-08-03T02:58:00
295,386,914
1
4
null
2020-10-19T07:45:07
2020-09-14T10:53:08
Java
UTF-8
Java
false
false
1,455
java
package commandrmoose.master.blocks; import commandrmoose.master.damagesrc.MDamageSource; import net.minecraft.block.BlockState; import net.minecraft.block.FenceBlock; import net.minecraft.block.PaneBlock; import net.minecraft.entity.Entity; import net.minecraft.item.BlockItem; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.particles.ParticleTypes; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.DamageSource; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import java.util.Random; public class ElectricBarBlock extends PaneBlock { public ElectricBarBlock(Properties prop) { super(prop); } @Override public void onEntityCollision(BlockState state, World worldIn, BlockPos pos, Entity entityIn) { if (!worldIn.isRemote()){ if (worldIn.getGameTime() % 20 == 0) { entityIn.attackEntityFrom(MDamageSource.ELECTRICITY, 3f); } } else { Random rand = new Random(); for(int i = 0; i < 18; ++ i) { double angle = Math.toRadians(i * 60); double x = Math.sin(angle); double z = Math.cos(angle); worldIn.addParticle(ParticleTypes.SMOKE, entityIn.posX + x, entityIn.posY + rand.nextDouble(), entityIn.posZ + z, 0, 0, 0); } } } }
b452e1d69b71f4d32d4a958392aa525065ba1d3e
83e2ea309ad32f0f43d5ce8b3b82306d5d93dcba
/core/src/main/java/com/xseagullx/jetlang/runtime/jvm/JVMCompilationContext.java
3cd32c36ef91ba9ce8ccef97cfe85a14236caa12
[]
no_license
xSeagullx/jetlang
097a3852e2bf2166b60735872106f1f37b26c84a
3995e785c9bd9c5948cc09dca96affa01972fe18
refs/heads/master
2021-01-19T22:21:30.125382
2017-05-29T17:35:27
2017-05-29T19:21:41
88,799,896
1
0
null
2017-05-24T19:33:20
2017-04-19T23:27:22
Java
UTF-8
Java
false
false
9,601
java
package com.xseagullx.jetlang.runtime.jvm; import com.xseagullx.jetlang.JetLangParser; import com.xseagullx.jetlang.ParseError; import com.xseagullx.jetlang.runtime.CSTUtils; import com.xseagullx.jetlang.runtime.CompilationVisitor; import com.xseagullx.jetlang.runtime.stack.nodes.OperationType; import com.xseagullx.jetlang.utils.ThisShouldNeverHappenException; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.util.ArrayDeque; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.stream.Collectors; class JVMCompilationContext extends CompilationVisitor<Void> { static class LambdaDefinition { List<String> variables; JetLangParser.ExprContext expression; String name; } private final Map<String, Integer> localVariables = new HashMap<>(); private final Queue<LambdaDefinition> lambdas = new ArrayDeque<>(); private MethodVisitor methodVisitor; private final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); @Override public JvmProgram visit(JetLangParser.ProgramContext ctx) { classWriter.visit(52, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "Program", null, Type.getInternalName(ProgramBase.class), null); createInitMethod(classWriter); createRunMethod(ctx); while (!lambdas.isEmpty()) { LambdaDefinition lambdaDefinition = lambdas.poll(); generateLambda(lambdaDefinition); } classWriter.visitEnd(); return new JvmProgram(classWriter.toByteArray()); } @Override public Void visit(JetLangParser.BinaryOpExprContext ctx) { pushThis(); visit(ctx.expr(0)); visit(ctx.expr(1)); generateOperationCall(CSTUtils.getOperationType(ctx)); return null; } @Override public Void visit(JetLangParser.UnaryOpExpressionContext ctx) { if (ctx.PLUS() != null) // unary plus is a no-op. visit(ctx.expr()); else { pushThis(); visit(ctx.expr()); invokeBase("negate", Object.class); } return null; } @Override public Void visit(JetLangParser.NumberExprContext ctx) { JetLangParser.NumberContext numberCtx = ctx.number(); Number number = CSTUtils.getNumber(numberCtx); if (number instanceof Integer) { methodVisitor.visitIntInsn(Opcodes.SIPUSH, number.intValue()); invoke(Opcodes.INVOKESTATIC, Integer.class, "valueOf", int.class); } else if (number instanceof Double) { methodVisitor.visitLdcInsn(number.doubleValue()); invoke(Opcodes.INVOKESTATIC, Double.class, "valueOf", double.class); } else { errors.add(new ParseError(ctx.start.getLine(), ctx.start.getCharPositionInLine() + 1, ctx.start.getStartIndex(), ctx.stop.getStopIndex(), "NumberFormatException")); } return null; } @Override public Void visit(JetLangParser.IdentifierExprContext ctx) { String name = ctx.identifier().IDENTIFIER().getText(); Integer pos = localVariables.get(name); if (pos == null) throw new RuntimeException("Compilation exception. Undeclared variable."); methodVisitor.visitVarInsn(Opcodes.ALOAD, pos); return null; } @Override public Void visit(JetLangParser.RangeExprContext ctx) { pushThis(); visit(ctx.range().expr(0)); visit(ctx.range().expr(1)); invokeBase("newRange", Object.class, Object.class); return null; } @Override public Void visit(JetLangParser.MapExprContext ctx) { LambdaDefinition lambdaDefinition = createLambdaDefinition(ctx.map().expr(1), Collections.singletonList(ctx.map().identifier().IDENTIFIER())); pushThis(); visit(ctx.map().expr(0)); // Range // lambdaRef pushThis(); methodVisitor.visitInvokeDynamicInsn("apply", "(LProgram;)Ljava/util/function/Function;", new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", false), Type.getType("(Ljava/lang/Object;)Ljava/lang/Object;"), new Handle(Opcodes.H_INVOKESPECIAL, "Program", lambdaDefinition.name, "(Ljava/lang/Object;)Ljava/lang/Object;", false), Type.getType("(Ljava/lang/Object;)Ljava/lang/Object;") ); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "Program", "map", "(Ljava/lang/Object;Ljava/util/function/Function;)Ljava/lang/Object;", false); return null; } @Override public Void visit(JetLangParser.ReduceExprContext ctx) { JetLangParser.ReduceContext reduce = ctx.reduce(); LambdaDefinition lambdaDefinition = createLambdaDefinition(reduce.expr(2), reduce.IDENTIFIER()); pushThis(); visit(reduce.expr(0)); // Range visit(reduce.expr(1)); // initial value // lambdaRef pushThis(); methodVisitor.visitInvokeDynamicInsn("apply", "(LProgram;)Ljava/util/function/BiFunction;", new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", false), Type.getType("(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"), new Handle(Opcodes.H_INVOKESPECIAL, "Program", lambdaDefinition.name, "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false), Type.getType("(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;") ); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "Program", "reduce", "(Ljava/lang/Object;Ljava/lang/Object;Ljava/util/function/BiFunction;)Ljava/lang/Object;", false); return null; } @Override public Void visit(JetLangParser.DeclarationContext ctx) { String name = ctx.identifier().IDENTIFIER().getText(); visit(ctx.expr()); int pos = localVariables.size() + 1; methodVisitor.visitVarInsn(Opcodes.ASTORE, pos); localVariables.put(name, pos); return null; } @Override public Void visit(JetLangParser.OutExprContext ctx) { pushThis(); visit(ctx.expr()); invokeBase("out", Object.class); return null; } @Override public Void visit(JetLangParser.PrintExprContext ctx) { String text = CSTUtils.getString(ctx.STRING()); pushThis(); methodVisitor.visitLdcInsn(text); invokeBase("out", Object.class); return null; } // Utility methods private void generateLambda(LambdaDefinition lambdaDefinition) { String args = String.join("", Collections.nCopies(lambdaDefinition.variables.size(),"Ljava/lang/Object;")); MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PRIVATE, lambdaDefinition.name, "(" + args + ")Ljava/lang/Object;", null, null); localVariables.clear(); int i = 1; for (String variable : lambdaDefinition.variables) { localVariables.put(variable, i); i++; } methodVisitor = mv; mv.visitCode(); visit(lambdaDefinition.expression); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private void createRunMethod(JetLangParser.ProgramContext programCtx) { MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); methodVisitor = mv; for (JetLangParser.StmtContext stmtContext : programCtx.stmt()) visit(stmtContext); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } private void createInitMethod(ClassWriter classWriter) { MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ProgramBase.class), "<init>", "()V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } private void pushThis() { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); } private void generateOperationCall(OperationType operationType) { String name = operationType.name().toLowerCase(); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "Program", name, "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", false); } private void invoke(int opcode, Class<?> owner, String method, Class<?> ... params) { try { String descriptor = Type.getMethodDescriptor(owner.getDeclaredMethod(method, params)); methodVisitor.visitMethodInsn(opcode, Type.getInternalName(owner), method, descriptor, false); } catch (NoSuchMethodException e) { throw new ThisShouldNeverHappenException("Wrong method call from jetlang to bytecode compiler."); } } private void invokeBase(String method, Class<?> ... params) { Class<ProgramBase> owner = ProgramBase.class; try { String descriptor = Type.getMethodDescriptor(owner.getDeclaredMethod(method, params)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "Program", method, descriptor, false); } catch (NoSuchMethodException e) { throw new ThisShouldNeverHappenException("Wrong method call from jetlang to bytecode compiler."); } } private LambdaDefinition createLambdaDefinition(JetLangParser.ExprContext ctx, List<TerminalNode> arguments) { LambdaDefinition definition = new LambdaDefinition(); definition.expression = ctx; definition.variables = arguments.stream().map(ParseTree::getText).collect(Collectors.toList()); Token firstToken = arguments.get(0).getSymbol(); definition.name = "lambda_" + firstToken.getLine() + "_" + (firstToken.getCharPositionInLine() + 1); lambdas.add(definition); return definition; } }
87b55f63c1d7d187b9a47d3fa06770572ec53b76
dcec7147a9a0b5f847e747d8a015fdbfd79deebc
/app/src/test/java/com/example/william/game/ExampleUnitTest.java
d1916e0300c6ecccdeda54a61742eb5f944cc6c6
[]
no_license
wpan2002/Old_Android_Game
70c0d83c16f88543b14a397514108412cd347209
571a9db89ed6cd7bda927fd3f608a6ede3abfa2f
refs/heads/master
2023-01-04T13:17:21.486212
2020-11-03T19:30:36
2020-11-03T19:30:36
309,786,404
0
0
null
null
null
null
UTF-8
Java
false
false
402
java
package com.example.william.game; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
024eb5af1161fffd93881b7cac87b1de2004e5fd
25b4d84d61b975c636c3e6520a55ba6b597eebe6
/hw14-0036505483/src/main/java/hr/fer/zemris/java/Inicijalizacija.java
5d4fbf550b7a091d8b7ff847e4d64d0385def192
[]
no_license
JurenIvan/Java-courses
fda19f412e935f3a4fc1ab422ee5a49ca41f23f5
c5de473f9f5da94bc079cdc49a232fd5d5a42a3d
refs/heads/master
2022-11-28T13:27:31.266625
2019-09-19T22:25:45
2019-09-19T22:25:45
184,144,843
1
0
null
2022-11-24T09:35:39
2019-04-29T21:11:33
Java
UTF-8
Java
false
false
10,438
java
package hr.fer.zemris.java; import java.beans.PropertyVetoException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; import hr.fer.zemris.java.model.PollModel; import hr.fer.zemris.java.model.PollOptionModel; /** * Class that is a implementation of {@link ServletContextListener}. Its * function is to initialize databases tables to default values defined in * project. * * @author juren * */ @WebListener public class Inicijalizacija implements ServletContextListener { /** String containing sql request for inserting into polloptions table */ private static final String POLLOPTIONS_INSERT_SQL = "INSERT INTO PollOptions (optionTitle,optionLink,pollID,votesCount) values(?,?,?,?)"; /** String containing sql request for inserting into polls table */ private static final String POLLS_INSERTION_SQL = "INSERT INTO Polls (title,message) values(?,?)"; /** constant used for storing sql command that creates table "pooloptions" */ private static final String CREATE_TABLE_POOL_OPTIONS = "CREATE TABLE PollOptions (id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, optionTitle VARCHAR(100) NOT NULL, optionLink VARCHAR(150) NOT NULL, pollID BIGINT, votesCount BIGINT, FOREIGN KEY (pollID) REFERENCES Polls(id))"; /** constant used for storing sql command that creates table "Polls" */ private static final String CREATE_TABLE_POOLS = "CREATE TABLE Polls (id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, title VARCHAR(150) NOT NULL, message CLOB(2048) NOT NULL)"; /** * variable that stores default path to txt file used for initialization of * table */ private String DEFAULT_POOLOPTIONS_DEFINITION_PATH; /** * variable that stores default path to txt file used for initialization of * table */ private String DEFAULT_POOLS_DEFINITION_PATH; @Override public void contextInitialized(ServletContextEvent sce) { DEFAULT_POOLOPTIONS_DEFINITION_PATH = sce.getServletContext().getRealPath("/WEB-INF/pollOptionsDefinition.txt"); DEFAULT_POOLS_DEFINITION_PATH = sce.getServletContext().getRealPath("/WEB-INF/polls.txt"); String connectionURL; ComboPooledDataSource cpds = new ComboPooledDataSource(); try { cpds.setDriverClass("org.apache.derby.jdbc.ClientDriver"); connectionURL = buildConnectionURL(sce); cpds.setJdbcUrl(connectionURL); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (PropertyVetoException e1) { throw new RuntimeException("Error while pool initialization.", e1); } initializeTables(cpds); sce.getServletContext().setAttribute("hr.fer.zemris.dbpool", cpds); } /** * Method used to check and initialize tables of database if no tables are found * or found tables are empty * * @param cpds {@link ComboPooledDataSource} used for data transfer */ private void initializeTables(ComboPooledDataSource cpds) { try (Connection con = cpds.getConnection()) { if (!tableExists(con, "Polls")) { con.prepareStatement(CREATE_TABLE_POOLS).execute(); } if (!tableExists(con, "PollOptions")) { con.prepareStatement(CREATE_TABLE_POOL_OPTIONS).execute(); } if (isTableEmpty(con, "Polls") || isTableEmpty(con, "PollOptions")) { fillDefaultValues(con); } } catch (SQLException e) { } } /** * Method that loads data from files, and initializes tables with that data. * * @param con used for communication with database * @throws SQLException if database can not be initialized */ private void fillDefaultValues(Connection con) throws SQLException { List<PollModel> polls; List<PollOptionModel> pollOptions; try { polls = loadPolls(DEFAULT_POOLS_DEFINITION_PATH); pollOptions = loadPollOptionModels(DEFAULT_POOLOPTIONS_DEFINITION_PATH); } catch (NumberFormatException | IOException e) { e.printStackTrace(); throw new SQLException("Cannot load default values."); } PreparedStatement psPoll = con.prepareStatement(POLLS_INSERTION_SQL, Statement.RETURN_GENERATED_KEYS); PreparedStatement psPollOption = con.prepareStatement(POLLOPTIONS_INSERT_SQL); for (var poll : polls) { psPoll.setString(1, poll.getTitle()); psPoll.setString(2, poll.getMessage()); psPoll.executeUpdate(); ResultSet rs = psPoll.getGeneratedKeys(); rs.next(); long generatedKey = rs.getLong(1); for (var pollOption : pollOptions.stream().filter(t -> t.getPollID() == poll.getId()) .collect(Collectors.toList())) { psPollOption.setString(1, pollOption.getOptionTitle()); psPollOption.setString(2, pollOption.getOptionLink()); psPollOption.setLong(3, generatedKey); psPollOption.setLong(4, pollOption.getVoteCount()); psPollOption.executeUpdate(); } } } @Override public void contextDestroyed(ServletContextEvent sce) { ComboPooledDataSource cpds = (ComboPooledDataSource) sce.getServletContext() .getAttribute("hr.fer.zemris.dbpool"); if (cpds != null) { try { DataSources.destroy(cpds); } catch (SQLException e) { e.printStackTrace(); } } } /** * Method that parses dbsettings.property file and creates a string needed for * conencting to database defined in dbsettings.property file. * * @param sce used to get path do data * @return string needed for connecting to database defined in * dbsettings.property file */ private String buildConnectionURL(ServletContextEvent sce) { String results = sce.getServletContext().getRealPath("/WEB-INF/dbsettings.properties"); Properties dataBaseProperties = new Properties(); try { dataBaseProperties.load(Files.newInputStream(Paths.get(results))); } catch (IOException e) { throw new IllegalArgumentException("dbsettings.properties file not found."); } StringBuilder sb = new StringBuilder(256); sb.append("jdbc:derby://"); sb.append(getDataAndCheck(dataBaseProperties, "host")); sb.append(":"); sb.append(getDataAndCheck(dataBaseProperties, "port")); sb.append("/"); sb.append(getDataAndCheck(dataBaseProperties, "name")); sb.append(";user="); sb.append(getDataAndCheck(dataBaseProperties, "user")); sb.append(";password="); sb.append(getDataAndCheck(dataBaseProperties, "password")); return sb.toString(); } /** * Method that parses line from property in such a way that it is compared to * other parameter and decided upon that if the line in dbsettings.property file * is valid or no. * * @param dataBaseProperties used for data retrieval * @param atribute name that is a key to mappings in provided * Properties * @return value of mapped object * @throws IllegalArgumentException if no such string is found in * pdbsettings.property. */ private static String getDataAndCheck(Properties dataBaseProperties, String atribute) { if (dataBaseProperties.getProperty(atribute) == null) throw new IllegalArgumentException(atribute + " is missing in dbsettings.properties ."); return dataBaseProperties.getProperty(atribute); } /** * Method that checks whether table with name is equal to one provided as * parameter is existent * * @param con used for data communication to base * @param name of table * @return flag describing statement above */ private static boolean tableExists(Connection con, String name) { try { DatabaseMetaData meta = con.getMetaData(); return meta.getTables(null, null, name.toUpperCase(), null).next(); } catch (SQLException e) { // e.printStackTrace(); return false; } } /** * Method that checks whether table with name is equal to one provided as * parameter is not empty * * @param con used for data comunication to base * @param name of table * @return flag describing statement above */ private static boolean isTableEmpty(Connection con, String tableName) { try { return !con.prepareStatement("SELECT * FROM " + tableName).executeQuery().next(); } catch (SQLException e) { return false; } } /** * Method that reads all lines from file found on given path and parses data * into {@link List} of {@link PollOptionModel}. method expects that columns are * divided by tabs and each row represents a new entry * * @param pathToFile path where file with data is looked for * @return list of {@link PollOptionModel} * @throws NumberFormatException if numbers from data can not be read * @throws IOException if file can not be read */ public static List<PollOptionModel> loadPollOptionModels(String pathToFile) throws NumberFormatException, IOException { Path path = Paths.get(pathToFile); List<String> lines = Files.readAllLines(path); List<PollOptionModel> results = new ArrayList<>(lines.size() + 1); for (var line : Files.readAllLines(path)) { String[] splitted = line.split("\\t"); results.add(new PollOptionModel(Long.parseLong(splitted[0]), splitted[1], splitted[2], Long.parseLong(splitted[3]), 0)); } return results; } /** * Method that reads all lines from file found on given path and parses data * into {@link List} of {@link PollModel}. Method expects that columns are * divided by tabs and each row represents a new entry * * @param pathToFile path where file with data is looked for * @return list of {@link PollModel} * @throws NumberFormatException if numbers from data can not be read * @throws IOException if file can not be read */ public static List<PollModel> loadPolls(String pathToFile) throws NumberFormatException, IOException { Path path = Paths.get(pathToFile); List<String> lines = Files.readAllLines(path); List<PollModel> results = new ArrayList<>(lines.size() + 1); for (var line : Files.readAllLines(path)) { String[] splitted = line.split("\\t"); results.add(new PollModel(Long.parseLong(splitted[0]), splitted[1], splitted[2])); } return results; } }
1aba5068b11fd1bddd5a48eeab4a54b71d364e23
36f5e4b8fe815ad16eb070a7d2557c921be77129
/Algorithms/src/algoExpert/PermutationsAlter.java
2dfa662358b78dccf13e7fc62173e5dba7afb0e9
[]
no_license
satyamsanghi1/DataStructures
97c3fcb4f95095db25ded447e1c1e70bd5187f66
65733d70c0f9e206243b60783b71f708231a9399
refs/heads/master
2023-07-06T00:38:53.091243
2021-08-11T10:31:10
2021-08-11T10:31:10
261,869,941
0
0
null
null
null
null
UTF-8
Java
false
false
1,126
java
package algoExpert; import java.util.ArrayList; import java.util.List; public class PermutationsAlter { public static void main(String[] args) { int nums[]= {1,2,3}; List<List<Integer>>perms=new ArrayList<>(); List<Integer>perm=new ArrayList<Integer>(); //using a boolean array to keep check which element is used boolean used[]=new boolean[nums.length]; helper(nums, used, perm, perms); System.out.println(perms); } public static void helper(int nums[],boolean[] used,List<Integer>perm,List<List<Integer>>perms) { if(perm.size()==nums.length) { perms.add(new ArrayList<Integer>(perm)); } else { for(int i=0;i<nums.length;i++) { // if current element is used than we simply skip it if(used[i]) continue; //if not used then add it to current perm and mark it as true perm.add(nums[i]); used[i]=true; helper(nums, used, perm, perms); // when coming back mark the element as false and remove the element // to the previous state , so that we can form new permutations from that state perm.remove(perm.size()-1); used[i]=false; } } } }
2cfc90c406cc64a7ca82814bca8d8bf96d39a8b5
561620811b2c07ac21d9043ef9896d1f44663446
/MyLinkedList.java
a7dac02e99adceea9a6583f2db8793e6d5876833
[]
no_license
cz1002/JavaDataStructure
c393f81dce6ecb2de9a0aecd108a2f0f2f89efe0
4762d3f88e785a6eb8e366f9a1c70d80773ca91a
refs/heads/master
2021-08-24T13:43:36.244175
2017-11-21T08:40:31
2017-11-21T08:40:31
111,522,218
0
0
null
null
null
null
UTF-8
Java
false
false
3,409
java
package DataStructure; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; /** * Created by Administrator on 2017/10/25 0025. */ public class MyLinkedList<T> implements Iterable<T> { private int theSize; private int modCount = 0; private Node<T> beginMarker; private Node<T> endMarker; private static class Node<T> { public T data; public Node<T> prev; public Node<T> next; public Node(T d, Node<T> p, Node<T> n) { data = d; prev = p; next = n; } } public MyLinkedList() { doClear(); } public void clear() { doClear(); } private void doClear(){ beginMarker = new Node<T>(null,null,null); endMarker = new Node<T>(null,beginMarker,null); beginMarker.next = endMarker; theSize = 0; modCount++; } public int size() { return theSize; } public boolean isEmpty() { return size() == 0; } public boolean add(T x) { add(size(), x); return true; } public void add(int idx, T x) { addBefore(getNode(idx, 0, size()), x); } public T get(int idx) { return getNode(idx).data; } public T set(int idx, T newVal) { Node<T> p = getNode(idx); T oldVal = p.data; p.data = newVal; return oldVal; } public T remove(int idx) { return remove(getNode(idx)); } private void addBefore(Node<T> p, T x) { Node<T> newNode = new Node(x,p.prev,p); newNode.prev.next = newNode; p.prev = newNode; theSize++; modCount++; } private T remove(Node<T> p) { p.next.prev = p.prev; p.prev.next = p.next; theSize--; modCount++; return p.data; } private Node<T> getNode(int idx) { return getNode(idx,0,size()-1); } private Node<T> getNode(int idx, int lower, int upper) { Node<T> p; if(idx < lower || idx > upper)throw new IndexOutOfBoundsException(); if(idx < size()/2){ p = beginMarker.next; for(int i = 0;i<idx;i++) p = p.next; }else{ p = endMarker; for(int i = size();i>idx;i--)p = p.prev; } return p; } public Iterator<T> iterator() { return new LinkedListIterator(); } private class LinkedListIterator implements Iterator<T> { private Node<T> current = beginMarker.next; private int expectedModCount = modCount; private boolean okToRemove = false; public boolean hasNext(){ return current != endMarker; } public T next(){ if(modCount != expectedModCount)throw new ConcurrentModificationException(); if(!hasNext())throw new NoSuchElementException(); T nextItem = current.data; current = current.next; okToRemove = true; return nextItem; } public void remove(){ if(modCount != expectedModCount)throw new ConcurrentModificationException(); if(!hasNext())throw new NoSuchElementException(); MyLinkedList.this.remove(current.prev); expectedModCount++; okToRemove = false; } } }
06986fe92c31b33264f4a28ae227e17157953858
a2b699456c94eed6cc54bf8366d1fab91781aeca
/pangu/pangu-taishang/pangu-taishang-api/src/main/java/com/colourfulchina/pangu/taishang/api/entity/OutlineRefundInfo.java
d54e52a3fabc5c7c87741743ed1c8f60ff1cb85b
[]
no_license
elephant5/old-code
8a35aa17163e87f506c6f12da032b1978b0c4ec3
bfb27297d5fcb6aaea8eac5a4032eba7d01cc7ee
refs/heads/master
2023-01-24T12:25:53.549609
2020-12-04T01:50:15
2020-12-04T01:50:15
318,364,156
1
2
null
null
null
null
UTF-8
Java
false
false
2,687
java
package com.colourfulchina.pangu.taishang.api.entity; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data @TableName(value = "outline_refund_info") public class OutlineRefundInfo extends Model<OutlineRefundInfo> { private static final long serialVersionUID = -8604514819657376254L; @ApiModelProperty("订单号") @TableId(value = "order_no", type = IdType.INPUT) private String orderNo; @ApiModelProperty("商品名") @TableField(value = "goods_name") private String goodsName; @ApiModelProperty("产品名") @TableField(value = "product_name") private String productName; @ApiModelProperty("商品id") @TableField(value = "goods_id") private Integer goodsId; @ApiModelProperty("产品组id") @TableField(value = "product_group_id") private Integer productGroupId; @ApiModelProperty("商户名称") @TableField(value = "merchant_name") private String merchantName; @ApiModelProperty("酒店名称") @TableField(value = "hotel_name") private String hotelName; @ApiModelProperty("手机号") @TableField(value = "phone_reciever") private String phoneReciever; @ApiModelProperty("收款方") @TableField(value = "refund_reciever") private String refundReciever; @ApiModelProperty("激活码") @TableField(value = "act_code") private String actCode; @ApiModelProperty("订单时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @TableField(value = "order_time") private Date orderTime; @ApiModelProperty("订单来源") @TableField(value = "order_source") private String orderSource; @ApiModelProperty("退款金额") @TableField(value = "refund_price") private Double refundPrice; @ApiModelProperty("退款状态, 0:未退款,1:已退款") @TableField(value = "refund_status") private Boolean refundStatus; @ApiModelProperty("退款时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @TableField(value = "refund_time") private Date refundTime; @ApiModelProperty("退款渠道") @TableField(value = "refund_channel") private String refundChannel; @Override protected Serializable pkVal() { return this.orderNo; } }
d28f6622596feefab9b410d6fdae74e9a6c0eb52
2b631cb14b185044e4201c9cc8be8219c5ab7556
/opt/net/wifi/tests/wifitests/src/com/android/server/wifi/hotspot2/OsuNetworkConnectionTest.java
acfb4b47e7e4e8209a3eee725a41c0e20492ac55
[]
no_license
yuchuangu85/Android-framework-code
59837ba3e41ebdda7de74ce82e1af2d0367610ce
fb27715328b4b0064b0f4e7b499b8c0f2e728d61
refs/heads/master
2020-09-03T09:00:20.642461
2019-11-04T16:21:25
2019-11-04T16:21:25
219,429,555
2
3
null
null
null
null
UTF-8
Java
false
false
14,161
java
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.wifi.hotspot2; import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED; import static org.junit.Assert.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.BroadcastReceiver; import android.content.Context; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.LinkAddress; import android.net.LinkProperties; import android.net.Network; import android.net.NetworkRequest; import android.net.NetworkUtils; import android.net.RouteInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiSsid; import android.os.Handler; import android.os.test.TestLooper; import androidx.test.filters.SmallTest; import com.android.server.wifi.TestUtil; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.net.InetAddress; /** * Unit tests for {@link OsuNetworkConnection}. */ @SmallTest public class OsuNetworkConnectionTest { private static final String TAG = "OsuNetworkConnectionTest"; private static final int ENABLE_LOGGING = 1; private static final int DISABLE_LOGGING = 0; private static final int TEST_NETWORK_ID = 6; private static final String TEST_NAI = null; private static final String TEST_NAI_OSEN = "access.test.com"; private static final String TEST_PROVIDER_NAME = "testService"; private static final WifiSsid TEST_SSID = WifiSsid.createFromAsciiEncoded("Test SSID"); private OsuNetworkConnection mNetworkConnection; private TestLooper mLooper; private Handler mHandler; @Mock Context mContext; @Mock WifiManager mWifiManager; @Mock ConnectivityManager mConnectivityManager; @Mock OsuNetworkConnection.Callbacks mNetworkCallbacks; @Mock WifiInfo mWifiInfo; @Mock Network mCurrentNetwork; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); doReturn(mWifiManager).when(mContext) .getSystemService(eq(Context.WIFI_SERVICE)); doReturn(mConnectivityManager).when(mContext) .getSystemService(eq(Context.CONNECTIVITY_SERVICE)); when(mWifiManager.isWifiEnabled()).thenReturn(true); when(mWifiManager.enableNetwork(TEST_NETWORK_ID, true)).thenReturn(true); when(mWifiManager.addNetwork(any(WifiConfiguration.class))).thenReturn(TEST_NETWORK_ID); when(mWifiManager.getConnectionInfo()).thenReturn(mWifiInfo); when(mWifiInfo.getNetworkId()).thenReturn(TEST_NETWORK_ID); mLooper = new TestLooper(); mHandler = new Handler(mLooper.getLooper()); mNetworkConnection = new OsuNetworkConnection(mContext); mNetworkConnection.enableVerboseLogging(ENABLE_LOGGING); } private LinkProperties createProvisionedLinkProperties() { InetAddress addrV4 = NetworkUtils.numericToInetAddress("75.208.6.1"); InetAddress dns1 = NetworkUtils.numericToInetAddress("75.208.7.1"); LinkAddress linkAddrV4 = new LinkAddress(addrV4, 32); InetAddress gateway1 = NetworkUtils.numericToInetAddress("75.208.8.1"); LinkProperties lp4 = new LinkProperties(); lp4.addLinkAddress(linkAddrV4); lp4.addDnsServer(dns1); lp4.addRoute(new RouteInfo(gateway1)); return lp4; } /** * Verify that the class registers for receiving the necessary broadcast intents upon init. * Verify that the initialization only occurs once even if init() is called multiple times. */ @Test public void verifyBroadcastIntentRegistration() { mNetworkConnection.init(mHandler); ArgumentCaptor<IntentFilter> intentFilterCaptor = ArgumentCaptor.forClass(IntentFilter.class); verify(mContext).registerReceiver(any(BroadcastReceiver.class), intentFilterCaptor.capture(), any(), eq(mHandler)); verify(mWifiManager).isWifiEnabled(); IntentFilter intentFilter = intentFilterCaptor.getValue(); assertEquals(intentFilter.countActions(), 1); } /** * Verifies that onWifiEnabled() callback is invoked when the relevant intent is * received and the caller is subscribed to receive the callback. */ @Test public void verifyWifiStateCallbacks() { when(mWifiManager.isWifiEnabled()).thenReturn(false); mNetworkConnection.init(mHandler); ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor = ArgumentCaptor.forClass(BroadcastReceiver.class); verify(mContext).registerReceiver(broadcastReceiverCaptor.capture(), any(IntentFilter.class), any(), eq(mHandler)); BroadcastReceiver broadcastReceiver = broadcastReceiverCaptor.getValue(); mLooper.dispatchAll(); mNetworkConnection.setEventCallback(mNetworkCallbacks); TestUtil.sendWifiStateChanged(broadcastReceiver, mContext, WifiManager.WIFI_STATE_ENABLED); TestUtil.sendWifiStateChanged(broadcastReceiver, mContext, WifiManager.WIFI_STATE_DISABLED); mNetworkConnection.setEventCallback(null); TestUtil.sendWifiStateChanged(broadcastReceiver, mContext, WifiManager.WIFI_STATE_ENABLED); TestUtil.sendWifiStateChanged(broadcastReceiver, mContext, WifiManager.WIFI_STATE_DISABLED); verify(mNetworkCallbacks, times(1)).onWifiEnabled(); verify(mNetworkCallbacks, times(1)).onWifiDisabled(); } /** * Verifies that connect() API returns false when Wifi is not enabled */ @Test public void verifyNetworkConnectionWhenWifiIsDisabled() { when(mWifiManager.isWifiEnabled()).thenReturn(false); mNetworkConnection.init(mHandler); assertEquals(false, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); } /** * Verifies that connect() API returns false when OSU AP is a part of an OSEN */ @Test public void verifyOSENUnsupported() { mNetworkConnection.init(mHandler); assertEquals(false, mNetworkConnection.connect(TEST_SSID, TEST_NAI_OSEN, TEST_PROVIDER_NAME)); } /** * Verifies that connect() API returns false when WifiManager's addNetwork() * returns an invalid network ID */ @Test public void verifyNetworkConnectionWhenAddNetworkFails() { when(mWifiManager.addNetwork(any(WifiConfiguration.class))).thenReturn(-1); mNetworkConnection.init(mHandler); assertEquals(false, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); verify(mWifiManager, never()).removeNetwork(TEST_NETWORK_ID); } /** * Verifies that connect() API returns false when WifiManager's enableNetwork() * fails for the given network ID corresponding to the OSU AP */ @Test public void verifyNetworkConnectionWhenEnableNetworkFails() { when(mWifiManager.enableNetwork(TEST_NETWORK_ID, true)).thenReturn(false); mNetworkConnection.init(mHandler); assertEquals(false, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); verify(mWifiManager).removeNetwork(TEST_NETWORK_ID); } /** * Verifies that network state callbacks are invoked when network callbacks * are received and when WifiManager has successfully requested connection to the OSU AP. * Ensure IP connectivity is available before invoking onConnected callback. */ @Test public void verifyNetworkCallbackInvokedWhenConnected() { mNetworkConnection.init(mHandler); mNetworkConnection.setEventCallback(mNetworkCallbacks); assertEquals(true, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); ArgumentCaptor<ConnectivityManager.NetworkCallback> networkCallbackCaptor = ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class); verify(mConnectivityManager).requestNetwork(any(NetworkRequest.class), networkCallbackCaptor.capture(), any(Handler.class), anyInt()); ConnectivityManager.NetworkCallback callback = networkCallbackCaptor.getValue(); callback.onAvailable(mCurrentNetwork); callback.onLinkPropertiesChanged(mCurrentNetwork, createProvisionedLinkProperties()); verify(mNetworkCallbacks).onConnected(mCurrentNetwork); callback.onLost(mCurrentNetwork); verify(mNetworkCallbacks).onDisconnected(); mNetworkConnection.disconnectIfNeeded(); verify(mConnectivityManager).unregisterNetworkCallback(any(ConnectivityManager .NetworkCallback.class)); verify(mWifiManager).removeNetwork(TEST_NETWORK_ID); } /** * Verifies that onConnected callback are never invoked when onLinkPropertiesChanged is invoked * without onAvailable of NetworkCallback. */ @Test public void verifyNetworkCallbackWithoutOnAvailable() { mNetworkConnection.init(mHandler); mNetworkConnection.setEventCallback(mNetworkCallbacks); assertEquals(true, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); ArgumentCaptor<ConnectivityManager.NetworkCallback> networkCallbackCaptor = ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class); verify(mConnectivityManager).requestNetwork(any(NetworkRequest.class), networkCallbackCaptor.capture(), any(Handler.class), anyInt()); ConnectivityManager.NetworkCallback callback = networkCallbackCaptor.getValue(); callback.onLinkPropertiesChanged(mCurrentNetwork, createProvisionedLinkProperties()); verify(mNetworkCallbacks, never()).onConnected(mCurrentNetwork); } /** * Verifies that network state callbacks are invoked when the network callbacks * are received and when WifiManager has successfully requested connection to the OSU AP. * If IP connectivity is not provisioned, do not invoke onConnected callback. */ @Test public void verifyNetworkConnectionTimeout() { mNetworkConnection.init(mHandler); mNetworkConnection.setEventCallback(mNetworkCallbacks); assertEquals(true, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); ArgumentCaptor<ConnectivityManager.NetworkCallback> networkCallbackCaptor = ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class); verify(mConnectivityManager).requestNetwork(any(NetworkRequest.class), networkCallbackCaptor.capture(), any(Handler.class), anyInt()); ConnectivityManager.NetworkCallback callback = networkCallbackCaptor.getValue(); callback.onLinkPropertiesChanged(mCurrentNetwork, new LinkProperties()); verify(mNetworkCallbacks, never()).onConnected(mCurrentNetwork); callback.onUnavailable(); verify(mNetworkCallbacks).onTimeOut(); mNetworkConnection.disconnectIfNeeded(); verify(mConnectivityManager).unregisterNetworkCallback(any(ConnectivityManager .NetworkCallback.class)); verify(mWifiManager).removeNetwork(TEST_NETWORK_ID); } /** * Verifies that WifiManager's removeNetwork() is called when disconnectIfNeeded() is called * on the OSU AP's network ID. */ @Test public void verifyNetworkDisconnect() { mNetworkConnection.init(mHandler); assertEquals(true, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); mNetworkConnection.disconnectIfNeeded(); verify(mConnectivityManager).unregisterNetworkCallback(any(ConnectivityManager .NetworkCallback.class)); verify(mWifiManager).removeNetwork(TEST_NETWORK_ID); } /** * Verifies that {@link WifiConfiguration} has been created properly for OSU network. * It is supposed to create a network as ephemeral network and suppress no internet access * notification. */ @Test public void verifyWifiConfigurationForOsuNetwork() { mNetworkConnection.init(mHandler); assertEquals(true, mNetworkConnection.connect(TEST_SSID, TEST_NAI, TEST_PROVIDER_NAME)); ArgumentCaptor<WifiConfiguration> wifiConfigurationCaptor = ArgumentCaptor.forClass( WifiConfiguration.class); verify(mWifiManager, times(1)).addNetwork(wifiConfigurationCaptor.capture()); WifiConfiguration wifiConfiguration = wifiConfigurationCaptor.getValue(); assertTrue(wifiConfiguration.isNoInternetAccessExpected()); assertTrue(wifiConfiguration.isEphemeral()); assertTrue(wifiConfiguration.osu); ArgumentCaptor<NetworkRequest> networkRequestCaptor = ArgumentCaptor.forClass( NetworkRequest.class); verify(mConnectivityManager, times(1)).requestNetwork(networkRequestCaptor.capture(), any(ConnectivityManager.NetworkCallback.class), any(Handler.class), anyInt()); assertFalse(networkRequestCaptor.getValue().hasCapability(NET_CAPABILITY_TRUSTED)); } }
aa745d81b62d3c02c9d9edf973a33d303d97983f
90f8a0875166ae79ffe81ce3f15c0ab143378117
/app/src/main/java/android/widget/TextView.java
08f280fe61dfaf900fab4891609e45bf7a9d62e1
[]
no_license
hoyouly/FuckingLollipop
71434287c2ac54b58f6b8a37995a4e91604162dd
004a0ca96baec0eccb6dda78e63cb6995e198987
refs/heads/master
2021-05-11T01:41:24.615978
2019-10-17T14:04:08
2019-10-17T14:04:08
118,334,376
0
0
null
null
null
null
UTF-8
Java
false
false
293,421
java
/* * Copyright (C) 2006 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 android.widget; import android.R; import android.annotation.NonNull; import android.annotation.Nullable; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.UndoManager; import android.content.res.ColorStateList; import android.content.res.CompatibilityInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Canvas; import android.graphics.Insets; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.inputmethodservice.ExtractEditText; import android.os.AsyncTask; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.os.UserHandle; import android.provider.Settings; import android.text.BoringLayout; import android.text.DynamicLayout; import android.text.Editable; import android.text.GetChars; import android.text.GraphicsOperations; import android.text.InputFilter; import android.text.InputType; import android.text.Layout; import android.text.ParcelableSpan; import android.text.Selection; import android.text.SpanWatcher; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.SpannedString; import android.text.StaticLayout; import android.text.TextDirectionHeuristic; import android.text.TextDirectionHeuristics; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.AllCapsTransformationMethod; import android.text.method.ArrowKeyMovementMethod; import android.text.method.DateKeyListener; import android.text.method.DateTimeKeyListener; import android.text.method.DialerKeyListener; import android.text.method.DigitsKeyListener; import android.text.method.KeyListener; import android.text.method.LinkMovementMethod; import android.text.method.MetaKeyKeyListener; import android.text.method.MovementMethod; import android.text.method.PasswordTransformationMethod; import android.text.method.SingleLineTransformationMethod; import android.text.method.TextKeyListener; import android.text.method.TimeKeyListener; import android.text.method.TransformationMethod; import android.text.method.TransformationMethod2; import android.text.method.WordIterator; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.ParagraphStyle; import android.text.style.SpellCheckSpan; import android.text.style.SuggestionSpan; import android.text.style.URLSpan; import android.text.style.UpdateAppearance; import android.text.util.Linkify; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.util.TypedValue; import android.view.AccessibilityIterators.TextSegmentIterator; import android.view.ActionMode; import android.view.Choreographer; import android.view.DragEvent; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewDebug; import android.view.ViewGroup.LayoutParams; import android.view.ViewRootImpl; import android.view.ViewTreeObserver; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.AnimationUtils; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.view.textservice.SpellCheckerSubtype; import android.view.textservice.TextServicesManager; import android.widget.RemoteViews.RemoteView; import com.android.internal.util.FastMath; import com.android.internal.widget.EditableInputConnection; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Locale; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; /** * Displays text to the user and optionally allows them to edit it. A TextView * is a complete text editor, however the basic class is configured to not * allow editing; see {@link EditText} for a subclass that configures the text * view for editing. * <p> * <p> * To allow users to copy some or all of the TextView's value and paste it somewhere else, set the * XML attribute {@link R.styleable#TextView_textIsSelectable * android:textIsSelectable} to "true" or call * {@link #setTextIsSelectable setTextIsSelectable(true)}. The {@code textIsSelectable} flag * allows users to make selection gestures in the TextView, which in turn triggers the system's * built-in copy/paste controls. * <p> * <b>XML attributes</b> * <p> * See {@link R.styleable#TextView TextView Attributes}, * {@link R.styleable#View View Attributes} * * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_bufferType * @attr ref android.R.styleable#TextView_hint * @attr ref android.R.styleable#TextView_textColor * @attr ref android.R.styleable#TextView_textColorHighlight * @attr ref android.R.styleable#TextView_textColorHint * @attr ref android.R.styleable#TextView_textAppearance * @attr ref android.R.styleable#TextView_textColorLink * @attr ref android.R.styleable#TextView_textSize * @attr ref android.R.styleable#TextView_textScaleX * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle * @attr ref android.R.styleable#TextView_cursorVisible * @attr ref android.R.styleable#TextView_maxLines * @attr ref android.R.styleable#TextView_maxHeight * @attr ref android.R.styleable#TextView_lines * @attr ref android.R.styleable#TextView_height * @attr ref android.R.styleable#TextView_minLines * @attr ref android.R.styleable#TextView_minHeight * @attr ref android.R.styleable#TextView_maxEms * @attr ref android.R.styleable#TextView_maxWidth * @attr ref android.R.styleable#TextView_ems * @attr ref android.R.styleable#TextView_width * @attr ref android.R.styleable#TextView_minEms * @attr ref android.R.styleable#TextView_minWidth * @attr ref android.R.styleable#TextView_gravity * @attr ref android.R.styleable#TextView_scrollHorizontally * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine * @attr ref android.R.styleable#TextView_selectAllOnFocus * @attr ref android.R.styleable#TextView_includeFontPadding * @attr ref android.R.styleable#TextView_maxLength * @attr ref android.R.styleable#TextView_shadowColor * @attr ref android.R.styleable#TextView_shadowDx * @attr ref android.R.styleable#TextView_shadowDy * @attr ref android.R.styleable#TextView_shadowRadius * @attr ref android.R.styleable#TextView_autoLink * @attr ref android.R.styleable#TextView_linksClickable * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText * @attr ref android.R.styleable#TextView_editable * @attr ref android.R.styleable#TextView_freezesText * @attr ref android.R.styleable#TextView_ellipsize * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableBottom * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawablePadding * @attr ref android.R.styleable#TextView_lineSpacingExtra * @attr ref android.R.styleable#TextView_lineSpacingMultiplier * @attr ref android.R.styleable#TextView_marqueeRepeatLimit * @attr ref android.R.styleable#TextView_inputType * @attr ref android.R.styleable#TextView_imeOptions * @attr ref android.R.styleable#TextView_privateImeOptions * @attr ref android.R.styleable#TextView_imeActionLabel * @attr ref android.R.styleable#TextView_imeActionId * @attr ref android.R.styleable#TextView_editorExtras * @attr ref android.R.styleable#TextView_elegantTextHeight * @attr ref android.R.styleable#TextView_letterSpacing * @attr ref android.R.styleable#TextView_fontFeatureSettings */ @RemoteView public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { static final String LOG_TAG = "TextView"; static final boolean DEBUG_EXTRACT = false; // Enum for the "typeface" XML parameter. // TODO: How can we get this from the XML instead of hardcoding it here? private static final int SANS = 1; private static final int SERIF = 2; private static final int MONOSPACE = 3; // Bitfield for the "numeric" XML parameter. // TODO: How can we get this from the XML instead of hardcoding it here? private static final int SIGNED = 2; private static final int DECIMAL = 4; /** * Draw marquee text with fading edges as usual */ private static final int MARQUEE_FADE_NORMAL = 0; /** * Draw marquee text as ellipsize end while inactive instead of with the fade. * (Useful for devices where the fade can be expensive if overdone) */ private static final int MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS = 1; /** * Draw marquee text with fading edges because it is currently active/animating. */ private static final int MARQUEE_FADE_SWITCH_SHOW_FADE = 2; private static final int LINES = 1; private static final int EMS = LINES; private static final int PIXELS = 2; private static final RectF TEMP_RECTF = new RectF(); // XXX should be much larger private static final int VERY_WIDE = 1024 * 1024; private static final int ANIMATED_SCROLL_GAP = 250; private static final InputFilter[] NO_FILTERS = new InputFilter[0]; private static final Spanned EMPTY_SPANNED = new SpannedString(""); private static final int CHANGE_WATCHER_PRIORITY = 100; // New state used to change background based on whether this TextView is multiline. private static final int[] MULTILINE_STATE_SET = {R.attr.state_multiline}; // System wide time for last cut or copy action. static long LAST_CUT_OR_COPY_TIME; private ColorStateList mTextColor; private ColorStateList mHintTextColor; private ColorStateList mLinkTextColor; @ViewDebug.ExportedProperty(category = "text") private int mCurTextColor; private int mCurHintTextColor; private boolean mFreezesText; private boolean mDispatchTemporaryDetach; /** * Whether this view is temporarily detached from the parent view. */ boolean mTemporaryDetach; private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); private float mShadowRadius, mShadowDx, mShadowDy; private int mShadowColor; private boolean mPreDrawRegistered; private boolean mPreDrawListenerDetached; // A flag to prevent repeated movements from escaping the enclosing text view. The idea here is // that if a user is holding down a movement key to traverse text, we shouldn't also traverse // the view hierarchy. On the other hand, if the user is using the movement key to traverse views // (i.e. the first movement was to traverse out of this view, or this view was traversed into by // the user holding the movement key down) then we shouldn't prevent the focus from changing. private boolean mPreventDefaultMovement; private TruncateAt mEllipsize; static class Drawables { final static int DRAWABLE_NONE = -1; final static int DRAWABLE_RIGHT = 0; final static int DRAWABLE_LEFT = 1; final Rect mCompoundRect = new Rect(); Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight, mDrawableStart, mDrawableEnd, mDrawableError, mDrawableTemp; Drawable mDrawableLeftInitial, mDrawableRightInitial; boolean mIsRtlCompatibilityMode; boolean mOverride; int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight, mDrawableSizeStart, mDrawableSizeEnd, mDrawableSizeError, mDrawableSizeTemp; int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight, mDrawableHeightStart, mDrawableHeightEnd, mDrawableHeightError, mDrawableHeightTemp; int mDrawablePadding; int mDrawableSaved = DRAWABLE_NONE; public Drawables(Context context) { final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; mIsRtlCompatibilityMode = (targetSdkVersion < JELLY_BEAN_MR1 || !context.getApplicationInfo().hasRtlSupport()); mOverride = false; } public void resolveWithLayoutDirection(int layoutDirection) { // First reset "left" and "right" drawables to their initial values mDrawableLeft = mDrawableLeftInitial; mDrawableRight = mDrawableRightInitial; if (mIsRtlCompatibilityMode) { // Use "start" drawable as "left" drawable if the "left" drawable was not defined if (mDrawableStart != null && mDrawableLeft == null) { mDrawableLeft = mDrawableStart; mDrawableSizeLeft = mDrawableSizeStart; mDrawableHeightLeft = mDrawableHeightStart; } // Use "end" drawable as "right" drawable if the "right" drawable was not defined if (mDrawableEnd != null && mDrawableRight == null) { mDrawableRight = mDrawableEnd; mDrawableSizeRight = mDrawableSizeEnd; mDrawableHeightRight = mDrawableHeightEnd; } } else { // JB-MR1+ normal case: "start" / "end" drawables are overriding "left" / "right" // drawable if and only if they have been defined switch (layoutDirection) { case LAYOUT_DIRECTION_RTL: if (mOverride) { mDrawableRight = mDrawableStart; mDrawableSizeRight = mDrawableSizeStart; mDrawableHeightRight = mDrawableHeightStart; mDrawableLeft = mDrawableEnd; mDrawableSizeLeft = mDrawableSizeEnd; mDrawableHeightLeft = mDrawableHeightEnd; } break; case LAYOUT_DIRECTION_LTR: default: if (mOverride) { mDrawableLeft = mDrawableStart; mDrawableSizeLeft = mDrawableSizeStart; mDrawableHeightLeft = mDrawableHeightStart; mDrawableRight = mDrawableEnd; mDrawableSizeRight = mDrawableSizeEnd; mDrawableHeightRight = mDrawableHeightEnd; } break; } } applyErrorDrawableIfNeeded(layoutDirection); updateDrawablesLayoutDirection(layoutDirection); } private void updateDrawablesLayoutDirection(int layoutDirection) { if (mDrawableLeft != null) { mDrawableLeft.setLayoutDirection(layoutDirection); } if (mDrawableRight != null) { mDrawableRight.setLayoutDirection(layoutDirection); } if (mDrawableTop != null) { mDrawableTop.setLayoutDirection(layoutDirection); } if (mDrawableBottom != null) { mDrawableBottom.setLayoutDirection(layoutDirection); } } public void setErrorDrawable(Drawable dr, TextView tv) { if (mDrawableError != dr && mDrawableError != null) { mDrawableError.setCallback(null); } mDrawableError = dr; final Rect compoundRect = mCompoundRect; int[] state = tv.getDrawableState(); if (mDrawableError != null) { mDrawableError.setState(state); mDrawableError.copyBounds(compoundRect); mDrawableError.setCallback(tv); mDrawableSizeError = compoundRect.width(); mDrawableHeightError = compoundRect.height(); } else { mDrawableSizeError = mDrawableHeightError = 0; } } private void applyErrorDrawableIfNeeded(int layoutDirection) { // first restore the initial state if needed switch (mDrawableSaved) { case DRAWABLE_LEFT: mDrawableLeft = mDrawableTemp; mDrawableSizeLeft = mDrawableSizeTemp; mDrawableHeightLeft = mDrawableHeightTemp; break; case DRAWABLE_RIGHT: mDrawableRight = mDrawableTemp; mDrawableSizeRight = mDrawableSizeTemp; mDrawableHeightRight = mDrawableHeightTemp; break; case DRAWABLE_NONE: default: } // then, if needed, assign the Error drawable to the correct location if (mDrawableError != null) { switch (layoutDirection) { case LAYOUT_DIRECTION_RTL: mDrawableSaved = DRAWABLE_LEFT; mDrawableTemp = mDrawableLeft; mDrawableSizeTemp = mDrawableSizeLeft; mDrawableHeightTemp = mDrawableHeightLeft; mDrawableLeft = mDrawableError; mDrawableSizeLeft = mDrawableSizeError; mDrawableHeightLeft = mDrawableHeightError; break; case LAYOUT_DIRECTION_LTR: default: mDrawableSaved = DRAWABLE_RIGHT; mDrawableTemp = mDrawableRight; mDrawableSizeTemp = mDrawableSizeRight; mDrawableHeightTemp = mDrawableHeightRight; mDrawableRight = mDrawableError; mDrawableSizeRight = mDrawableSizeError; mDrawableHeightRight = mDrawableHeightError; break; } } } } Drawables mDrawables; private CharWrapper mCharWrapper; private Marquee mMarquee; private boolean mRestartMarquee; private int mMarqueeRepeatLimit = 3; private int mLastLayoutDirection = -1; /** * On some devices the fading edges add a performance penalty if used * extensively in the same layout. This mode indicates how the marquee * is currently being shown, if applicable. (mEllipsize will == MARQUEE) */ private int mMarqueeFadeMode = MARQUEE_FADE_NORMAL; /** * When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores * the layout that should be used when the mode switches. */ private Layout mSavedMarqueeModeLayout; @ViewDebug.ExportedProperty(category = "text") private CharSequence mText; private CharSequence mTransformed; private BufferType mBufferType = BufferType.NORMAL; private CharSequence mHint; private Layout mHintLayout; private MovementMethod mMovement; private TransformationMethod mTransformation; private boolean mAllowTransformationLengthChange; private ChangeWatcher mChangeWatcher; private ArrayList<TextWatcher> mListeners; // display attributes private final TextPaint mTextPaint; private boolean mUserSetTextScaleX; private Layout mLayout; private int mGravity = Gravity.TOP | Gravity.START; private boolean mHorizontallyScrolling; private int mAutoLinkMask; private boolean mLinksClickable = true; private float mSpacingMult = 1.0f; private float mSpacingAdd = 0.0f; private int mMaximum = Integer.MAX_VALUE; private int mMaxMode = LINES; private int mMinimum = 0; private int mMinMode = LINES; private int mOldMaximum = mMaximum; private int mOldMaxMode = mMaxMode; private int mMaxWidth = Integer.MAX_VALUE; private int mMaxWidthMode = PIXELS; private int mMinWidth = 0; private int mMinWidthMode = PIXELS; private boolean mSingleLine; private int mDesiredHeightAtMeasure = -1; private boolean mIncludePad = true; private int mDeferScroll = -1; // tmp primitives, so we don't alloc them on each draw private Rect mTempRect; private long mLastScroll; private Scroller mScroller; private BoringLayout.Metrics mBoring, mHintBoring; private BoringLayout mSavedLayout, mSavedHintLayout; private TextDirectionHeuristic mTextDir; private InputFilter[] mFilters = NO_FILTERS; private volatile Locale mCurrentSpellCheckerLocaleCache; // It is possible to have a selection even when mEditor is null (programmatically set, like when // a link is pressed). These highlight-related fields do not go in mEditor. int mHighlightColor = 0x6633B5E5; private Path mHighlightPath; private final Paint mHighlightPaint; private boolean mHighlightPathBogus = true; // Although these fields are specific to editable text, they are not added to Editor because // they are defined by the TextView's style and are theme-dependent. int mCursorDrawableRes; // These four fields, could be moved to Editor, since we know their default values and we // could condition the creation of the Editor to a non standard value. This is however // brittle since the hardcoded values here (such as // com.android.internal.R.drawable.text_select_handle_left) would have to be updated if the // default style is modified. int mTextSelectHandleLeftRes; int mTextSelectHandleRightRes; int mTextSelectHandleRes; int mTextEditSuggestionItemLayout; /** * EditText specific data, created on demand when one of the Editor fields is used. * EditText特定数据,在使用编辑器字段时创建。 * See {@link #createEditorIfNeeded()}. */ private Editor mEditor; /* * Kick-start the font cache for the zygote process (to pay the cost of * initializing freetype for our default font only once). */ static { Paint p = new Paint(); p.setAntiAlias(true); // We don't care about the result, just the side-effect of measuring. p.measureText("H"); } /** * Interface definition for a callback to be invoked when an action is * performed on the editor. */ public interface OnEditorActionListener { /** * Called when an action is being performed. * * @param v The view that was clicked. * @param actionId Identifier of the action. This will be either the * identifier you supplied, or {@link EditorInfo#IME_NULL * EditorInfo.IME_NULL} if being called due to the enter key * being pressed. * @param event If triggered by an enter key, this is the event; * otherwise, this is null. * @return Return true if you have consumed the action, else false. */ boolean onEditorAction(TextView v, int actionId, KeyEvent event); } public TextView(Context context) { this(context, null); } public TextView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.textViewStyle); } public TextView(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } @SuppressWarnings("deprecation") public TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); mText = ""; final Resources res = getResources(); final CompatibilityInfo compat = res.getCompatibilityInfo(); mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); mTextPaint.density = res.getDisplayMetrics().density; mTextPaint.setCompatibilityScaling(compat.applicationScale); mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mHighlightPaint.setCompatibilityScaling(compat.applicationScale); mMovement = getDefaultMovementMethod(); mTransformation = null; int textColorHighlight = 0; ColorStateList textColor = null; ColorStateList textColorHint = null; ColorStateList textColorLink = null; int textSize = 15; String fontFamily = null; boolean fontFamilyExplicit = false; int typefaceIndex = -1; int styleIndex = -1; boolean allCaps = false; int shadowcolor = 0; float dx = 0, dy = 0, r = 0; boolean elegant = false; float letterSpacing = 0; String fontFeatureSettings = null; final Resources.Theme theme = context.getTheme(); /* * Look the appearance up without checking first if it exists because * almost every TextView has one and it greatly simplifies the logic * to be able to parse the appearance first and then let specific tags * for this View override it. */ TypedArray a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes); TypedArray appearance = null; int ap = a.getResourceId(com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1); a.recycle(); if (ap != -1) { appearance = theme.obtainStyledAttributes(ap, com.android.internal.R.styleable.TextAppearance); } if (appearance != null) { int n = appearance.getIndexCount(); for (int i = 0; i < n; i++) { int attr = appearance.getIndex(i); switch (attr) { case com.android.internal.R.styleable.TextAppearance_textColorHighlight: textColorHighlight = appearance.getColor(attr, textColorHighlight); break; case com.android.internal.R.styleable.TextAppearance_textColor: textColor = appearance.getColorStateList(attr); break; case com.android.internal.R.styleable.TextAppearance_textColorHint: textColorHint = appearance.getColorStateList(attr); break; case com.android.internal.R.styleable.TextAppearance_textColorLink: textColorLink = appearance.getColorStateList(attr); break; case com.android.internal.R.styleable.TextAppearance_textSize: textSize = appearance.getDimensionPixelSize(attr, textSize); break; case com.android.internal.R.styleable.TextAppearance_typeface: typefaceIndex = appearance.getInt(attr, -1); break; case com.android.internal.R.styleable.TextAppearance_fontFamily: fontFamily = appearance.getString(attr); break; case com.android.internal.R.styleable.TextAppearance_textStyle: styleIndex = appearance.getInt(attr, -1); break; case com.android.internal.R.styleable.TextAppearance_textAllCaps: allCaps = appearance.getBoolean(attr, false); break; case com.android.internal.R.styleable.TextAppearance_shadowColor: shadowcolor = appearance.getInt(attr, 0); break; case com.android.internal.R.styleable.TextAppearance_shadowDx: dx = appearance.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextAppearance_shadowDy: dy = appearance.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextAppearance_shadowRadius: r = appearance.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextAppearance_elegantTextHeight: elegant = appearance.getBoolean(attr, false); break; case com.android.internal.R.styleable.TextAppearance_letterSpacing: letterSpacing = appearance.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextAppearance_fontFeatureSettings: fontFeatureSettings = appearance.getString(attr); break; } } appearance.recycle(); } boolean editable = getDefaultEditable(); CharSequence inputMethod = null; int numeric = 0; CharSequence digits = null; boolean phone = false; boolean autotext = false; int autocap = -1; int buffertype = 0; boolean selectallonfocus = false; Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null, drawableStart = null, drawableEnd = null; int drawablePadding = 0; int ellipsize = -1; boolean singleLine = false; int maxlength = -1; CharSequence text = ""; CharSequence hint = null; boolean password = false; int inputType = EditorInfo.TYPE_NULL; a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case com.android.internal.R.styleable.TextView_editable: editable = a.getBoolean(attr, editable); break; case com.android.internal.R.styleable.TextView_inputMethod: inputMethod = a.getText(attr); break; case com.android.internal.R.styleable.TextView_numeric: numeric = a.getInt(attr, numeric); break; case com.android.internal.R.styleable.TextView_digits: digits = a.getText(attr); break; case com.android.internal.R.styleable.TextView_phoneNumber: phone = a.getBoolean(attr, phone); break; case com.android.internal.R.styleable.TextView_autoText: autotext = a.getBoolean(attr, autotext); break; case com.android.internal.R.styleable.TextView_capitalize: autocap = a.getInt(attr, autocap); break; case com.android.internal.R.styleable.TextView_bufferType: buffertype = a.getInt(attr, buffertype); break; case com.android.internal.R.styleable.TextView_selectAllOnFocus: selectallonfocus = a.getBoolean(attr, selectallonfocus); break; case com.android.internal.R.styleable.TextView_autoLink: mAutoLinkMask = a.getInt(attr, 0); break; case com.android.internal.R.styleable.TextView_linksClickable: mLinksClickable = a.getBoolean(attr, true); break; case com.android.internal.R.styleable.TextView_drawableLeft: drawableLeft = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawableTop: drawableTop = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawableRight: drawableRight = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawableBottom: drawableBottom = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawableStart: drawableStart = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawableEnd: drawableEnd = a.getDrawable(attr); break; case com.android.internal.R.styleable.TextView_drawablePadding: drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); break; case com.android.internal.R.styleable.TextView_maxLines: setMaxLines(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_maxHeight: setMaxHeight(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_lines: setLines(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_height: setHeight(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_minLines: setMinLines(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_minHeight: setMinHeight(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_maxEms: setMaxEms(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_maxWidth: setMaxWidth(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_ems: setEms(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_width: setWidth(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_minEms: setMinEms(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_minWidth: setMinWidth(a.getDimensionPixelSize(attr, -1)); break; case com.android.internal.R.styleable.TextView_gravity: setGravity(a.getInt(attr, -1)); break; case com.android.internal.R.styleable.TextView_hint: hint = a.getText(attr); break; case com.android.internal.R.styleable.TextView_text: text = a.getText(attr); break; case com.android.internal.R.styleable.TextView_scrollHorizontally: if (a.getBoolean(attr, false)) { setHorizontallyScrolling(true); } break; case com.android.internal.R.styleable.TextView_singleLine: singleLine = a.getBoolean(attr, singleLine); break; case com.android.internal.R.styleable.TextView_ellipsize: ellipsize = a.getInt(attr, ellipsize); break; case com.android.internal.R.styleable.TextView_marqueeRepeatLimit: setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit)); break; case com.android.internal.R.styleable.TextView_includeFontPadding: if (!a.getBoolean(attr, true)) { setIncludeFontPadding(false); } break; case com.android.internal.R.styleable.TextView_cursorVisible: if (!a.getBoolean(attr, true)) { setCursorVisible(false); } break; case com.android.internal.R.styleable.TextView_maxLength: maxlength = a.getInt(attr, -1); break; case com.android.internal.R.styleable.TextView_textScaleX: setTextScaleX(a.getFloat(attr, 1.0f)); break; case com.android.internal.R.styleable.TextView_freezesText: mFreezesText = a.getBoolean(attr, false); break; case com.android.internal.R.styleable.TextView_shadowColor: shadowcolor = a.getInt(attr, 0); break; case com.android.internal.R.styleable.TextView_shadowDx: dx = a.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextView_shadowDy: dy = a.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextView_shadowRadius: r = a.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextView_enabled: setEnabled(a.getBoolean(attr, isEnabled())); break; case com.android.internal.R.styleable.TextView_textColorHighlight: textColorHighlight = a.getColor(attr, textColorHighlight); break; case com.android.internal.R.styleable.TextView_textColor: textColor = a.getColorStateList(attr); break; case com.android.internal.R.styleable.TextView_textColorHint: textColorHint = a.getColorStateList(attr); break; case com.android.internal.R.styleable.TextView_textColorLink: textColorLink = a.getColorStateList(attr); break; case com.android.internal.R.styleable.TextView_textSize: textSize = a.getDimensionPixelSize(attr, textSize); break; case com.android.internal.R.styleable.TextView_typeface: typefaceIndex = a.getInt(attr, typefaceIndex); break; case com.android.internal.R.styleable.TextView_textStyle: styleIndex = a.getInt(attr, styleIndex); break; case com.android.internal.R.styleable.TextView_fontFamily: fontFamily = a.getString(attr); fontFamilyExplicit = true; break; case com.android.internal.R.styleable.TextView_password: password = a.getBoolean(attr, password); break; case com.android.internal.R.styleable.TextView_lineSpacingExtra: mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd); break; case com.android.internal.R.styleable.TextView_lineSpacingMultiplier: mSpacingMult = a.getFloat(attr, mSpacingMult); break; case com.android.internal.R.styleable.TextView_inputType: inputType = a.getInt(attr, EditorInfo.TYPE_NULL); break; case com.android.internal.R.styleable.TextView_imeOptions: createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.imeOptions = a.getInt(attr, mEditor.mInputContentType.imeOptions); break; case com.android.internal.R.styleable.TextView_imeActionLabel: createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.imeActionLabel = a.getText(attr); break; case com.android.internal.R.styleable.TextView_imeActionId: createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.imeActionId = a.getInt(attr, mEditor.mInputContentType.imeActionId); break; case com.android.internal.R.styleable.TextView_privateImeOptions: setPrivateImeOptions(a.getString(attr)); break; case com.android.internal.R.styleable.TextView_editorExtras: try { setInputExtras(a.getResourceId(attr, 0)); } catch (XmlPullParserException e) { Log.w(LOG_TAG, "Failure reading input extras", e); } catch (IOException e) { Log.w(LOG_TAG, "Failure reading input extras", e); } break; case com.android.internal.R.styleable.TextView_textCursorDrawable: mCursorDrawableRes = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textSelectHandleLeft: mTextSelectHandleLeftRes = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textSelectHandleRight: mTextSelectHandleRightRes = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textSelectHandle: mTextSelectHandleRes = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout: mTextEditSuggestionItemLayout = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textIsSelectable: setTextIsSelectable(a.getBoolean(attr, false)); break; case com.android.internal.R.styleable.TextView_textAllCaps: allCaps = a.getBoolean(attr, false); break; case com.android.internal.R.styleable.TextView_elegantTextHeight: elegant = a.getBoolean(attr, false); break; case com.android.internal.R.styleable.TextView_letterSpacing: letterSpacing = a.getFloat(attr, 0); break; case com.android.internal.R.styleable.TextView_fontFeatureSettings: fontFeatureSettings = a.getString(attr); break; } } a.recycle(); BufferType bufferType = BufferType.EDITABLE; final int variation = inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); final boolean passwordInputType = variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); final boolean webPasswordInputType = variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); final boolean numberPasswordInputType = variation == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); if (inputMethod != null) { Class<?> c; try { c = Class.forName(inputMethod.toString()); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } try { createEditorIfNeeded(); mEditor.mKeyListener = (KeyListener) c.newInstance(); } catch (InstantiationException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } try { mEditor.mInputType = inputType != EditorInfo.TYPE_NULL ? inputType : mEditor.mKeyListener.getInputType(); } catch (IncompatibleClassChangeError e) { mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; } } else if (digits != null) { createEditorIfNeeded(); mEditor.mKeyListener = DigitsKeyListener.getInstance(digits.toString()); // If no input type was specified, we will default to generic // text, since we can't tell the IME about the set of digits // that was selected. mEditor.mInputType = inputType != EditorInfo.TYPE_NULL ? inputType : EditorInfo.TYPE_CLASS_TEXT; } else if (inputType != EditorInfo.TYPE_NULL) { setInputType(inputType, true); // If set, the input type overrides what was set using the deprecated singleLine flag. singleLine = !isMultilineInputType(inputType); } else if (phone) { createEditorIfNeeded(); mEditor.mKeyListener = DialerKeyListener.getInstance(); mEditor.mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; } else if (numeric != 0) { createEditorIfNeeded(); mEditor.mKeyListener = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, (numeric & DECIMAL) != 0); inputType = EditorInfo.TYPE_CLASS_NUMBER; if ((numeric & SIGNED) != 0) { inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; } if ((numeric & DECIMAL) != 0) { inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; } mEditor.mInputType = inputType; } else if (autotext || autocap != -1) { TextKeyListener.Capitalize cap; inputType = EditorInfo.TYPE_CLASS_TEXT; switch (autocap) { case 1: cap = TextKeyListener.Capitalize.SENTENCES; inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; break; case 2: cap = TextKeyListener.Capitalize.WORDS; inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; break; case 3: cap = TextKeyListener.Capitalize.CHARACTERS; inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; break; default: cap = TextKeyListener.Capitalize.NONE; break; } createEditorIfNeeded(); mEditor.mKeyListener = TextKeyListener.getInstance(autotext, cap); mEditor.mInputType = inputType; } else if (isTextSelectable()) { // Prevent text changes from keyboard. if (mEditor != null) { mEditor.mKeyListener = null; mEditor.mInputType = EditorInfo.TYPE_NULL; } bufferType = BufferType.SPANNABLE; // So that selection can be changed using arrow keys and touch is handled. setMovementMethod(ArrowKeyMovementMethod.getInstance()); } else if (editable) { createEditorIfNeeded(); mEditor.mKeyListener = TextKeyListener.getInstance(); mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; } else { if (mEditor != null) mEditor.mKeyListener = null; switch (buffertype) { case 0: bufferType = BufferType.NORMAL; break; case 1: bufferType = BufferType.SPANNABLE; break; case 2: bufferType = BufferType.EDITABLE; break; } } if (mEditor != null) mEditor.adjustInputType(password, passwordInputType, webPasswordInputType, numberPasswordInputType); if (selectallonfocus) { createEditorIfNeeded(); mEditor.mSelectAllOnFocus = true; if (bufferType == BufferType.NORMAL) bufferType = BufferType.SPANNABLE; } // This call will save the initial left/right drawables setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom); setRelativeDrawablesIfNeeded(drawableStart, drawableEnd); setCompoundDrawablePadding(drawablePadding); // Same as setSingleLine(), but make sure the transformation method and the maximum number // of lines of height are unchanged for multi-line TextViews. setInputTypeSingleLine(singleLine); applySingleLine(singleLine, singleLine, singleLine); if (singleLine && getKeyListener() == null && ellipsize < 0) { ellipsize = 3; // END } switch (ellipsize) { case 1: setEllipsize(TruncateAt.START); break; case 2: setEllipsize(TruncateAt.MIDDLE); break; case 3: setEllipsize(TruncateAt.END); break; case 4: if (ViewConfiguration.get(context).isFadingMarqueeEnabled()) { setHorizontalFadingEdgeEnabled(true); mMarqueeFadeMode = MARQUEE_FADE_NORMAL; } else { setHorizontalFadingEdgeEnabled(false); mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; } setEllipsize(TruncateAt.MARQUEE); break; } setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000)); setHintTextColor(textColorHint); setLinkTextColor(textColorLink); if (textColorHighlight != 0) { setHighlightColor(textColorHighlight); } setRawTextSize(textSize); setElegantTextHeight(elegant); setLetterSpacing(letterSpacing); setFontFeatureSettings(fontFeatureSettings); if (allCaps) { setTransformationMethod(new AllCapsTransformationMethod(getContext())); } if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) { setTransformationMethod(PasswordTransformationMethod.getInstance()); typefaceIndex = MONOSPACE; } else if (mEditor != null && (mEditor.mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { typefaceIndex = MONOSPACE; } if (typefaceIndex != -1 && !fontFamilyExplicit) { fontFamily = null; } setTypefaceFromAttrs(fontFamily, typefaceIndex, styleIndex); if (shadowcolor != 0) { setShadowLayer(r, dx, dy, shadowcolor); } if (maxlength >= 0) { setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxlength)}); } else { setFilters(NO_FILTERS); } setText(text, bufferType); if (hint != null) setHint(hint); /* * Views are not normally focusable unless specified to be. * However, TextViews that have input or movement methods *are* * focusable by default. */ a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); boolean focusable = mMovement != null || getKeyListener() != null; boolean clickable = focusable || isClickable(); boolean longClickable = focusable || isLongClickable(); n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case com.android.internal.R.styleable.View_focusable: focusable = a.getBoolean(attr, focusable); break; case com.android.internal.R.styleable.View_clickable: clickable = a.getBoolean(attr, clickable); break; case com.android.internal.R.styleable.View_longClickable: longClickable = a.getBoolean(attr, longClickable); break; } } a.recycle(); setFocusable(focusable); setClickable(clickable); setLongClickable(longClickable); if (mEditor != null) mEditor.prepareCursorControllers(); // If not explicitly specified this view is important for accessibility. if (getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); } } private void setTypefaceFromAttrs(String familyName, int typefaceIndex, int styleIndex) { Typeface tf = null; if (familyName != null) { tf = Typeface.create(familyName, styleIndex); if (tf != null) { setTypeface(tf); return; } } switch (typefaceIndex) { case SANS: tf = Typeface.SANS_SERIF; break; case SERIF: tf = Typeface.SERIF; break; case MONOSPACE: tf = Typeface.MONOSPACE; break; } setTypeface(tf, styleIndex); } private void setRelativeDrawablesIfNeeded(Drawable start, Drawable end) { boolean hasRelativeDrawables = (start != null) || (end != null); if (hasRelativeDrawables) { Drawables dr = mDrawables; if (dr == null) { mDrawables = dr = new Drawables(getContext()); } mDrawables.mOverride = true; final Rect compoundRect = dr.mCompoundRect; int[] state = getDrawableState(); if (start != null) { start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); start.setState(state); start.copyBounds(compoundRect); start.setCallback(this); dr.mDrawableStart = start; dr.mDrawableSizeStart = compoundRect.width(); dr.mDrawableHeightStart = compoundRect.height(); } else { dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; } if (end != null) { end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); end.setState(state); end.copyBounds(compoundRect); end.setCallback(this); dr.mDrawableEnd = end; dr.mDrawableSizeEnd = compoundRect.width(); dr.mDrawableHeightEnd = compoundRect.height(); } else { dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; } resetResolvedDrawables(); resolveDrawables(); } } @Override public void setEnabled(boolean enabled) { if (enabled == isEnabled()) { return; } if (!enabled) { // Hide the soft input if the currently active TextView is disabled InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null && imm.isActive(this)) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } } super.setEnabled(enabled); if (enabled) { // Make sure IME is updated with current editor info. InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } // Will change text color if (mEditor != null) { mEditor.invalidateTextDisplayList(); mEditor.prepareCursorControllers(); // start or stop the cursor blinking as appropriate mEditor.makeBlink(); } } /** * Sets the typeface and style in which the text should be displayed, * and turns on the fake bold and italic bits in the Paint if the * Typeface that you provided does not have all the bits in the * style that you specified. * * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public void setTypeface(Typeface tf, int style) { if (style > 0) { if (tf == null) { tf = Typeface.defaultFromStyle(style); } else { tf = Typeface.create(tf, style); } setTypeface(tf); // now compute what (if any) algorithmic styling is needed int typefaceStyle = tf != null ? tf.getStyle() : 0; int need = style & ~typefaceStyle; mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else { mTextPaint.setFakeBoldText(false); mTextPaint.setTextSkewX(0); setTypeface(tf); } } /** * Subclasses override this to specify that they have a KeyListener * by default even if not specifically called for in the XML options. */ protected boolean getDefaultEditable() { return false; } /** * Subclasses override this to specify a default movement method. */ protected MovementMethod getDefaultMovementMethod() { return null; } /** * Return the text the TextView is displaying. If setText() was called with * an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast * the return value from this method to Spannable or Editable, respectively. * <p> * Note: The content of the return value should not be modified. If you want * a modifiable one, you should make your own copy first. * * @attr ref android.R.styleable#TextView_text */ @ViewDebug.CapturedViewProperty public CharSequence getText() { return mText; } /** * Returns the length, in characters, of the text managed by this TextView */ public int length() { return mText.length(); } /** * Return the text the TextView is displaying as an Editable object. If * the text is not editable, null is returned. * * @see #getText */ public Editable getEditableText() { return (mText instanceof Editable) ? (Editable) mText : null; } /** * @return the height of one standard line in pixels. Note that markup * within the text can cause individual lines to be taller or shorter * than this height, and the layout may contain additional first- * or last-line padding. */ public int getLineHeight() { return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); } /** * @return the Layout that is currently being used to display the text. * This can be null if the text or width has recently changes. */ public final Layout getLayout() { return mLayout; } /** * @return the Layout that is currently being used to display the hint text. * This can be null. */ final Layout getHintLayout() { return mHintLayout; } /** * Retrieve the {@link android.content.UndoManager} that is currently associated * with this TextView. By default there is no associated UndoManager, so null * is returned. One can be associated with the TextView through * {@link #setUndoManager(android.content.UndoManager, String)} * * @hide */ public final UndoManager getUndoManager() { return mEditor == null ? null : mEditor.mUndoManager; } /** * Associate an {@link android.content.UndoManager} with this TextView. Once * done, all edit operations on the TextView will result in appropriate * {@link android.content.UndoOperation} objects pushed on the given UndoManager's * stack. * * @param undoManager The {@link android.content.UndoManager} to associate with * this TextView, or null to clear any existing association. * @param tag String tag identifying this particular TextView owner in the * UndoManager. This is used to keep the correct association with the * {@link android.content.UndoOwner} of any operations inside of the UndoManager. * @hide */ public final void setUndoManager(UndoManager undoManager, String tag) { if (undoManager != null) { createEditorIfNeeded(); mEditor.mUndoManager = undoManager; mEditor.mUndoOwner = undoManager.getOwner(tag, this); mEditor.mUndoInputFilter = new Editor.UndoInputFilter(mEditor); if (!(mText instanceof Editable)) { setText(mText, BufferType.EDITABLE); } setFilters((Editable) mText, mFilters); } else if (mEditor != null) { // XXX need to destroy all associated state. mEditor.mUndoManager = null; mEditor.mUndoOwner = null; mEditor.mUndoInputFilter = null; } } /** * @return the current key listener for this TextView. * This will frequently be null for non-EditText TextViews. * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ public final KeyListener getKeyListener() { return mEditor == null ? null : mEditor.mKeyListener; } /** * Sets the key listener to be used with this TextView. This can be null * to disallow user input. Note that this method has significant and * subtle interactions with soft keyboards and other input method: * see {@link KeyListener#getInputType() KeyListener.getContentType()} * for important details. Calling this method will replace the current * content type of the text view with the content type returned by the * key listener. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. * * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ public void setKeyListener(KeyListener input) { setKeyListenerOnly(input); fixFocusableAndClickableSettings(); if (input != null) { createEditorIfNeeded(); try { mEditor.mInputType = mEditor.mKeyListener.getInputType(); } catch (IncompatibleClassChangeError e) { mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; } // Change inputType, without affecting transformation. // No need to applySingleLine since mSingleLine is unchanged. setInputTypeSingleLine(mSingleLine); } else { if (mEditor != null) mEditor.mInputType = EditorInfo.TYPE_NULL; } InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } private void setKeyListenerOnly(KeyListener input) { if (mEditor == null && input == null) return; // null is the default value createEditorIfNeeded(); if (mEditor.mKeyListener != input) { mEditor.mKeyListener = input; if (input != null && !(mText instanceof Editable)) { setText(mText); } setFilters((Editable) mText, mFilters); } } /** * @return the movement method being used for this TextView. * This will frequently be null for non-EditText TextViews. */ public final MovementMethod getMovementMethod() { return mMovement; } /** * Sets the movement method (arrow key handler) to be used for * this TextView. This can be null to disallow using the arrow keys * to move the cursor or scroll the view. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. */ public final void setMovementMethod(MovementMethod movement) { if (mMovement != movement) { mMovement = movement; if (movement != null && !(mText instanceof Spannable)) { setText(mText); } fixFocusableAndClickableSettings(); // SelectionModifierCursorController depends on textCanBeSelected, which depends on // mMovement if (mEditor != null) mEditor.prepareCursorControllers(); } } private void fixFocusableAndClickableSettings() { if (mMovement != null || (mEditor != null && mEditor.mKeyListener != null)) { setFocusable(true); setClickable(true); setLongClickable(true); } else { setFocusable(false); setClickable(false); setLongClickable(false); } } /** * @return the current transformation method for this TextView. * This will frequently be null except for single-line and password * fields. * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ public final TransformationMethod getTransformationMethod() { return mTransformation; } /** * Sets the transformation that is applied to the text that this * TextView is displaying. * * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ public final void setTransformationMethod(TransformationMethod method) { if (method == mTransformation) { // Avoid the setText() below if the transformation is // the same. return; } if (mTransformation != null) { if (mText instanceof Spannable) { ((Spannable) mText).removeSpan(mTransformation); } } mTransformation = method; if (method instanceof TransformationMethod2) { TransformationMethod2 method2 = (TransformationMethod2) method; mAllowTransformationLengthChange = !isTextSelectable() && !(mText instanceof Editable); method2.setLengthChangesAllowed(mAllowTransformationLengthChange); } else { mAllowTransformationLengthChange = false; } setText(mText); if (hasPasswordTransformationMethod()) { notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); } } /** * Returns the top padding of the view, plus space for the top * Drawable if any. */ public int getCompoundPaddingTop() { final Drawables dr = mDrawables; if (dr == null || dr.mDrawableTop == null) { return mPaddingTop; } else { return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; } } /** * Returns the bottom padding of the view, plus space for the bottom * Drawable if any. */ public int getCompoundPaddingBottom() { final Drawables dr = mDrawables; if (dr == null || dr.mDrawableBottom == null) { return mPaddingBottom; } else { return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; } } /** * Returns the left padding of the view, plus space for the left * Drawable if any. */ public int getCompoundPaddingLeft() { final Drawables dr = mDrawables; if (dr == null || dr.mDrawableLeft == null) { return mPaddingLeft; } else { return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; } } /** * Returns the right padding of the view, plus space for the right * Drawable if any. */ public int getCompoundPaddingRight() { final Drawables dr = mDrawables; if (dr == null || dr.mDrawableRight == null) { return mPaddingRight; } else { return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; } } /** * Returns the start padding of the view, plus space for the start * Drawable if any. */ public int getCompoundPaddingStart() { resolveDrawables(); switch (getLayoutDirection()) { default: case LAYOUT_DIRECTION_LTR: return getCompoundPaddingLeft(); case LAYOUT_DIRECTION_RTL: return getCompoundPaddingRight(); } } /** * Returns the end padding of the view, plus space for the end * Drawable if any. */ public int getCompoundPaddingEnd() { resolveDrawables(); switch (getLayoutDirection()) { default: case LAYOUT_DIRECTION_LTR: return getCompoundPaddingRight(); case LAYOUT_DIRECTION_RTL: return getCompoundPaddingLeft(); } } /** * Returns the extended top padding of the view, including both the * top Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ public int getExtendedPaddingTop() { if (mMaxMode != LINES) { return getCompoundPaddingTop(); } if (mLayout == null) { assumeLayout(); } if (mLayout.getLineCount() <= mMaximum) { return getCompoundPaddingTop(); } int top = getCompoundPaddingTop(); int bottom = getCompoundPaddingBottom(); int viewht = getHeight() - top - bottom; int layoutht = mLayout.getLineTop(mMaximum); if (layoutht >= viewht) { return top; } final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == Gravity.TOP) { return top; } else if (gravity == Gravity.BOTTOM) { return top + viewht - layoutht; } else { // (gravity == Gravity.CENTER_VERTICAL) return top + (viewht - layoutht) / 2; } } /** * Returns the extended bottom padding of the view, including both the * bottom Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ public int getExtendedPaddingBottom() { if (mMaxMode != LINES) { return getCompoundPaddingBottom(); } if (mLayout == null) { assumeLayout(); } if (mLayout.getLineCount() <= mMaximum) { return getCompoundPaddingBottom(); } int top = getCompoundPaddingTop(); int bottom = getCompoundPaddingBottom(); int viewht = getHeight() - top - bottom; int layoutht = mLayout.getLineTop(mMaximum); if (layoutht >= viewht) { return bottom; } final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == Gravity.TOP) { return bottom + viewht - layoutht; } else if (gravity == Gravity.BOTTOM) { return bottom; } else { // (gravity == Gravity.CENTER_VERTICAL) return bottom + (viewht - layoutht) / 2; } } /** * Returns the total left padding of the view, including the left * Drawable if any. */ public int getTotalPaddingLeft() { return getCompoundPaddingLeft(); } /** * Returns the total right padding of the view, including the right * Drawable if any. */ public int getTotalPaddingRight() { return getCompoundPaddingRight(); } /** * Returns the total start padding of the view, including the start * Drawable if any. */ public int getTotalPaddingStart() { return getCompoundPaddingStart(); } /** * Returns the total end padding of the view, including the end * Drawable if any. */ public int getTotalPaddingEnd() { return getCompoundPaddingEnd(); } /** * Returns the total top padding of the view, including the top * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ public int getTotalPaddingTop() { return getExtendedPaddingTop() + getVerticalOffset(true); } /** * Returns the total bottom padding of the view, including the bottom * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ public int getTotalPaddingBottom() { return getExtendedPaddingBottom() + getBottomVerticalOffset(true); } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use {@code null} if you do not want a * Drawable there. The Drawables must already have had * {@link Drawable#setBounds} called. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) { Drawables dr = mDrawables; // We're switching to absolute, discard relative. if (dr != null) { if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null); dr.mDrawableStart = null; if (dr.mDrawableEnd != null) dr.mDrawableEnd.setCallback(null); dr.mDrawableEnd = null; dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; } final boolean drawables = left != null || top != null || right != null || bottom != null; if (!drawables) { // Clearing drawables... can we free the data structure? if (dr != null) { if (dr.mDrawablePadding == 0) { mDrawables = null; } else { // We need to retain the last set padding, so just clear // out all of the fields in the existing structure. if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null); dr.mDrawableLeft = null; if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); dr.mDrawableTop = null; if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null); dr.mDrawableRight = null; if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); dr.mDrawableBottom = null; dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } } else { if (dr == null) { mDrawables = dr = new Drawables(getContext()); } mDrawables.mOverride = false; if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) { dr.mDrawableLeft.setCallback(null); } dr.mDrawableLeft = left; if (dr.mDrawableTop != top && dr.mDrawableTop != null) { dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = top; if (dr.mDrawableRight != right && dr.mDrawableRight != null) { dr.mDrawableRight.setCallback(null); } dr.mDrawableRight = right; if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = bottom; final Rect compoundRect = dr.mCompoundRect; int[] state; state = getDrawableState(); if (left != null) { left.setState(state); left.copyBounds(compoundRect); left.setCallback(this); dr.mDrawableSizeLeft = compoundRect.width(); dr.mDrawableHeightLeft = compoundRect.height(); } else { dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; } if (right != null) { right.setState(state); right.copyBounds(compoundRect); right.setCallback(this); dr.mDrawableSizeRight = compoundRect.width(); dr.mDrawableHeightRight = compoundRect.height(); } else { dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; } if (top != null) { top.setState(state); top.copyBounds(compoundRect); top.setCallback(this); dr.mDrawableSizeTop = compoundRect.height(); dr.mDrawableWidthTop = compoundRect.width(); } else { dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; } if (bottom != null) { bottom.setState(state); bottom.copyBounds(compoundRect); bottom.setCallback(this); dr.mDrawableSizeBottom = compoundRect.height(); dr.mDrawableWidthBottom = compoundRect.width(); } else { dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } // Save initial left/right drawables if (dr != null) { dr.mDrawableLeftInitial = left; dr.mDrawableRightInitial = right; } resetResolvedDrawables(); resolveDrawables(); invalidate(); requestLayout(); } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use 0 if you do not want a Drawable there. * The Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @param left Resource identifier of the left Drawable. * @param top Resource identifier of the top Drawable. * @param right Resource identifier of the right Drawable. * @param bottom Resource identifier of the bottom Drawable. * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ @android.view.RemotableViewMethod public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { final Context context = getContext(); setCompoundDrawablesWithIntrinsicBounds(left != 0 ? context.getDrawable(left) : null, top != 0 ? context.getDrawable(top) : null, right != 0 ? context.getDrawable(right) : null, bottom != 0 ? context.getDrawable(bottom) : null); } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use {@code null} if you do not want a * Drawable there. The Drawables' bounds will be set to their intrinsic * bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawablesWithIntrinsicBounds(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) { if (left != null) { left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); } if (right != null) { right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); } if (top != null) { top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); } if (bottom != null) { bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); } setCompoundDrawables(left, top, right, bottom); } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use {@code null} if you do not want a Drawable * there. The Drawables must already have had {@link Drawable#setBounds} * called. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawablesRelative(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable Drawable bottom) { Drawables dr = mDrawables; // We're switching to relative, discard absolute. if (dr != null) { if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null); dr.mDrawableLeft = dr.mDrawableLeftInitial = null; if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null); dr.mDrawableRight = dr.mDrawableRightInitial = null; dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; } final boolean drawables = start != null || top != null || end != null || bottom != null; if (!drawables) { // Clearing drawables... can we free the data structure? if (dr != null) { if (dr.mDrawablePadding == 0) { mDrawables = null; } else { // We need to retain the last set padding, so just clear // out all of the fields in the existing structure. if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null); dr.mDrawableStart = null; if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); dr.mDrawableTop = null; if (dr.mDrawableEnd != null) dr.mDrawableEnd.setCallback(null); dr.mDrawableEnd = null; if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); dr.mDrawableBottom = null; dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } } else { if (dr == null) { mDrawables = dr = new Drawables(getContext()); } mDrawables.mOverride = true; if (dr.mDrawableStart != start && dr.mDrawableStart != null) { dr.mDrawableStart.setCallback(null); } dr.mDrawableStart = start; if (dr.mDrawableTop != top && dr.mDrawableTop != null) { dr.mDrawableTop.setCallback(null); } dr.mDrawableTop = top; if (dr.mDrawableEnd != end && dr.mDrawableEnd != null) { dr.mDrawableEnd.setCallback(null); } dr.mDrawableEnd = end; if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { dr.mDrawableBottom.setCallback(null); } dr.mDrawableBottom = bottom; final Rect compoundRect = dr.mCompoundRect; int[] state; state = getDrawableState(); if (start != null) { start.setState(state); start.copyBounds(compoundRect); start.setCallback(this); dr.mDrawableSizeStart = compoundRect.width(); dr.mDrawableHeightStart = compoundRect.height(); } else { dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; } if (end != null) { end.setState(state); end.copyBounds(compoundRect); end.setCallback(this); dr.mDrawableSizeEnd = compoundRect.width(); dr.mDrawableHeightEnd = compoundRect.height(); } else { dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; } if (top != null) { top.setState(state); top.copyBounds(compoundRect); top.setCallback(this); dr.mDrawableSizeTop = compoundRect.height(); dr.mDrawableWidthTop = compoundRect.width(); } else { dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; } if (bottom != null) { bottom.setState(state); bottom.copyBounds(compoundRect); bottom.setCallback(this); dr.mDrawableSizeBottom = compoundRect.height(); dr.mDrawableWidthBottom = compoundRect.width(); } else { dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; } } resetResolvedDrawables(); resolveDrawables(); invalidate(); requestLayout(); } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use 0 if you do not want a Drawable there. The * Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @param start Resource identifier of the start Drawable. * @param top Resource identifier of the top Drawable. * @param end Resource identifier of the end Drawable. * @param bottom Resource identifier of the bottom Drawable. * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ @android.view.RemotableViewMethod public void setCompoundDrawablesRelativeWithIntrinsicBounds(int start, int top, int end, int bottom) { final Context context = getContext(); setCompoundDrawablesRelativeWithIntrinsicBounds(start != 0 ? context.getDrawable(start) : null, top != 0 ? context.getDrawable(top) : null, end != 0 ? context.getDrawable(end) : null, bottom != 0 ? context.getDrawable(bottom) : null); } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use {@code null} if you do not want a Drawable * there. The Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawablesRelativeWithIntrinsicBounds(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable Drawable bottom) { if (start != null) { start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); } if (end != null) { end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); } if (top != null) { top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); } if (bottom != null) { bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); } setCompoundDrawablesRelative(start, top, end, bottom); } /** * Returns drawables for the left, top, right, and bottom borders. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ @NonNull public Drawable[] getCompoundDrawables() { final Drawables dr = mDrawables; if (dr != null) { return new Drawable[]{dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom}; } else { return new Drawable[]{null, null, null, null}; } } /** * Returns drawables for the start, top, end, and bottom borders. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ @NonNull public Drawable[] getCompoundDrawablesRelative() { final Drawables dr = mDrawables; if (dr != null) { return new Drawable[]{dr.mDrawableStart, dr.mDrawableTop, dr.mDrawableEnd, dr.mDrawableBottom}; } else { return new Drawable[]{null, null, null, null}; } } /** * Sets the size of the padding between the compound drawables and * the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ @android.view.RemotableViewMethod public void setCompoundDrawablePadding(int pad) { Drawables dr = mDrawables; if (pad == 0) { if (dr != null) { dr.mDrawablePadding = pad; } } else { if (dr == null) { mDrawables = dr = new Drawables(getContext()); } dr.mDrawablePadding = pad; } invalidate(); requestLayout(); } /** * Returns the padding between the compound drawables and the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ public int getCompoundDrawablePadding() { final Drawables dr = mDrawables; return dr != null ? dr.mDrawablePadding : 0; } @Override public void setPadding(int left, int top, int right, int bottom) { if (left != mPaddingLeft || right != mPaddingRight || top != mPaddingTop || bottom != mPaddingBottom) { nullLayouts(); } // the super call will requestLayout() super.setPadding(left, top, right, bottom); invalidate(); } @Override public void setPaddingRelative(int start, int top, int end, int bottom) { if (start != getPaddingStart() || end != getPaddingEnd() || top != mPaddingTop || bottom != mPaddingBottom) { nullLayouts(); } // the super call will requestLayout() super.setPaddingRelative(start, top, end, bottom); invalidate(); } /** * Gets the autolink mask of the text. See {@link * Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ public final int getAutoLinkMask() { return mAutoLinkMask; } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setTextAppearance(Context context, int resid) { TypedArray appearance = context.obtainStyledAttributes(resid, com.android.internal.R.styleable.TextAppearance); int color; ColorStateList colors; int ts; color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); if (color != 0) { setHighlightColor(color); } colors = appearance.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColor); if (colors != null) { setTextColor(colors); } ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable. TextAppearance_textSize, 0); if (ts != 0) { setRawTextSize(ts); } colors = appearance.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColorHint); if (colors != null) { setHintTextColor(colors); } colors = appearance.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColorLink); if (colors != null) { setLinkTextColor(colors); } String familyName; int typefaceIndex, styleIndex; familyName = appearance.getString(com.android.internal.R.styleable. TextAppearance_fontFamily); typefaceIndex = appearance.getInt(com.android.internal.R.styleable. TextAppearance_typeface, -1); styleIndex = appearance.getInt(com.android.internal.R.styleable. TextAppearance_textStyle, -1); setTypefaceFromAttrs(familyName, typefaceIndex, styleIndex); final int shadowcolor = appearance.getInt(com.android.internal.R.styleable.TextAppearance_shadowColor, 0); if (shadowcolor != 0) { final float dx = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowDx, 0); final float dy = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowDy, 0); final float r = appearance.getFloat(com.android.internal.R.styleable.TextAppearance_shadowRadius, 0); setShadowLayer(r, dx, dy, shadowcolor); } if (appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_textAllCaps, false)) { setTransformationMethod(new AllCapsTransformationMethod(getContext())); } if (appearance.hasValue(com.android.internal.R.styleable.TextAppearance_elegantTextHeight)) { setElegantTextHeight(appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_elegantTextHeight, false)); } if (appearance.hasValue(com.android.internal.R.styleable.TextAppearance_letterSpacing)) { setLetterSpacing(appearance.getFloat(com.android.internal.R.styleable.TextAppearance_letterSpacing, 0)); } if (appearance.hasValue(com.android.internal.R.styleable.TextAppearance_fontFeatureSettings)) { setFontFeatureSettings(appearance.getString(com.android.internal.R.styleable.TextAppearance_fontFeatureSettings)); } appearance.recycle(); } /** * Get the default {@link Locale} of the text in this TextView. * * @return the default {@link Locale} of the text in this TextView. */ public Locale getTextLocale() { return mTextPaint.getTextLocale(); } /** * Set the default {@link Locale} of the text in this TextView to the given value. This value * is used to choose appropriate typefaces for ambiguous characters. Typically used for CJK * locales to disambiguate Hanzi/Kanji/Hanja characters. * * @param locale the {@link Locale} for drawing text, must not be null. * @see Paint#setTextLocale */ public void setTextLocale(Locale locale) { mTextPaint.setTextLocale(locale); } /** * @return the size (in pixels) of the default text size in this TextView. */ @ViewDebug.ExportedProperty(category = "text") public float getTextSize() { return mTextPaint.getTextSize(); } /** * @return the size (in scaled pixels) of thee default text size in this TextView. * @hide */ @ViewDebug.ExportedProperty(category = "text") public float getScaledTextSize() { return mTextPaint.getTextSize() / mTextPaint.density; } /** * @hide */ @ViewDebug.ExportedProperty(category = "text", mapping = {@ViewDebug.IntToString(from = Typeface.NORMAL, to = "NORMAL"), @ViewDebug.IntToString(from = Typeface.BOLD, to = "BOLD"), @ViewDebug.IntToString(from = Typeface.ITALIC, to = "ITALIC"), @ViewDebug.IntToString(from = Typeface.BOLD_ITALIC, to = "BOLD_ITALIC")}) public int getTypefaceStyle() { return mTextPaint.getTypeface().getStyle(); } /** * Set the default text size to the given value, interpreted as "scaled * pixel" units. This size is adjusted based on the current density and * user font size preference. * * @param size The scaled pixel size. * @attr ref android.R.styleable#TextView_textSize */ @android.view.RemotableViewMethod public void setTextSize(float size) { setTextSize(TypedValue.COMPLEX_UNIT_SP, size); } /** * Set the default text size to a given unit and value. See {@link * TypedValue} for the possible dimension units. * * @param unit The desired dimension unit. * @param size The desired size in the given units. * @attr ref android.R.styleable#TextView_textSize */ public void setTextSize(int unit, float size) { Context c = getContext(); Resources r; if (c == null) r = Resources.getSystem(); else r = c.getResources(); setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics())); } private void setRawTextSize(float size) { if (size != mTextPaint.getTextSize()) { mTextPaint.setTextSize(size); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * @return the extent by which text is currently being stretched * horizontally. This will usually be 1. */ public float getTextScaleX() { return mTextPaint.getTextScaleX(); } /** * Sets the extent by which text should be stretched horizontally. * * @attr ref android.R.styleable#TextView_textScaleX */ @android.view.RemotableViewMethod public void setTextScaleX(float size) { if (size != mTextPaint.getTextScaleX()) { mUserSetTextScaleX = true; mTextPaint.setTextScaleX(size); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Sets the typeface and style in which the text should be displayed. * Note that not all Typeface families actually have bold and italic * variants, so you may need to use * {@link #setTypeface(Typeface, int)} to get the appearance * that you actually want. * * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle * @see #getTypeface() */ public void setTypeface(Typeface tf) { if (mTextPaint.getTypeface() != tf) { mTextPaint.setTypeface(tf); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * @return the current typeface and style in which the text is being * displayed. * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle * @see #setTypeface(Typeface) */ public Typeface getTypeface() { return mTextPaint.getTypeface(); } /** * Set the TextView's elegant height metrics flag. This setting selects font * variants that have not been compacted to fit Latin-based vertical * metrics, and also increases top and bottom bounds to provide more space. * * @param elegant set the paint's elegant metrics flag. * @attr ref android.R.styleable#TextView_elegantTextHeight */ public void setElegantTextHeight(boolean elegant) { mTextPaint.setElegantTextHeight(elegant); } /** * @return the extent by which text is currently being letter-spaced. * This will normally be 0. * @see #setLetterSpacing(float) * @see Paint#setLetterSpacing */ public float getLetterSpacing() { return mTextPaint.getLetterSpacing(); } /** * Sets text letter-spacing. The value is in 'EM' units. Typical values * for slight expansion will be around 0.05. Negative values tighten text. * * @attr ref android.R.styleable#TextView_letterSpacing * @see #getLetterSpacing() * @see Paint#getLetterSpacing */ @android.view.RemotableViewMethod public void setLetterSpacing(float letterSpacing) { if (letterSpacing != mTextPaint.getLetterSpacing()) { mTextPaint.setLetterSpacing(letterSpacing); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * @return the currently set font feature settings. Default is null. * @see #setFontFeatureSettings(String) * @see Paint#setFontFeatureSettings */ @Nullable public String getFontFeatureSettings() { return mTextPaint.getFontFeatureSettings(); } /** * Sets font feature settings. The format is the same as the CSS * font-feature-settings attribute: * http://dev.w3.org/csswg/css-fonts/#propdef-font-feature-settings * * @param fontFeatureSettings font feature settings represented as CSS compatible string * @attr ref android.R.styleable#TextView_fontFeatureSettings * @see #getFontFeatureSettings() * @see Paint#getFontFeatureSettings */ @android.view.RemotableViewMethod public void setFontFeatureSettings(@Nullable String fontFeatureSettings) { if (fontFeatureSettings != mTextPaint.getFontFeatureSettings()) { mTextPaint.setFontFeatureSettings(fontFeatureSettings); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Sets the text color for all the states (normal, selected, * focused) to be this color. * * @attr ref android.R.styleable#TextView_textColor * @see #setTextColor(ColorStateList) * @see #getTextColors() */ @android.view.RemotableViewMethod public void setTextColor(int color) { mTextColor = ColorStateList.valueOf(color); updateTextColors(); } /** * Sets the text color. * * @attr ref android.R.styleable#TextView_textColor * @see #setTextColor(int) * @see #getTextColors() * @see #setHintTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) */ public void setTextColor(ColorStateList colors) { if (colors == null) { throw new NullPointerException(); } mTextColor = colors; updateTextColors(); } /** * Gets the text colors for the different states (normal, selected, focused) of the TextView. * * @attr ref android.R.styleable#TextView_textColor * @see #setTextColor(ColorStateList) * @see #setTextColor(int) */ public final ColorStateList getTextColors() { return mTextColor; } /** * <p>Return the current color selected for normal text.</p> * * @return Returns the current text color. */ public final int getCurrentTextColor() { return mCurTextColor; } /** * Sets the color used to display the selection highlight. * * @attr ref android.R.styleable#TextView_textColorHighlight */ @android.view.RemotableViewMethod public void setHighlightColor(int color) { if (mHighlightColor != color) { mHighlightColor = color; invalidate(); } } /** * @return the color used to display the selection highlight * @attr ref android.R.styleable#TextView_textColorHighlight * @see #setHighlightColor(int) */ public int getHighlightColor() { return mHighlightColor; } /** * Sets whether the soft input method will be made visible when this * TextView gets focused. The default is true. */ @android.view.RemotableViewMethod public final void setShowSoftInputOnFocus(boolean show) { createEditorIfNeeded(); mEditor.mShowSoftInputOnFocus = show; } /** * Returns whether the soft input method will be made visible when this * TextView gets focused. The default is true. */ public final boolean getShowSoftInputOnFocus() { // When there is no Editor, return default true value return mEditor == null || mEditor.mShowSoftInputOnFocus; } /** * Gives the text a shadow of the specified blur radius and color, the specified * distance from its drawn position. * <p> * The text shadow produced does not interact with the properties on view * that are responsible for real time shadows, * {@link View#getElevation() elevation} and * {@link View#getTranslationZ() translationZ}. * * @attr ref android.R.styleable#TextView_shadowColor * @attr ref android.R.styleable#TextView_shadowDx * @attr ref android.R.styleable#TextView_shadowDy * @attr ref android.R.styleable#TextView_shadowRadius * @see Paint#setShadowLayer(float, float, float, int) */ public void setShadowLayer(float radius, float dx, float dy, int color) { mTextPaint.setShadowLayer(radius, dx, dy, color); mShadowRadius = radius; mShadowDx = dx; mShadowDy = dy; mShadowColor = color; // Will change text clip region if (mEditor != null) mEditor.invalidateTextDisplayList(); invalidate(); } /** * Gets the radius of the shadow layer. * * @return the radius of the shadow layer. If 0, the shadow layer is not visible * @attr ref android.R.styleable#TextView_shadowRadius * @see #setShadowLayer(float, float, float, int) */ public float getShadowRadius() { return mShadowRadius; } /** * @return the horizontal offset of the shadow layer * @attr ref android.R.styleable#TextView_shadowDx * @see #setShadowLayer(float, float, float, int) */ public float getShadowDx() { return mShadowDx; } /** * @return the vertical offset of the shadow layer * @attr ref android.R.styleable#TextView_shadowDy * @see #setShadowLayer(float, float, float, int) */ public float getShadowDy() { return mShadowDy; } /** * @return the color of the shadow layer * @attr ref android.R.styleable#TextView_shadowColor * @see #setShadowLayer(float, float, float, int) */ public int getShadowColor() { return mShadowColor; } /** * @return the base paint used for the text. Please use this only to * consult the Paint's properties and not to change them. */ public TextPaint getPaint() { return mTextPaint; } /** * Sets the autolink mask of the text. See {@link * Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ @android.view.RemotableViewMethod public final void setAutoLinkMask(int mask) { mAutoLinkMask = mask; } /** * Sets whether the movement method will automatically be set to * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ @android.view.RemotableViewMethod public final void setLinksClickable(boolean whether) { mLinksClickable = whether; } /** * Returns whether the movement method will automatically be set to * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ public final boolean getLinksClickable() { return mLinksClickable; } /** * Returns the list of URLSpans attached to the text * (by {@link Linkify} or otherwise) if any. You can call * {@link URLSpan#getURL} on them to find where they link to * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} * to find the region of the text they are attached to. */ public URLSpan[] getUrls() { if (mText instanceof Spanned) { return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class); } else { return new URLSpan[0]; } } /** * Sets the color of the hint text for all the states (disabled, focussed, selected...) of this * TextView. * * @attr ref android.R.styleable#TextView_textColorHint * @see #setHintTextColor(ColorStateList) * @see #getHintTextColors() * @see #setTextColor(int) */ @android.view.RemotableViewMethod public final void setHintTextColor(int color) { mHintTextColor = ColorStateList.valueOf(color); updateTextColors(); } /** * Sets the color of the hint text. * * @attr ref android.R.styleable#TextView_textColorHint * @see #getHintTextColors() * @see #setHintTextColor(int) * @see #setTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) */ public final void setHintTextColor(ColorStateList colors) { mHintTextColor = colors; updateTextColors(); } /** * @return the color of the hint text, for the different states of this TextView. * @attr ref android.R.styleable#TextView_textColorHint * @see #setHintTextColor(ColorStateList) * @see #setHintTextColor(int) * @see #setTextColor(ColorStateList) * @see #setLinkTextColor(ColorStateList) */ public final ColorStateList getHintTextColors() { return mHintTextColor; } /** * <p>Return the current color selected to paint the hint text.</p> * * @return Returns the current hint text color. */ public final int getCurrentHintTextColor() { return mHintTextColor != null ? mCurHintTextColor : mCurTextColor; } /** * Sets the color of links in the text. * * @attr ref android.R.styleable#TextView_textColorLink * @see #setLinkTextColor(ColorStateList) * @see #getLinkTextColors() */ @android.view.RemotableViewMethod public final void setLinkTextColor(int color) { mLinkTextColor = ColorStateList.valueOf(color); updateTextColors(); } /** * Sets the color of links in the text. * * @attr ref android.R.styleable#TextView_textColorLink * @see #setLinkTextColor(int) * @see #getLinkTextColors() * @see #setTextColor(ColorStateList) * @see #setHintTextColor(ColorStateList) */ public final void setLinkTextColor(ColorStateList colors) { mLinkTextColor = colors; updateTextColors(); } /** * @return the list of colors used to paint the links in the text, for the different states of * this TextView * @attr ref android.R.styleable#TextView_textColorLink * @see #setLinkTextColor(ColorStateList) * @see #setLinkTextColor(int) */ public final ColorStateList getLinkTextColors() { return mLinkTextColor; } /** * Sets the horizontal alignment of the text and the * vertical gravity that will be used when there is extra space * in the TextView beyond what is required for the text itself. * * @attr ref android.R.styleable#TextView_gravity * @see Gravity */ public void setGravity(int gravity) { if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.START; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } boolean newLayout = false; if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) != (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)) { newLayout = true; } if (gravity != mGravity) { invalidate(); } mGravity = gravity; if (mLayout != null && newLayout) { // XXX this is heavy-handed because no actual content changes. int want = mLayout.getWidth(); int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), true); } } /** * Returns the horizontal and vertical alignment of this TextView. * * @attr ref android.R.styleable#TextView_gravity * @see Gravity */ public int getGravity() { return mGravity; } /** * @return the flags on the Paint being used to display the text. * @see Paint#getFlags */ public int getPaintFlags() { return mTextPaint.getFlags(); } /** * Sets flags on the Paint being used to display the text and * reflows the text if they are different from the old flags. * * @see Paint#setFlags */ @android.view.RemotableViewMethod public void setPaintFlags(int flags) { if (mTextPaint.getFlags() != flags) { mTextPaint.setFlags(flags); if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Sets whether the text should be allowed to be wider than the * View is. If false, it will be wrapped to the width of the View. * * @attr ref android.R.styleable#TextView_scrollHorizontally */ public void setHorizontallyScrolling(boolean whether) { if (mHorizontallyScrolling != whether) { mHorizontallyScrolling = whether; if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Returns whether the text is allowed to be wider than the View is. * If false, the text will be wrapped to the width of the View. * * @attr ref android.R.styleable#TextView_scrollHorizontally * @hide */ public boolean getHorizontallyScrolling() { return mHorizontallyScrolling; } /** * Makes the TextView at least this many lines tall. * <p> * Setting this value overrides any other (minimum) height setting. A single line TextView will * set this value to 1. * * @attr ref android.R.styleable#TextView_minLines * @see #getMinLines() */ @android.view.RemotableViewMethod public void setMinLines(int minlines) { mMinimum = minlines; mMinMode = LINES; requestLayout(); invalidate(); } /** * @return the minimum number of lines displayed in this TextView, or -1 if the minimum * height was set in pixels instead using {@link #setMinHeight(int) or #setHeight(int)}. * @attr ref android.R.styleable#TextView_minLines * @see #setMinLines(int) */ public int getMinLines() { return mMinMode == LINES ? mMinimum : -1; } /** * Makes the TextView at least this many pixels tall. * <p> * Setting this value overrides any other (minimum) number of lines setting. * * @attr ref android.R.styleable#TextView_minHeight */ @android.view.RemotableViewMethod public void setMinHeight(int minHeight) { mMinimum = minHeight; mMinMode = PIXELS; requestLayout(); invalidate(); } /** * @return the minimum height of this TextView expressed in pixels, or -1 if the minimum * height was set in number of lines instead using {@link #setMinLines(int) or #setLines(int)}. * @attr ref android.R.styleable#TextView_minHeight * @see #setMinHeight(int) */ public int getMinHeight() { return mMinMode == PIXELS ? mMinimum : -1; } /** * Makes the TextView at most this many lines tall. * <p> * Setting this value overrides any other (maximum) height setting. * * @attr ref android.R.styleable#TextView_maxLines */ @android.view.RemotableViewMethod public void setMaxLines(int maxlines) { mMaximum = maxlines; mMaxMode = LINES; requestLayout(); invalidate(); } /** * @return the maximum number of lines displayed in this TextView, or -1 if the maximum * height was set in pixels instead using {@link #setMaxHeight(int) or #setHeight(int)}. * @attr ref android.R.styleable#TextView_maxLines * @see #setMaxLines(int) */ public int getMaxLines() { return mMaxMode == LINES ? mMaximum : -1; } /** * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the * {@link #setMaxLines(int)} method. * <p> * Setting this value overrides any other (maximum) number of lines setting. * * @attr ref android.R.styleable#TextView_maxHeight */ @android.view.RemotableViewMethod public void setMaxHeight(int maxHeight) { mMaximum = maxHeight; mMaxMode = PIXELS; requestLayout(); invalidate(); } /** * @return the maximum height of this TextView expressed in pixels, or -1 if the maximum * height was set in number of lines instead using {@link #setMaxLines(int) or #setLines(int)}. * @attr ref android.R.styleable#TextView_maxHeight * @see #setMaxHeight(int) */ public int getMaxHeight() { return mMaxMode == PIXELS ? mMaximum : -1; } /** * Makes the TextView exactly this many lines tall. * <p> * Note that setting this value overrides any other (minimum / maximum) number of lines or * height setting. A single line TextView will set this value to 1. * * @attr ref android.R.styleable#TextView_lines */ @android.view.RemotableViewMethod public void setLines(int lines) { mMaximum = mMinimum = lines; mMaxMode = mMinMode = LINES; requestLayout(); invalidate(); } /** * Makes the TextView exactly this many pixels tall. * You could do the same thing by specifying this number in the * LayoutParams. * <p> * Note that setting this value overrides any other (minimum / maximum) number of lines or * height setting. * * @attr ref android.R.styleable#TextView_height */ @android.view.RemotableViewMethod public void setHeight(int pixels) { mMaximum = mMinimum = pixels; mMaxMode = mMinMode = PIXELS; requestLayout(); invalidate(); } /** * Makes the TextView at least this many ems wide * * @attr ref android.R.styleable#TextView_minEms */ @android.view.RemotableViewMethod public void setMinEms(int minems) { mMinWidth = minems; mMinWidthMode = EMS; requestLayout(); invalidate(); } /** * @return the minimum width of the TextView, expressed in ems or -1 if the minimum width * was set in pixels instead (using {@link #setMinWidth(int)} or {@link #setWidth(int)}). * @attr ref android.R.styleable#TextView_minEms * @see #setMinEms(int) * @see #setEms(int) */ public int getMinEms() { return mMinWidthMode == EMS ? mMinWidth : -1; } /** * Makes the TextView at least this many pixels wide * * @attr ref android.R.styleable#TextView_minWidth */ @android.view.RemotableViewMethod public void setMinWidth(int minpixels) { mMinWidth = minpixels; mMinWidthMode = PIXELS; requestLayout(); invalidate(); } /** * @return the minimum width of the TextView, in pixels or -1 if the minimum width * was set in ems instead (using {@link #setMinEms(int)} or {@link #setEms(int)}). * @attr ref android.R.styleable#TextView_minWidth * @see #setMinWidth(int) * @see #setWidth(int) */ public int getMinWidth() { return mMinWidthMode == PIXELS ? mMinWidth : -1; } /** * Makes the TextView at most this many ems wide * * @attr ref android.R.styleable#TextView_maxEms */ @android.view.RemotableViewMethod public void setMaxEms(int maxems) { mMaxWidth = maxems; mMaxWidthMode = EMS; requestLayout(); invalidate(); } /** * @return the maximum width of the TextView, expressed in ems or -1 if the maximum width * was set in pixels instead (using {@link #setMaxWidth(int)} or {@link #setWidth(int)}). * @attr ref android.R.styleable#TextView_maxEms * @see #setMaxEms(int) * @see #setEms(int) */ public int getMaxEms() { return mMaxWidthMode == EMS ? mMaxWidth : -1; } /** * Makes the TextView at most this many pixels wide * * @attr ref android.R.styleable#TextView_maxWidth */ @android.view.RemotableViewMethod public void setMaxWidth(int maxpixels) { mMaxWidth = maxpixels; mMaxWidthMode = PIXELS; requestLayout(); invalidate(); } /** * @return the maximum width of the TextView, in pixels or -1 if the maximum width * was set in ems instead (using {@link #setMaxEms(int)} or {@link #setEms(int)}). * @attr ref android.R.styleable#TextView_maxWidth * @see #setMaxWidth(int) * @see #setWidth(int) */ public int getMaxWidth() { return mMaxWidthMode == PIXELS ? mMaxWidth : -1; } /** * Makes the TextView exactly this many ems wide * * @attr ref android.R.styleable#TextView_ems * @see #setMaxEms(int) * @see #setMinEms(int) * @see #getMinEms() * @see #getMaxEms() */ @android.view.RemotableViewMethod public void setEms(int ems) { mMaxWidth = mMinWidth = ems; mMaxWidthMode = mMinWidthMode = EMS; requestLayout(); invalidate(); } /** * Makes the TextView exactly this many pixels wide. * You could do the same thing by specifying this number in the * LayoutParams. * * @attr ref android.R.styleable#TextView_width * @see #setMaxWidth(int) * @see #setMinWidth(int) * @see #getMinWidth() * @see #getMaxWidth() */ @android.view.RemotableViewMethod public void setWidth(int pixels) { mMaxWidth = mMinWidth = pixels; mMaxWidthMode = mMinWidthMode = PIXELS; requestLayout(); invalidate(); } /** * Sets line spacing for this TextView. Each line will have its height * multiplied by <code>mult</code> and have <code>add</code> added to it. * * @attr ref android.R.styleable#TextView_lineSpacingExtra * @attr ref android.R.styleable#TextView_lineSpacingMultiplier */ public void setLineSpacing(float add, float mult) { if (mSpacingAdd != add || mSpacingMult != mult) { mSpacingAdd = add; mSpacingMult = mult; if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Gets the line spacing multiplier * * @return the value by which each line's height is multiplied to get its actual height. * @attr ref android.R.styleable#TextView_lineSpacingMultiplier * @see #setLineSpacing(float, float) * @see #getLineSpacingExtra() */ public float getLineSpacingMultiplier() { return mSpacingMult; } /** * Gets the line spacing extra space * * @return the extra space that is added to the height of each lines of this TextView. * @attr ref android.R.styleable#TextView_lineSpacingExtra * @see #setLineSpacing(float, float) * @see #getLineSpacingMultiplier() */ public float getLineSpacingExtra() { return mSpacingAdd; } /** * Convenience method: Append the specified text to the TextView's * display buffer, upgrading it to BufferType.EDITABLE if it was * not already editable. */ public final void append(CharSequence text) { append(text, 0, text.length()); } /** * Convenience method: Append the specified text slice to the TextView's * display buffer, upgrading it to BufferType.EDITABLE if it was * not already editable. */ public void append(CharSequence text, int start, int end) { if (!(mText instanceof Editable)) { setText(mText, BufferType.EDITABLE); } ((Editable) mText).append(text, start, end); } private void updateTextColors() { boolean inval = false; int color = mTextColor.getColorForState(getDrawableState(), 0); if (color != mCurTextColor) { mCurTextColor = color; inval = true; } if (mLinkTextColor != null) { color = mLinkTextColor.getColorForState(getDrawableState(), 0); if (color != mTextPaint.linkColor) { mTextPaint.linkColor = color; inval = true; } } if (mHintTextColor != null) { color = mHintTextColor.getColorForState(getDrawableState(), 0); if (color != mCurHintTextColor) { mCurHintTextColor = color; if (mText.length() == 0) { inval = true; } } } if (inval) { // Text needs to be redrawn with the new color if (mEditor != null) mEditor.invalidateTextDisplayList(); invalidate(); } } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mTextColor != null && mTextColor.isStateful() || (mHintTextColor != null && mHintTextColor.isStateful()) || (mLinkTextColor != null && mLinkTextColor.isStateful())) { updateTextColors(); } final Drawables dr = mDrawables; if (dr != null) { int[] state = getDrawableState(); if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) { dr.mDrawableTop.setState(state); } if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) { dr.mDrawableBottom.setState(state); } if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) { dr.mDrawableLeft.setState(state); } if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) { dr.mDrawableRight.setState(state); } if (dr.mDrawableStart != null && dr.mDrawableStart.isStateful()) { dr.mDrawableStart.setState(state); } if (dr.mDrawableEnd != null && dr.mDrawableEnd.isStateful()) { dr.mDrawableEnd.setState(state); } } } @Override public void drawableHotspotChanged(float x, float y) { super.drawableHotspotChanged(x, y); final Drawables dr = mDrawables; if (dr != null) { if (dr.mDrawableTop != null) { dr.mDrawableTop.setHotspot(x, y); } if (dr.mDrawableBottom != null) { dr.mDrawableBottom.setHotspot(x, y); } if (dr.mDrawableLeft != null) { dr.mDrawableLeft.setHotspot(x, y); } if (dr.mDrawableRight != null) { dr.mDrawableRight.setHotspot(x, y); } if (dr.mDrawableStart != null) { dr.mDrawableStart.setHotspot(x, y); } if (dr.mDrawableEnd != null) { dr.mDrawableEnd.setHotspot(x, y); } } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); // Save state if we are forced to boolean save = mFreezesText; int start = 0; int end = 0; if (mText != null) { start = getSelectionStart(); end = getSelectionEnd(); if (start >= 0 || end >= 0) { // Or save state if there is a selection save = true; } } if (save) { SavedState ss = new SavedState(superState); // XXX Should also save the current scroll position! ss.selStart = start; ss.selEnd = end; if (mText instanceof Spanned) { Spannable sp = new SpannableStringBuilder(mText); if (mEditor != null) { removeMisspelledSpans(sp); sp.removeSpan(mEditor.mSuggestionRangeSpan); } ss.text = sp; } else { ss.text = mText.toString(); } if (isFocused() && start >= 0 && end >= 0) { ss.frozenWithFocus = true; } ss.error = getError(); return ss; } return superState; } void removeMisspelledSpans(Spannable spannable) { SuggestionSpan[] suggestionSpans = spannable.getSpans(0, spannable.length(), SuggestionSpan.class); for (int i = 0; i < suggestionSpans.length; i++) { int flags = suggestionSpans[i].getFlags(); if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) { spannable.removeSpan(suggestionSpans[i]); } } } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); // XXX restore buffer type too, as well as lots of other stuff if (ss.text != null) { setText(ss.text); } if (ss.selStart >= 0 && ss.selEnd >= 0) { if (mText instanceof Spannable) { int len = mText.length(); if (ss.selStart > len || ss.selEnd > len) { String restored = ""; if (ss.text != null) { restored = "(restored) "; } Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + "/" + ss.selEnd + " out of range for " + restored + "text " + mText); } else { Selection.setSelection((Spannable) mText, ss.selStart, ss.selEnd); if (ss.frozenWithFocus) { createEditorIfNeeded(); mEditor.mFrozenWithFocus = true; } } } } if (ss.error != null) { final CharSequence error = ss.error; // Display the error later, after the first layout pass post(new Runnable() { public void run() { setError(error); } }); } } /** * Control whether this text view saves its entire text contents when * freezing to an icicle, in addition to dynamic state such as cursor * position. By default this is false, not saving the text. Set to true * if the text in the text view is not being saved somewhere else in * persistent storage (such as in a content provider) so that if the * view is later thawed the user will not lose their data. * * @param freezesText Controls whether a frozen icicle should include the * entire text data: true to include it, false to not. * @attr ref android.R.styleable#TextView_freezesText */ @android.view.RemotableViewMethod public void setFreezesText(boolean freezesText) { mFreezesText = freezesText; } /** * Return whether this text view is including its entire text contents * in frozen icicles. * * @return Returns true if text is included, false if it isn't. * @see #setFreezesText */ public boolean getFreezesText() { return mFreezesText; } /////////////////////////////////////////////////////////////////////////// /** * Sets the Factory used to create new Editables. */ public final void setEditableFactory(Editable.Factory factory) { mEditableFactory = factory; setText(mText); } /** * Sets the Factory used to create new Spannables. */ public final void setSpannableFactory(Spannable.Factory factory) { mSpannableFactory = factory; setText(mText); } /** * Sets the string value of the TextView. TextView <em>does not</em> accept * HTML-like formatting, which you can do with text strings in XML resource files. * To style your strings, attach android.text.style.* objects to a * {@link SpannableString SpannableString}, or see the * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> * Available Resource Types</a> documentation for an example of setting * formatted text in the XML resource file. * * @attr ref android.R.styleable#TextView_text */ @android.view.RemotableViewMethod public final void setText(CharSequence text) { setText(text, mBufferType); } /** * Like {@link #setText(CharSequence)}, * except that the cursor position (if any) is retained in the new text. * * @param text The new text to place in the text view. * @see #setText(CharSequence) */ @android.view.RemotableViewMethod public final void setTextKeepState(CharSequence text) { setTextKeepState(text, mBufferType); } /** * Sets the text that this TextView is to display (see * {@link #setText(CharSequence)}) and also sets whether it is stored * in a styleable/spannable buffer and whether it is editable. * * @attr ref android.R.styleable#TextView_text * @attr ref android.R.styleable#TextView_bufferType */ public void setText(CharSequence text, BufferType type) { setText(text, type, true, 0); if (mCharWrapper != null) { mCharWrapper.mChars = null; } } private void setText(CharSequence text, BufferType type, boolean notifyBefore, int oldlen) { if (text == null) { text = ""; } // If suggestions are not enabled, remove the suggestion spans from the text if (!isSuggestionsEnabled()) { text = removeSuggestionSpans(text); } if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f); if (text instanceof Spanned && ((Spanned) text).getSpanStart(TruncateAt.MARQUEE) >= 0) { if (ViewConfiguration.get(mContext).isFadingMarqueeEnabled()) { setHorizontalFadingEdgeEnabled(true); mMarqueeFadeMode = MARQUEE_FADE_NORMAL; } else { setHorizontalFadingEdgeEnabled(false); mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; } setEllipsize(TruncateAt.MARQUEE); } int n = mFilters.length; for (int i = 0; i < n; i++) { CharSequence out = mFilters[i].filter(text, 0, text.length(), EMPTY_SPANNED, 0, 0); if (out != null) { text = out; } } if (notifyBefore) { if (mText != null) { oldlen = mText.length(); sendBeforeTextChanged(mText, 0, oldlen, text.length()); } else { sendBeforeTextChanged("", 0, 0, text.length()); } } boolean needEditableForNotification = false; if (mListeners != null && mListeners.size() != 0) { needEditableForNotification = true; } if (type == BufferType.EDITABLE || getKeyListener() != null || needEditableForNotification) { createEditorIfNeeded(); Editable t = mEditableFactory.newEditable(text); text = t; setFilters(t, mFilters); InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } else if (type == BufferType.SPANNABLE || mMovement != null) { text = mSpannableFactory.newSpannable(text); } else if (!(text instanceof CharWrapper)) { text = TextUtils.stringOrSpannedString(text); } if (mAutoLinkMask != 0) { Spannable s2; if (type == BufferType.EDITABLE || text instanceof Spannable) { s2 = (Spannable) text; } else { s2 = mSpannableFactory.newSpannable(text); } if (Linkify.addLinks(s2, mAutoLinkMask)) { text = s2; type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE; /* * We must go ahead and set the text before changing the * movement method, because setMovementMethod() may call * setText() again to try to upgrade the buffer type. */ mText = text; // Do not change the movement method for text that support text selection as it // would prevent an arbitrary cursor displacement. if (mLinksClickable && !textCanBeSelected()) { setMovementMethod(LinkMovementMethod.getInstance()); } } } mBufferType = type; mText = text; if (mTransformation == null) { mTransformed = text; } else { mTransformed = mTransformation.getTransformation(text, this); } final int textLength = text.length(); if (text instanceof Spannable && !mAllowTransformationLengthChange) { Spannable sp = (Spannable) text; // Remove any ChangeWatchers that might have come from other TextViews. final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class); final int count = watchers.length; for (int i = 0; i < count; i++) { sp.removeSpan(watchers[i]); } if (mChangeWatcher == null) mChangeWatcher = new ChangeWatcher(); sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE | (CHANGE_WATCHER_PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); if (mEditor != null) mEditor.addSpanWatchers(sp); if (mTransformation != null) { sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); } if (mMovement != null) { mMovement.initialize(this, (Spannable) text); /* * Initializing the movement method will have set the * selection, so reset mSelectionMoved to keep that from * interfering with the normal on-focus selection-setting. */ if (mEditor != null) mEditor.mSelectionMoved = false; } } if (mLayout != null) { checkForRelayout(); } sendOnTextChanged(text, 0, oldlen, textLength); onTextChanged(text, 0, oldlen, textLength); notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT); if (needEditableForNotification) { sendAfterTextChanged((Editable) text); } // SelectionModifierCursorController depends on textCanBeSelected, which depends on text if (mEditor != null) mEditor.prepareCursorControllers(); } /** * Sets the TextView to display the specified slice of the specified * char array. You must promise that you will not change the contents * of the array except for right before another call to setText(), * since the TextView has no way to know that the text * has changed and that it needs to invalidate and re-layout. */ public final void setText(char[] text, int start, int len) { int oldlen = 0; if (start < 0 || len < 0 || start + len > text.length) { throw new IndexOutOfBoundsException(start + ", " + len); } /* * We must do the before-notification here ourselves because if * the old text is a CharWrapper we destroy it before calling * into the normal path. */ if (mText != null) { oldlen = mText.length(); sendBeforeTextChanged(mText, 0, oldlen, len); } else { sendBeforeTextChanged("", 0, 0, len); } if (mCharWrapper == null) { mCharWrapper = new CharWrapper(text, start, len); } else { mCharWrapper.set(text, start, len); } setText(mCharWrapper, mBufferType, false, oldlen); } /** * Like {@link #setText(CharSequence, BufferType)}, * except that the cursor position (if any) is retained in the new text. * * @see #setText(CharSequence, BufferType) */ public final void setTextKeepState(CharSequence text, BufferType type) { int start = getSelectionStart(); int end = getSelectionEnd(); int len = text.length(); setText(text, type); if (start >= 0 || end >= 0) { if (mText instanceof Spannable) { Selection.setSelection((Spannable) mText, Math.max(0, Math.min(start, len)), Math.max(0, Math.min(end, len))); } } } @android.view.RemotableViewMethod public final void setText(int resid) { setText(getContext().getResources().getText(resid)); } public final void setText(int resid, BufferType type) { setText(getContext().getResources().getText(resid), type); } /** * Sets the text to be displayed when the text of the TextView is empty. * Null means to use the normal empty text. The hint does not currently * participate in determining the size of the view. * * @attr ref android.R.styleable#TextView_hint */ @android.view.RemotableViewMethod public final void setHint(CharSequence hint) { mHint = TextUtils.stringOrSpannedString(hint); if (mLayout != null) { checkForRelayout(); } if (mText.length() == 0) { invalidate(); } // Invalidate display list if hint is currently used if (mEditor != null && mText.length() == 0 && mHint != null) { mEditor.invalidateTextDisplayList(); } } /** * Sets the text to be displayed when the text of the TextView is empty, * from a resource. * * @attr ref android.R.styleable#TextView_hint */ @android.view.RemotableViewMethod public final void setHint(int resid) { setHint(getContext().getResources().getText(resid)); } /** * Returns the hint that is displayed when the text of the TextView * is empty. * * @attr ref android.R.styleable#TextView_hint */ @ViewDebug.CapturedViewProperty public CharSequence getHint() { return mHint; } boolean isSingleLine() { return mSingleLine; } private static boolean isMultilineInputType(int type) { return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); } /** * Removes the suggestion spans. */ CharSequence removeSuggestionSpans(CharSequence text) { if (text instanceof Spanned) { Spannable spannable; if (text instanceof Spannable) { spannable = (Spannable) text; } else { spannable = new SpannableString(text); text = spannable; } SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class); for (int i = 0; i < spans.length; i++) { spannable.removeSpan(spans[i]); } } return text; } /** * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} * then a soft keyboard will not be displayed for this text view. * <p> * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input * type. * * @attr ref android.R.styleable#TextView_inputType * @see #getInputType() * @see #setRawInputType(int) * @see InputType */ public void setInputType(int type) { final boolean wasPassword = isPasswordInputType(getInputType()); final boolean wasVisiblePassword = isVisiblePasswordInputType(getInputType()); setInputType(type, false); final boolean isPassword = isPasswordInputType(type); final boolean isVisiblePassword = isVisiblePasswordInputType(type); boolean forceUpdate = false; if (isPassword) { setTransformationMethod(PasswordTransformationMethod.getInstance()); setTypefaceFromAttrs(null /* fontFamily */, MONOSPACE, 0); } else if (isVisiblePassword) { if (mTransformation == PasswordTransformationMethod.getInstance()) { forceUpdate = true; } setTypefaceFromAttrs(null /* fontFamily */, MONOSPACE, 0); } else if (wasPassword || wasVisiblePassword) { // not in password mode, clean up typeface and transformation setTypefaceFromAttrs(null /* fontFamily */, -1, -1); if (mTransformation == PasswordTransformationMethod.getInstance()) { forceUpdate = true; } } boolean singleLine = !isMultilineInputType(type); // We need to update the single line mode if it has changed or we // were previously in password mode. if (mSingleLine != singleLine || forceUpdate) { // Change single line mode, but only change the transformation if // we are not in password mode. applySingleLine(singleLine, !isPassword, true); } if (!isSuggestionsEnabled()) { mText = removeSuggestionSpans(mText); } InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } /** * It would be better to rely on the input type for everything. A password inputType should have * a password transformation. We should hence use isPasswordInputType instead of this method. * <p> * We should: * - Call setInputType in setKeyListener instead of changing the input type directly (which * would install the correct transformation). * - Refuse the installation of a non-password transformation in setTransformation if the input * type is password. * <p> * However, this is like this for legacy reasons and we cannot break existing apps. This method * is useful since it matches what the user can see (obfuscated text or not). * * @return true if the current transformation method is of the password type. */ private boolean hasPasswordTransformationMethod() { return mTransformation instanceof PasswordTransformationMethod; } private static boolean isPasswordInputType(int inputType) { final int variation = inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); return variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) || variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) || variation == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); } private static boolean isVisiblePasswordInputType(int inputType) { final int variation = inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); return variation == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } /** * Directly change the content type integer of the text view, without * modifying any other state. * * @attr ref android.R.styleable#TextView_inputType * @see #setInputType(int) * @see InputType */ public void setRawInputType(int type) { if (type == InputType.TYPE_NULL && mEditor == null) return; //TYPE_NULL is the default value createEditorIfNeeded(); mEditor.mInputType = type; } private void setInputType(int type, boolean direct) { final int cls = type & EditorInfo.TYPE_MASK_CLASS; KeyListener input; if (cls == EditorInfo.TYPE_CLASS_TEXT) { boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; TextKeyListener.Capitalize cap; if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { cap = TextKeyListener.Capitalize.CHARACTERS; } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { cap = TextKeyListener.Capitalize.WORDS; } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { cap = TextKeyListener.Capitalize.SENTENCES; } else { cap = TextKeyListener.Capitalize.NONE; } input = TextKeyListener.getInstance(autotext, cap); } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { input = DigitsKeyListener.getInstance((type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { switch (type & EditorInfo.TYPE_MASK_VARIATION) { case EditorInfo.TYPE_DATETIME_VARIATION_DATE: input = DateKeyListener.getInstance(); break; case EditorInfo.TYPE_DATETIME_VARIATION_TIME: input = TimeKeyListener.getInstance(); break; default: input = DateTimeKeyListener.getInstance(); break; } } else if (cls == EditorInfo.TYPE_CLASS_PHONE) { input = DialerKeyListener.getInstance(); } else { input = TextKeyListener.getInstance(); } setRawInputType(type); if (direct) { createEditorIfNeeded(); mEditor.mKeyListener = input; } else { setKeyListenerOnly(input); } } /** * Get the type of the editable content. * * @see #setInputType(int) * @see InputType */ public int getInputType() { return mEditor == null ? EditorInfo.TYPE_NULL : mEditor.mInputType; } /** * Change the editor type integer associated with the text view, which * will be reported to an IME with {@link EditorInfo#imeOptions} when it * has focus. * * @attr ref android.R.styleable#TextView_imeOptions * @see #getImeOptions * @see EditorInfo */ public void setImeOptions(int imeOptions) { createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.imeOptions = imeOptions; } /** * Get the type of the IME editor. * * @see #setImeOptions(int) * @see EditorInfo */ public int getImeOptions() { return mEditor != null && mEditor.mInputContentType != null ? mEditor.mInputContentType.imeOptions : EditorInfo.IME_NULL; } /** * Change the custom IME action associated with the text view, which * will be reported to an IME with {@link EditorInfo#actionLabel} * and {@link EditorInfo#actionId} when it has focus. * * @attr ref android.R.styleable#TextView_imeActionLabel * @attr ref android.R.styleable#TextView_imeActionId * @see #getImeActionLabel * @see #getImeActionId * @see EditorInfo */ public void setImeActionLabel(CharSequence label, int actionId) { createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.imeActionLabel = label; mEditor.mInputContentType.imeActionId = actionId; } /** * Get the IME action label previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see EditorInfo */ public CharSequence getImeActionLabel() { return mEditor != null && mEditor.mInputContentType != null ? mEditor.mInputContentType.imeActionLabel : null; } /** * Get the IME action ID previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see EditorInfo */ public int getImeActionId() { return mEditor != null && mEditor.mInputContentType != null ? mEditor.mInputContentType.imeActionId : 0; } /** * Set a special listener to be called when an action is performed * on the text view. This will be called when the enter key is pressed, * or when an action supplied to the IME is selected by the user. Setting * this means that the normal hard key event will not insert a newline * into the text view, even if it is multi-line; holding down the ALT * modifier will, however, allow the user to insert a newline character. */ public void setOnEditorActionListener(OnEditorActionListener l) { createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.onEditorActionListener = l; } /** * Called when an attached input method calls * {@link InputConnection#performEditorAction(int) * InputConnection.performEditorAction()} * for this text view. The default implementation will call your action * listener supplied to {@link #setOnEditorActionListener}, or perform * a standard operation for {@link EditorInfo#IME_ACTION_NEXT * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE * EditorInfo.IME_ACTION_DONE}. * <p> * <p>For backwards compatibility, if no IME options have been set and the * text view would not normally advance focus on enter, then * the NEXT and DONE actions received here will be turned into an enter * key down/up pair to go through the normal key handling. * * @param actionCode The code of the action being performed. * @see #setOnEditorActionListener */ public void onEditorAction(int actionCode) { final Editor.InputContentType ict = mEditor == null ? null : mEditor.mInputContentType; if (ict != null) { if (ict.onEditorActionListener != null) { if (ict.onEditorActionListener.onEditorAction(this, actionCode, null)) { return; } } // This is the handling for some default action. // Note that for backwards compatibility we don't do this // default handling if explicit ime options have not been given, // instead turning this into the normal enter key codes that an // app may be expecting. if (actionCode == EditorInfo.IME_ACTION_NEXT) { View v = focusSearch(FOCUS_FORWARD); if (v != null) { if (!v.requestFocus(FOCUS_FORWARD)) { throw new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!"); } } return; } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { View v = focusSearch(FOCUS_BACKWARD); if (v != null) { if (!v.requestFocus(FOCUS_BACKWARD)) { throw new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!"); } } return; } else if (actionCode == EditorInfo.IME_ACTION_DONE) { InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null && imm.isActive(this)) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } return; } } ViewRootImpl viewRootImpl = getViewRootImpl(); if (viewRootImpl != null) { long eventTime = SystemClock.uptimeMillis(); viewRootImpl.dispatchKeyFromIme(new KeyEvent(eventTime, eventTime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE | KeyEvent.FLAG_EDITOR_ACTION)); viewRootImpl.dispatchKeyFromIme(new KeyEvent(SystemClock.uptimeMillis(), eventTime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE | KeyEvent.FLAG_EDITOR_ACTION)); } } /** * Set the private content type of the text, which is the * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} * field that will be filled in when creating an input connection. * * @attr ref android.R.styleable#TextView_privateImeOptions * @see #getPrivateImeOptions() * @see EditorInfo#privateImeOptions */ public void setPrivateImeOptions(String type) { createEditorIfNeeded(); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.privateImeOptions = type; } /** * Get the private type of the content. * * @see #setPrivateImeOptions(String) * @see EditorInfo#privateImeOptions */ public String getPrivateImeOptions() { return mEditor != null && mEditor.mInputContentType != null ? mEditor.mInputContentType.privateImeOptions : null; } /** * Set the extra input data of the text, which is the * {@link EditorInfo#extras TextBoxAttribute.extras} * Bundle that will be filled in when creating an input connection. The * given integer is the resource ID of an XML resource holding an * {@link R.styleable#InputExtras &lt;input-extras&gt;} XML tree. * * @attr ref android.R.styleable#TextView_editorExtras * @see #getInputExtras(boolean) * @see EditorInfo#extras */ public void setInputExtras(int xmlResId) throws XmlPullParserException, IOException { createEditorIfNeeded(); XmlResourceParser parser = getResources().getXml(xmlResId); mEditor.createInputContentTypeIfNeeded(); mEditor.mInputContentType.extras = new Bundle(); getResources().parseBundleExtras(parser, mEditor.mInputContentType.extras); } /** * Retrieve the input extras currently associated with the text view, which * can be viewed as well as modified. * * @param create If true, the extras will be created if they don't already * exist. Otherwise, null will be returned if none have been created. * @attr ref android.R.styleable#TextView_editorExtras * @see #setInputExtras(int) * @see EditorInfo#extras */ public Bundle getInputExtras(boolean create) { if (mEditor == null && !create) return null; createEditorIfNeeded(); if (mEditor.mInputContentType == null) { if (!create) return null; mEditor.createInputContentTypeIfNeeded(); } if (mEditor.mInputContentType.extras == null) { if (!create) return null; mEditor.mInputContentType.extras = new Bundle(); } return mEditor.mInputContentType.extras; } /** * Returns the error message that was set to be displayed with * {@link #setError}, or <code>null</code> if no error was set * or if it the error was cleared by the widget after user input. */ public CharSequence getError() { return mEditor == null ? null : mEditor.mError; } /** * Sets the right-hand compound drawable of the TextView to the "error" * icon and sets an error message that will be displayed in a popup when * the TextView has focus. The icon and error message will be reset to * null when any key events cause changes to the TextView's text. If the * <code>error</code> is <code>null</code>, the error message and icon * will be cleared. */ @android.view.RemotableViewMethod public void setError(CharSequence error) { if (error == null) { setError(null, null); } else { Drawable dr = getContext().getDrawable(com.android.internal.R.drawable.indicator_input_error); dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); setError(error, dr); } } /** * Sets the right-hand compound drawable of the TextView to the specified * icon and sets an error message that will be displayed in a popup when * the TextView has focus. The icon and error message will be reset to * null when any key events cause changes to the TextView's text. The * drawable must already have had {@link Drawable#setBounds} set on it. * If the <code>error</code> is <code>null</code>, the error message will * be cleared (and you should provide a <code>null</code> icon as well). */ public void setError(CharSequence error, Drawable icon) { createEditorIfNeeded(); mEditor.setError(error, icon); notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean result = super.setFrame(l, t, r, b); if (mEditor != null) mEditor.setFrame(); restartMarqueeIfNeeded(); return result; } private void restartMarqueeIfNeeded() { if (mRestartMarquee && mEllipsize == TruncateAt.MARQUEE) { mRestartMarquee = false; startMarquee(); } } /** * Sets the list of input filters that will be used if the buffer is * Editable. Has no effect otherwise. * * @attr ref android.R.styleable#TextView_maxLength */ public void setFilters(InputFilter[] filters) { if (filters == null) { throw new IllegalArgumentException(); } mFilters = filters; if (mText instanceof Editable) { setFilters((Editable) mText, filters); } } /** * Sets the list of input filters on the specified Editable, * and includes mInput in the list if it is an InputFilter. */ private void setFilters(Editable e, InputFilter[] filters) { if (mEditor != null) { final boolean undoFilter = mEditor.mUndoInputFilter != null; final boolean keyFilter = mEditor.mKeyListener instanceof InputFilter; int num = 0; if (undoFilter) num++; if (keyFilter) num++; if (num > 0) { InputFilter[] nf = new InputFilter[filters.length + num]; System.arraycopy(filters, 0, nf, 0, filters.length); num = 0; if (undoFilter) { nf[filters.length] = mEditor.mUndoInputFilter; num++; } if (keyFilter) { nf[filters.length + num] = (InputFilter) mEditor.mKeyListener; } e.setFilters(nf); return; } } e.setFilters(filters); } /** * Returns the current list of input filters. * * @attr ref android.R.styleable#TextView_maxLength */ public InputFilter[] getFilters() { return mFilters; } ///////////////////////////////////////////////////////////////////////// private int getBoxHeight(Layout l) { Insets opticalInsets = isLayoutModeOptical(mParent) ? getOpticalInsets() : Insets.NONE; int padding = (l == mHintLayout) ? getCompoundPaddingTop() + getCompoundPaddingBottom() : getExtendedPaddingTop() + getExtendedPaddingBottom(); return getMeasuredHeight() - padding + opticalInsets.top + opticalInsets.bottom; } int getVerticalOffset(boolean forceNormal) { int voffset = 0; final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; Layout l = mLayout; if (!forceNormal && mText.length() == 0 && mHintLayout != null) { l = mHintLayout; } if (gravity != Gravity.TOP) { int boxht = getBoxHeight(l); int textht = l.getHeight(); if (textht < boxht) { if (gravity == Gravity.BOTTOM) voffset = boxht - textht; else // (gravity == Gravity.CENTER_VERTICAL) voffset = (boxht - textht) >> 1; } } return voffset; } private int getBottomVerticalOffset(boolean forceNormal) { int voffset = 0; final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; Layout l = mLayout; if (!forceNormal && mText.length() == 0 && mHintLayout != null) { l = mHintLayout; } if (gravity != Gravity.BOTTOM) { int boxht = getBoxHeight(l); int textht = l.getHeight(); if (textht < boxht) { if (gravity == Gravity.TOP) voffset = boxht - textht; else // (gravity == Gravity.CENTER_VERTICAL) voffset = (boxht - textht) >> 1; } } return voffset; } void invalidateCursorPath() { if (mHighlightPathBogus) { invalidateCursor(); } else { final int horizontalPadding = getCompoundPaddingLeft(); final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); if (mEditor.mCursorCount == 0) { synchronized (TEMP_RECTF) { /* * The reason for this concern about the thickness of the * cursor and doing the floor/ceil on the coordinates is that * some EditTexts (notably textfields in the Browser) have * anti-aliased text where not all the characters are * necessarily at integer-multiple locations. This should * make sure the entire cursor gets invalidated instead of * sometimes missing half a pixel. */ float thick = FloatMath.ceil(mTextPaint.getStrokeWidth()); if (thick < 1.0f) { thick = 1.0f; } thick /= 2.0f; // mHighlightPath is guaranteed to be non null at that point. mHighlightPath.computeBounds(TEMP_RECTF, false); invalidate((int) FloatMath.floor(horizontalPadding + TEMP_RECTF.left - thick), (int) FloatMath.floor(verticalPadding + TEMP_RECTF.top - thick), (int) FloatMath.ceil(horizontalPadding + TEMP_RECTF.right + thick), (int) FloatMath.ceil(verticalPadding + TEMP_RECTF.bottom + thick)); } } else { for (int i = 0; i < mEditor.mCursorCount; i++) { Rect bounds = mEditor.mCursorDrawable[i].getBounds(); invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, bounds.right + horizontalPadding, bounds.bottom + verticalPadding); } } } } void invalidateCursor() { int where = getSelectionEnd(); invalidateCursor(where, where, where); } private void invalidateCursor(int a, int b, int c) { if (a >= 0 || b >= 0 || c >= 0) { int start = Math.min(Math.min(a, b), c); int end = Math.max(Math.max(a, b), c); invalidateRegion(start, end, true /* Also invalidates blinking cursor */); } } /** * Invalidates the region of text enclosed between the start and end text offsets. */ void invalidateRegion(int start, int end, boolean invalidateCursor) { if (mLayout == null) { invalidate(); } else { int lineStart = mLayout.getLineForOffset(start); int top = mLayout.getLineTop(lineStart); // This is ridiculous, but the descent from the line above // can hang down into the line we really want to redraw, // so we have to invalidate part of the line above to make // sure everything that needs to be redrawn really is. // (But not the whole line above, because that would cause // the same problem with the descenders on the line above it!) if (lineStart > 0) { top -= mLayout.getLineDescent(lineStart - 1); } int lineEnd; if (start == end) lineEnd = lineStart; else lineEnd = mLayout.getLineForOffset(end); int bottom = mLayout.getLineBottom(lineEnd); // mEditor can be null in case selection is set programmatically. if (invalidateCursor && mEditor != null) { for (int i = 0; i < mEditor.mCursorCount; i++) { Rect bounds = mEditor.mCursorDrawable[i].getBounds(); top = Math.min(top, bounds.top); bottom = Math.max(bottom, bounds.bottom); } } final int compoundPaddingLeft = getCompoundPaddingLeft(); final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); int left, right; if (lineStart == lineEnd && !invalidateCursor) { left = (int) mLayout.getPrimaryHorizontal(start); right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0); left += compoundPaddingLeft; right += compoundPaddingLeft; } else { // Rectangle bounding box when the region spans several lines left = compoundPaddingLeft; right = getWidth() - getCompoundPaddingRight(); } invalidate(mScrollX + left, verticalPadding + top, mScrollX + right, verticalPadding + bottom); } } private void registerForPreDraw() { if (!mPreDrawRegistered) { getViewTreeObserver().addOnPreDrawListener(this); mPreDrawRegistered = true; } } private void unregisterForPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); mPreDrawRegistered = false; mPreDrawListenerDetached = false; } /** * {@inheritDoc} */ public boolean onPreDraw() { if (mLayout == null) { assumeLayout(); } if (mMovement != null) { /* This code also provides auto-scrolling when a cursor is moved using a * CursorController (insertion point or selection limits). * For selection, ensure start or end is visible depending on controller's state. */ int curs = getSelectionEnd(); // Do not create the controller if it is not already created. if (mEditor != null && mEditor.mSelectionModifierCursorController != null && mEditor.mSelectionModifierCursorController.isSelectionStartDragged()) { curs = getSelectionStart(); } /* * TODO: This should really only keep the end in view if * it already was before the text changed. I'm not sure * of a good way to tell from here if it was. */ if (curs < 0 && (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { curs = mText.length(); } if (curs >= 0) { bringPointIntoView(curs); } } else { bringTextIntoView(); } // This has to be checked here since: // - onFocusChanged cannot start it when focus is given to a view with selected text (after // a screen rotation) since layout is not yet initialized at that point. if (mEditor != null && mEditor.mCreatedWithASelection) { mEditor.startSelectionActionMode(); mEditor.mCreatedWithASelection = false; } // Phone specific code (there is no ExtractEditText on tablets). // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can // not be set. Do the test here instead. if (this instanceof ExtractEditText && hasSelection() && mEditor != null) { mEditor.startSelectionActionMode(); } unregisterForPreDraw(); return true; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mTemporaryDetach = false; if (mEditor != null) mEditor.onAttachedToWindow(); if (mPreDrawListenerDetached) { getViewTreeObserver().addOnPreDrawListener(this); mPreDrawListenerDetached = false; } } /** * @hide */ @Override protected void onDetachedFromWindowInternal() { if (mPreDrawRegistered) { getViewTreeObserver().removeOnPreDrawListener(this); mPreDrawListenerDetached = true; } resetResolvedDrawables(); if (mEditor != null) mEditor.onDetachedFromWindow(); super.onDetachedFromWindowInternal(); } @Override public void onScreenStateChanged(int screenState) { super.onScreenStateChanged(screenState); if (mEditor != null) mEditor.onScreenStateChanged(screenState); } @Override protected boolean isPaddingOffsetRequired() { return mShadowRadius != 0 || mDrawables != null; } @Override protected int getLeftPaddingOffset() { return getCompoundPaddingLeft() - mPaddingLeft + (int) Math.min(0, mShadowDx - mShadowRadius); } @Override protected int getTopPaddingOffset() { return (int) Math.min(0, mShadowDy - mShadowRadius); } @Override protected int getBottomPaddingOffset() { return (int) Math.max(0, mShadowDy + mShadowRadius); } private int getFudgedPaddingRight() { // Add sufficient space for cursor and tone marks int cursorWidth = 2 + (int) mTextPaint.density; // adequate for Material cursors return Math.max(0, getCompoundPaddingRight() - (cursorWidth - 1)); } @Override protected int getRightPaddingOffset() { return -(getFudgedPaddingRight() - mPaddingRight) + (int) Math.max(0, mShadowDx + mShadowRadius); } @Override protected boolean verifyDrawable(Drawable who) { final boolean verified = super.verifyDrawable(who); if (!verified && mDrawables != null) { return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom || who == mDrawables.mDrawableStart || who == mDrawables.mDrawableEnd; } return verified; } @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); if (mDrawables != null) { if (mDrawables.mDrawableLeft != null) { mDrawables.mDrawableLeft.jumpToCurrentState(); } if (mDrawables.mDrawableTop != null) { mDrawables.mDrawableTop.jumpToCurrentState(); } if (mDrawables.mDrawableRight != null) { mDrawables.mDrawableRight.jumpToCurrentState(); } if (mDrawables.mDrawableBottom != null) { mDrawables.mDrawableBottom.jumpToCurrentState(); } if (mDrawables.mDrawableStart != null) { mDrawables.mDrawableStart.jumpToCurrentState(); } if (mDrawables.mDrawableEnd != null) { mDrawables.mDrawableEnd.jumpToCurrentState(); } } } @Override public void invalidateDrawable(Drawable drawable) { boolean handled = false; if (verifyDrawable(drawable)) { final Rect dirty = drawable.getBounds(); int scrollX = mScrollX; int scrollY = mScrollY; // IMPORTANT: The coordinates below are based on the coordinates computed // for each compound drawable in onDraw(). Make sure to update each section // accordingly. final Drawables drawables = mDrawables; if (drawables != null) { if (drawable == drawables.mDrawableLeft) { final int compoundPaddingTop = getCompoundPaddingTop(); final int compoundPaddingBottom = getCompoundPaddingBottom(); final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; scrollX += mPaddingLeft; scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; handled = true; } else if (drawable == drawables.mDrawableRight) { final int compoundPaddingTop = getCompoundPaddingTop(); final int compoundPaddingBottom = getCompoundPaddingBottom(); final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; handled = true; } else if (drawable == drawables.mDrawableTop) { final int compoundPaddingLeft = getCompoundPaddingLeft(); final int compoundPaddingRight = getCompoundPaddingRight(); final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; scrollY += mPaddingTop; handled = true; } else if (drawable == drawables.mDrawableBottom) { final int compoundPaddingLeft = getCompoundPaddingLeft(); final int compoundPaddingRight = getCompoundPaddingRight(); final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); handled = true; } } if (handled) { invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } } if (!handled) { super.invalidateDrawable(drawable); } } @Override public boolean hasOverlappingRendering() { // horizontal fading edge causes SaveLayerAlpha, which doesn't support alpha modulation return ((getBackground() != null && getBackground().getCurrent() != null) || mText instanceof Spannable || hasSelection() || isHorizontalFadingEdgeEnabled()); } /** * Returns the state of the {@code textIsSelectable} flag (See * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag * to allow users to select and copy text in a non-editable TextView, the content of an * {@link EditText} can always be selected, independently of the value of this flag. * <p> * * @return True if the text displayed in this TextView can be selected by the user. * @attr ref android.R.styleable#TextView_textIsSelectable */ public boolean isTextSelectable() { return mEditor == null ? false : mEditor.mTextIsSelectable; } /** * Sets whether the content of this view is selectable by the user. The default is * {@code false}, meaning that the content is not selectable. * <p> * When you use a TextView to display a useful piece of information to the user (such as a * contact's address), make it selectable, so that the user can select and copy its * content. You can also use set the XML attribute * {@link R.styleable#TextView_textIsSelectable} to "true". * <p> * When you call this method to set the value of {@code textIsSelectable}, it sets * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable}, * and {@code longClickable} to the same value. These flags correspond to the attributes * {@link R.styleable#View_focusable android:focusable}, * {@link R.styleable#View_focusableInTouchMode android:focusableInTouchMode}, * {@link R.styleable#View_clickable android:clickable}, and * {@link R.styleable#View_longClickable android:longClickable}. To restore any of these * flags to a state you had set previously, call one or more of the following methods: * {@link #setFocusable(boolean) setFocusable()}, * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()}, * {@link #setClickable(boolean) setClickable()} or * {@link #setLongClickable(boolean) setLongClickable()}. * * @param selectable Whether the content of this TextView should be selectable. */ public void setTextIsSelectable(boolean selectable) { if (!selectable && mEditor == null) return; // false is default value with no edit data createEditorIfNeeded(); if (mEditor.mTextIsSelectable == selectable) return; mEditor.mTextIsSelectable = selectable; setFocusableInTouchMode(selectable); setFocusable(selectable); setClickable(selectable); setLongClickable(selectable); // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL); // Called by setText above, but safer in case of future code changes mEditor.prepareCursorControllers(); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState; if (mSingleLine) { drawableState = super.onCreateDrawableState(extraSpace); } else { drawableState = super.onCreateDrawableState(extraSpace + 1); mergeDrawableStates(drawableState, MULTILINE_STATE_SET); } if (isTextSelectable()) { // Disable pressed state, which was introduced when TextView was made clickable. // Prevents text color change. // setClickable(false) would have a similar effect, but it also disables focus changes // and long press actions, which are both needed by text selection. final int length = drawableState.length; for (int i = 0; i < length; i++) { if (drawableState[i] == R.attr.state_pressed) { final int[] nonPressedState = new int[length - 1]; System.arraycopy(drawableState, 0, nonPressedState, 0, i); System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); return nonPressedState; } } } return drawableState; } private Path getUpdatedHighlightPath() { Path highlight = null; Paint highlightPaint = mHighlightPaint; final int selStart = getSelectionStart(); final int selEnd = getSelectionEnd(); if (mMovement != null && (isFocused() || isPressed()) && selStart >= 0) { if (selStart == selEnd) { if (mEditor != null && mEditor.isCursorVisible() && (SystemClock.uptimeMillis() - mEditor.mShowCursor) % (2 * Editor.BLINK) < Editor.BLINK) { if (mHighlightPathBogus) { if (mHighlightPath == null) mHighlightPath = new Path(); mHighlightPath.reset(); mLayout.getCursorPath(selStart, mHighlightPath, mText); mEditor.updateCursorsPositions(); mHighlightPathBogus = false; } // XXX should pass to skin instead of drawing directly highlightPaint.setColor(mCurTextColor); highlightPaint.setStyle(Paint.Style.STROKE); highlight = mHighlightPath; } } else { if (mHighlightPathBogus) { if (mHighlightPath == null) mHighlightPath = new Path(); mHighlightPath.reset(); mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); mHighlightPathBogus = false; } // XXX should pass to skin instead of drawing directly highlightPaint.setColor(mHighlightColor); highlightPaint.setStyle(Paint.Style.FILL); highlight = mHighlightPath; } } return highlight; } /** * @hide */ public int getHorizontalOffsetForDrawables() { return 0; } @Override protected void onDraw(Canvas canvas) { restartMarqueeIfNeeded(); // Draw the background for this view super.onDraw(canvas); final int compoundPaddingLeft = getCompoundPaddingLeft(); final int compoundPaddingTop = getCompoundPaddingTop(); final int compoundPaddingRight = getCompoundPaddingRight(); final int compoundPaddingBottom = getCompoundPaddingBottom(); final int scrollX = mScrollX; final int scrollY = mScrollY; final int right = mRight; final int left = mLeft; final int bottom = mBottom; final int top = mTop; final boolean isLayoutRtl = isLayoutRtl(); final int offset = getHorizontalOffsetForDrawables(); final int leftOffset = isLayoutRtl ? 0 : offset; final int rightOffset = isLayoutRtl ? offset : 0; final Drawables dr = mDrawables; if (dr != null) { /* * Compound, not extended, because the icon is not clipped * if the text height is smaller. */ int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; // IMPORTANT: The coordinates computed are also used in invalidateDrawable() // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableLeft != null) { canvas.save(); canvas.translate(scrollX + mPaddingLeft + leftOffset, scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightLeft) / 2); dr.mDrawableLeft.draw(canvas); canvas.restore(); } // IMPORTANT: The coordinates computed are also used in invalidateDrawable() // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableRight != null) { canvas.save(); canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight - rightOffset, scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); dr.mDrawableRight.draw(canvas); canvas.restore(); } // IMPORTANT: The coordinates computed are also used in invalidateDrawable() // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableTop != null) { canvas.save(); canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop); dr.mDrawableTop.draw(canvas); canvas.restore(); } // IMPORTANT: The coordinates computed are also used in invalidateDrawable() // Make sure to update invalidateDrawable() when changing this code. if (dr.mDrawableBottom != null) { canvas.save(); canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthBottom) / 2, scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); dr.mDrawableBottom.draw(canvas); canvas.restore(); } } int color = mCurTextColor; if (mLayout == null) { assumeLayout(); } Layout layout = mLayout; if (mHint != null && mText.length() == 0) { if (mHintTextColor != null) { color = mCurHintTextColor; } layout = mHintLayout; } mTextPaint.setColor(color); mTextPaint.drawableState = getDrawableState(); canvas.save(); /* Would be faster if we didn't have to do this. Can we chop the (displayable) text so that we don't need to do this ever? */ int extendedPaddingTop = getExtendedPaddingTop(); int extendedPaddingBottom = getExtendedPaddingBottom(); final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; final int maxScrollY = mLayout.getHeight() - vspace; float clipLeft = compoundPaddingLeft + scrollX; float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY; float clipRight = right - left - getFudgedPaddingRight() + scrollX; float clipBottom = bottom - top + scrollY - ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom); if (mShadowRadius != 0) { clipLeft += Math.min(0, mShadowDx - mShadowRadius); clipRight += Math.max(0, mShadowDx + mShadowRadius); clipTop += Math.min(0, mShadowDy - mShadowRadius); clipBottom += Math.max(0, mShadowDy + mShadowRadius); } canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); int voffsetText = 0; int voffsetCursor = 0; // translate in by our padding /* shortcircuit calling getVerticaOffset() */ if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffsetText = getVerticalOffset(false); voffsetCursor = getVerticalOffset(true); } canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); final int layoutDirection = getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); if (mEllipsize == TruncateAt.MARQUEE && mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (!mSingleLine && getLineCount() == 1 && canMarquee() && (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { final int width = mRight - mLeft; final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight(); final float dx = mLayout.getLineRight(0) - (width - padding); canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); } if (mMarquee != null && mMarquee.isRunning()) { final float dx = -mMarquee.getScroll(); canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); } } final int cursorOffsetVertical = voffsetCursor - voffsetText; Path highlight = getUpdatedHighlightPath(); if (mEditor != null) { mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical); } else { layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); } if (mMarquee != null && mMarquee.shouldDrawGhost()) { final float dx = mMarquee.getGhostOffset(); canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); } canvas.restore(); } @Override public void getFocusedRect(Rect r) { if (mLayout == null) { super.getFocusedRect(r); return; } int selEnd = getSelectionEnd(); if (selEnd < 0) { super.getFocusedRect(r); return; } int selStart = getSelectionStart(); if (selStart < 0 || selStart >= selEnd) { int line = mLayout.getLineForOffset(selEnd); r.top = mLayout.getLineTop(line); r.bottom = mLayout.getLineBottom(line); r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2; r.right = r.left + 4; } else { int lineStart = mLayout.getLineForOffset(selStart); int lineEnd = mLayout.getLineForOffset(selEnd); r.top = mLayout.getLineTop(lineStart); r.bottom = mLayout.getLineBottom(lineEnd); if (lineStart == lineEnd) { r.left = (int) mLayout.getPrimaryHorizontal(selStart); r.right = (int) mLayout.getPrimaryHorizontal(selEnd); } else { // Selection extends across multiple lines -- make the focused // rect cover the entire width. if (mHighlightPathBogus) { if (mHighlightPath == null) mHighlightPath = new Path(); mHighlightPath.reset(); mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); mHighlightPathBogus = false; } synchronized (TEMP_RECTF) { mHighlightPath.computeBounds(TEMP_RECTF, true); r.left = (int) TEMP_RECTF.left - 1; r.right = (int) TEMP_RECTF.right + 1; } } } // Adjust for padding and gravity. int paddingLeft = getCompoundPaddingLeft(); int paddingTop = getExtendedPaddingTop(); if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { paddingTop += getVerticalOffset(false); } r.offset(paddingLeft, paddingTop); int paddingBottom = getExtendedPaddingBottom(); r.bottom += paddingBottom; } /** * Return the number of lines of text, or 0 if the internal Layout has not * been built. */ public int getLineCount() { return mLayout != null ? mLayout.getLineCount() : 0; } /** * Return the baseline for the specified line (0...getLineCount() - 1) * If bounds is not null, return the top, left, right, bottom extents * of the specified line in it. If the internal Layout has not been built, * return 0 and set bounds to (0, 0, 0, 0) * * @param line which line to examine (0..getLineCount() - 1) * @param bounds Optional. If not null, it returns the extent of the line * @return the Y-coordinate of the baseline */ public int getLineBounds(int line, Rect bounds) { if (mLayout == null) { if (bounds != null) { bounds.set(0, 0, 0, 0); } return 0; } else { int baseline = mLayout.getLineBounds(line, bounds); int voffset = getExtendedPaddingTop(); if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset += getVerticalOffset(true); } if (bounds != null) { bounds.offset(getCompoundPaddingLeft(), voffset); } return baseline + voffset; } } @Override public int getBaseline() { if (mLayout == null) { return super.getBaseline(); } int voffset = 0; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset = getVerticalOffset(true); } if (isLayoutModeOptical(mParent)) { voffset -= getOpticalInsets().top; } return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); } /** * @hide */ @Override protected int getFadeTop(boolean offsetRequired) { if (mLayout == null) return 0; int voffset = 0; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { voffset = getVerticalOffset(true); } if (offsetRequired) voffset += getTopPaddingOffset(); return getExtendedPaddingTop() + voffset; } /** * @hide */ @Override protected int getFadeHeight(boolean offsetRequired) { return mLayout != null ? mLayout.getHeight() : 0; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { boolean isInSelectionMode = mEditor != null && mEditor.mSelectionActionMode != null; if (isInSelectionMode) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.handleUpEvent(event); } if (event.isTracking() && !event.isCanceled()) { stopSelectionActionMode(); return true; } } } } return super.onKeyPreIme(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { int which = doKeyDown(keyCode, event, null); if (which == 0) { return super.onKeyDown(keyCode, event); } return true; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); int which = doKeyDown(keyCode, down, event); if (which == 0) { // Go through default dispatching. return super.onKeyMultiple(keyCode, repeatCount, event); } if (which == -1) { // Consumed the whole thing. return true; } repeatCount--; // We are going to dispatch the remaining events to either the input // or movement method. To do this, we will just send a repeated stream // of down and up events until we have done the complete repeatCount. // It would be nice if those interfaces had an onKeyMultiple() method, // but adding that is a more complicated change. KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); if (which == 1) { // mEditor and mEditor.mInput are not null from doKeyDown mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up); while (--repeatCount > 0) { mEditor.mKeyListener.onKeyDown(this, (Editable) mText, keyCode, down); mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up); } hideErrorIfUnchanged(); } else if (which == 2) { // mMovement is not null from doKeyDown mMovement.onKeyUp(this, (Spannable) mText, keyCode, up); while (--repeatCount > 0) { mMovement.onKeyDown(this, (Spannable) mText, keyCode, down); mMovement.onKeyUp(this, (Spannable) mText, keyCode, up); } } return true; } /** * Returns true if pressing ENTER in this field advances focus instead * of inserting the character. This is true mostly in single-line fields, * but also in mail addresses and subjects which will display on multiple * lines but where it doesn't make sense to insert newlines. */ private boolean shouldAdvanceFocusOnEnter() { if (getKeyListener() == null) { return false; } if (mSingleLine) { return true; } if (mEditor != null && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { return true; } } return false; } /** * Returns true if pressing TAB in this field advances focus instead * of inserting the character. Insert tabs only in multi-line editors. */ private boolean shouldAdvanceFocusOnTab() { if (getKeyListener() != null && !mSingleLine && mEditor != null && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { return false; } } return true; } private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { if (!isEnabled()) { return 0; } // If this is the initial keydown, we don't want to prevent a movement away from this view. // While this shouldn't be necessary because any time we're preventing default movement we // should be restricting the focus to remain within this view, thus we'll also receive // the key up event, occasionally key up events will get dropped and we don't want to // prevent the user from traversing out of this on the next key down. if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { mPreventDefaultMovement = false; } switch (keyCode) { case KeyEvent.KEYCODE_ENTER: if (event.hasNoModifiers()) { // When mInputContentType is set, we know that we are // running in a "modern" cupcake environment, so don't need // to worry about the application trying to capture // enter key events. if (mEditor != null && mEditor.mInputContentType != null) { // If there is an action listener, given them a // chance to consume the event. if (mEditor.mInputContentType.onEditorActionListener != null && mEditor.mInputContentType.onEditorActionListener.onEditorAction(this, EditorInfo.IME_NULL, event)) { mEditor.mInputContentType.enterDown = true; // We are consuming the enter key for them. return -1; } } // If our editor should move focus when enter is pressed, or // this is a generated event from an IME action button, then // don't let it be inserted into the text. if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 || shouldAdvanceFocusOnEnter()) { if (hasOnClickListeners()) { return 0; } return -1; } } break; case KeyEvent.KEYCODE_DPAD_CENTER: if (event.hasNoModifiers()) { if (shouldAdvanceFocusOnEnter()) { return 0; } } break; case KeyEvent.KEYCODE_TAB: if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { if (shouldAdvanceFocusOnTab()) { return 0; } } break; // Has to be done on key down (and not on key up) to correctly be intercepted. case KeyEvent.KEYCODE_BACK: if (mEditor != null && mEditor.mSelectionActionMode != null) { stopSelectionActionMode(); return -1; } break; } if (mEditor != null && mEditor.mKeyListener != null) { boolean doDown = true; if (otherEvent != null) { try { beginBatchEdit(); final boolean handled = mEditor.mKeyListener.onKeyOther(this, (Editable) mText, otherEvent); hideErrorIfUnchanged(); doDown = false; if (handled) { return -1; } } catch (AbstractMethodError e) { // onKeyOther was added after 1.0, so if it isn't // implemented we need to try to dispatch as a regular down. } finally { endBatchEdit(); } } if (doDown) { beginBatchEdit(); final boolean handled = mEditor.mKeyListener.onKeyDown(this, (Editable) mText, keyCode, event); endBatchEdit(); hideErrorIfUnchanged(); if (handled) return 1; } } // bug 650865: sometimes we get a key event before a layout. // don't try to move around if we don't know the layout. if (mMovement != null && mLayout != null) { boolean doDown = true; if (otherEvent != null) { try { boolean handled = mMovement.onKeyOther(this, (Spannable) mText, otherEvent); doDown = false; if (handled) { return -1; } } catch (AbstractMethodError e) { // onKeyOther was added after 1.0, so if it isn't // implemented we need to try to dispatch as a regular down. } } if (doDown) { if (mMovement.onKeyDown(this, (Spannable) mText, keyCode, event)) { if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { mPreventDefaultMovement = true; } return 2; } } } return mPreventDefaultMovement && !KeyEvent.isModifierKey(keyCode) ? -1 : 0; } /** * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} * can be recorded. * * @hide */ public void resetErrorChangedFlag() { /* * Keep track of what the error was before doing the input * so that if an input filter changed the error, we leave * that error showing. Otherwise, we take down whatever * error was showing when the user types something. */ if (mEditor != null) mEditor.mErrorWasChanged = false; } /** * @hide */ public void hideErrorIfUnchanged() { if (mEditor != null && mEditor.mError != null && !mEditor.mErrorWasChanged) { setError(null, null); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (!isEnabled()) { return super.onKeyUp(keyCode, event); } if (!KeyEvent.isModifierKey(keyCode)) { mPreventDefaultMovement = false; } switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: if (event.hasNoModifiers()) { /* * If there is a click listener, just call through to * super, which will invoke it. * * If there isn't a click listener, try to show the soft * input method. (It will also * call performClick(), but that won't do anything in * this case.) */ if (!hasOnClickListeners()) { if (mMovement != null && mText instanceof Editable && mLayout != null && onCheckIsTextEditor()) { InputMethodManager imm = InputMethodManager.peekInstance(); viewClicked(imm); if (imm != null && getShowSoftInputOnFocus()) { imm.showSoftInput(this, 0); } } } } return super.onKeyUp(keyCode, event); case KeyEvent.KEYCODE_ENTER: if (event.hasNoModifiers()) { if (mEditor != null && mEditor.mInputContentType != null && mEditor.mInputContentType.onEditorActionListener != null && mEditor.mInputContentType.enterDown) { mEditor.mInputContentType.enterDown = false; if (mEditor.mInputContentType.onEditorActionListener.onEditorAction(this, EditorInfo.IME_NULL, event)) { return true; } } if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 || shouldAdvanceFocusOnEnter()) { /* * If there is a click listener, just call through to * super, which will invoke it. * * If there isn't a click listener, try to advance focus, * but still call through to super, which will reset the * pressed state and longpress state. (It will also * call performClick(), but that won't do anything in * this case.) */ if (!hasOnClickListeners()) { View v = focusSearch(FOCUS_DOWN); if (v != null) { if (!v.requestFocus(FOCUS_DOWN)) { throw new IllegalStateException("focus search returned a view " + "that wasn't able to take focus!"); } /* * Return true because we handled the key; super * will return false because there was no click * listener. */ super.onKeyUp(keyCode, event); return true; } else if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0) { // No target for next focus, but make sure the IME // if this came from it. InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null && imm.isActive(this)) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } } } } return super.onKeyUp(keyCode, event); } break; } if (mEditor != null && mEditor.mKeyListener != null) if (mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event)) return true; if (mMovement != null && mLayout != null) if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) return true; return super.onKeyUp(keyCode, event); } @Override public boolean onCheckIsTextEditor() { return mEditor != null && mEditor.mInputType != EditorInfo.TYPE_NULL; } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { if (onCheckIsTextEditor() && isEnabled()) { mEditor.createInputMethodStateIfNeeded(); outAttrs.inputType = getInputType(); if (mEditor.mInputContentType != null) { outAttrs.imeOptions = mEditor.mInputContentType.imeOptions; outAttrs.privateImeOptions = mEditor.mInputContentType.privateImeOptions; outAttrs.actionLabel = mEditor.mInputContentType.imeActionLabel; outAttrs.actionId = mEditor.mInputContentType.imeActionId; outAttrs.extras = mEditor.mInputContentType.extras; } else { outAttrs.imeOptions = EditorInfo.IME_NULL; } if (focusSearch(FOCUS_DOWN) != null) { outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; } if (focusSearch(FOCUS_UP) != null) { outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; } if ((outAttrs.imeOptions & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_UNSPECIFIED) { if ((outAttrs.imeOptions & EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { // An action has not been set, but the enter key will move to // the next focus, so set the action to that. outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; } else { // An action has not been set, and there is no focus to move // to, so let's just supply a "done" action. outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; } if (!shouldAdvanceFocusOnEnter()) { outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; } } if (isMultilineInputType(outAttrs.inputType)) { // Multi-line text editors should always show an enter key. outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; } outAttrs.hintText = mHint; if (mText instanceof Editable) { //露面了,是 EditableInputConnection, textView作为参数传入 InputConnection ic = new EditableInputConnection(this); outAttrs.initialSelStart = getSelectionStart(); outAttrs.initialSelEnd = getSelectionEnd(); outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType()); return ic; } } return null; } /** * If this TextView contains editable content, extract a portion of it * based on the information in <var>request</var> in to <var>outText</var>. * * @return Returns true if the text was successfully extracted, else false. */ public boolean extractText(ExtractedTextRequest request, ExtractedText outText) { createEditorIfNeeded(); return mEditor.extractText(request, outText); } /** * This is used to remove all style-impacting spans from text before new * extracted text is being replaced into it, so that we don't have any * lingering spans applied during the replace. */ static void removeParcelableSpans(Spannable spannable, int start, int end) { Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); int i = spans.length; while (i > 0) { i--; spannable.removeSpan(spans[i]); } } /** * Apply to this text view the given extracted text, as previously * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. */ public void setExtractedText(ExtractedText text) { Editable content = getEditableText(); if (text.text != null) { if (content == null) { setText(text.text, BufferType.EDITABLE); } else if (text.partialStartOffset < 0) { removeParcelableSpans(content, 0, content.length()); content.replace(0, content.length(), text.text); } else { final int N = content.length(); int start = text.partialStartOffset; if (start > N) start = N; int end = text.partialEndOffset; if (end > N) end = N; removeParcelableSpans(content, start, end); content.replace(start, end, text.text); } } // Now set the selection position... make sure it is in range, to // avoid crashes. If this is a partial update, it is possible that // the underlying text may have changed, causing us problems here. // Also we just don't want to trust clients to do the right thing. Spannable sp = (Spannable) getText(); final int N = sp.length(); int start = text.selectionStart; if (start < 0) start = 0; else if (start > N) start = N; int end = text.selectionEnd; if (end < 0) end = 0; else if (end > N) end = N; Selection.setSelection(sp, start, end); // Finally, update the selection mode. if ((text.flags & ExtractedText.FLAG_SELECTING) != 0) { MetaKeyKeyListener.startSelecting(this, sp); } else { MetaKeyKeyListener.stopSelecting(this, sp); } } /** * @hide */ public void setExtracting(ExtractedTextRequest req) { if (mEditor.mInputMethodState != null) { mEditor.mInputMethodState.mExtractedTextRequest = req; } // This would stop a possible selection mode, but no such mode is started in case // extracted mode will start. Some text is selected though, and will trigger an action mode // in the extracted view. mEditor.hideControllers(); } /** * Called by the framework in response to a text completion from * the current input method, provided by it calling * {@link InputConnection#commitCompletion * InputConnection.commitCompletion()}. The default implementation does * nothing; text views that are supporting auto-completion should override * this to do their desired behavior. * * @param text The auto complete text the user has selected. */ public void onCommitCompletion(CompletionInfo text) { // intentionally empty } /** * Called by the framework in response to a text auto-correction (such as fixing a typo using a * a dictionnary) from the current input method, provided by it calling * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default * implementation flashes the background of the corrected word to provide feedback to the user. * * @param info The auto correct info about the text that was corrected. */ public void onCommitCorrection(CorrectionInfo info) { if (mEditor != null) mEditor.onCommitCorrection(info); } public void beginBatchEdit() { if (mEditor != null) mEditor.beginBatchEdit(); } public void endBatchEdit() { if (mEditor != null) mEditor.endBatchEdit(); } /** * Called by the framework in response to a request to begin a batch * of edit operations through a call to link {@link #beginBatchEdit()}. */ public void onBeginBatchEdit() { // intentionally empty } /** * Called by the framework in response to a request to end a batch * of edit operations through a call to link {@link #endBatchEdit}. */ public void onEndBatchEdit() { // intentionally empty } /** * Called by the framework in response to a private command from the * current method, provided by it calling * {@link InputConnection#performPrivateCommand * InputConnection.performPrivateCommand()}. * * @param action The action name of the command. * @param data Any additional data for the command. This may be null. * @return Return true if you handled the command, else false. */ public boolean onPrivateIMECommand(String action, Bundle data) { return false; } private void nullLayouts() { if (mLayout instanceof BoringLayout && mSavedLayout == null) { mSavedLayout = (BoringLayout) mLayout; } if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { mSavedHintLayout = (BoringLayout) mHintLayout; } mSavedMarqueeModeLayout = mLayout = mHintLayout = null; mBoring = mHintBoring = null; // Since it depends on the value of mLayout if (mEditor != null) mEditor.prepareCursorControllers(); } /** * Make a new Layout based on the already-measured size of the view, * on the assumption that it was measured correctly at some point. */ private void assumeLayout() { int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); if (width < 1) { width = 0; } int physicalWidth = width; if (mHorizontallyScrolling) { width = VERY_WIDE; } makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, physicalWidth, false); } private Layout.Alignment getLayoutAlignment() { Layout.Alignment alignment; switch (getTextAlignment()) { case TEXT_ALIGNMENT_GRAVITY: switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) { case Gravity.START: alignment = Layout.Alignment.ALIGN_NORMAL; break; case Gravity.END: alignment = Layout.Alignment.ALIGN_OPPOSITE; break; case Gravity.LEFT: alignment = Layout.Alignment.ALIGN_LEFT; break; case Gravity.RIGHT: alignment = Layout.Alignment.ALIGN_RIGHT; break; case Gravity.CENTER_HORIZONTAL: alignment = Layout.Alignment.ALIGN_CENTER; break; default: alignment = Layout.Alignment.ALIGN_NORMAL; break; } break; case TEXT_ALIGNMENT_TEXT_START: alignment = Layout.Alignment.ALIGN_NORMAL; break; case TEXT_ALIGNMENT_TEXT_END: alignment = Layout.Alignment.ALIGN_OPPOSITE; break; case TEXT_ALIGNMENT_CENTER: alignment = Layout.Alignment.ALIGN_CENTER; break; case TEXT_ALIGNMENT_VIEW_START: alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; break; case TEXT_ALIGNMENT_VIEW_END: alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; break; case TEXT_ALIGNMENT_INHERIT: // This should never happen as we have already resolved the text alignment // but better safe than sorry so we just fall through default: alignment = Layout.Alignment.ALIGN_NORMAL; break; } return alignment; } /** * The width passed in is now the desired layout width, * not the full view width with padding. * {@hide} */ protected void makeNewLayout(int wantWidth, int hintWidth, BoringLayout.Metrics boring, BoringLayout.Metrics hintBoring, int ellipsisWidth, boolean bringIntoView) { stopMarquee(); // Update "old" cached values mOldMaximum = mMaximum; mOldMaxMode = mMaxMode; mHighlightPathBogus = true; if (wantWidth < 0) { wantWidth = 0; } if (hintWidth < 0) { hintWidth = 0; } Layout.Alignment alignment = getLayoutAlignment(); final boolean testDirChange = mSingleLine && mLayout != null && (alignment == Layout.Alignment.ALIGN_NORMAL || alignment == Layout.Alignment.ALIGN_OPPOSITE); int oldDir = 0; if (testDirChange) oldDir = mLayout.getParagraphDirection(0); boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null; final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE && mMarqueeFadeMode != MARQUEE_FADE_NORMAL; TruncateAt effectiveEllipsize = mEllipsize; if (mEllipsize == TruncateAt.MARQUEE && mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { effectiveEllipsize = TruncateAt.END_SMALL; } if (mTextDir == null) { mTextDir = getTextDirectionHeuristic(); } mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, effectiveEllipsize, effectiveEllipsize == mEllipsize); if (switchEllipsize) { TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ? TruncateAt.END : TruncateAt.MARQUEE; mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize); } shouldEllipsize = mEllipsize != null; mHintLayout = null; if (mHint != null) { if (shouldEllipsize) hintWidth = wantWidth; if (hintBoring == UNKNOWN_BORING) { hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring); if (hintBoring != null) { mHintBoring = hintBoring; } } if (hintBoring != null) { if (hintBoring.width <= hintWidth && (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { if (mSavedHintLayout != null) { mHintLayout = mSavedHintLayout. replaceOrMake(mHint, mTextPaint, hintWidth, alignment, mSpacingMult, mSpacingAdd, hintBoring, mIncludePad); } else { mHintLayout = BoringLayout.make(mHint, mTextPaint, hintWidth, alignment, mSpacingMult, mSpacingAdd, hintBoring, mIncludePad); } mSavedHintLayout = (BoringLayout) mHintLayout; } else if (shouldEllipsize && hintBoring.width <= hintWidth) { if (mSavedHintLayout != null) { mHintLayout = mSavedHintLayout. replaceOrMake(mHint, mTextPaint, hintWidth, alignment, mSpacingMult, mSpacingAdd, hintBoring, mIncludePad, mEllipsize, ellipsisWidth); } else { mHintLayout = BoringLayout.make(mHint, mTextPaint, hintWidth, alignment, mSpacingMult, mSpacingAdd, hintBoring, mIncludePad, mEllipsize, ellipsisWidth); } } else if (shouldEllipsize) { mHintLayout = new StaticLayout(mHint, 0, mHint.length(), mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad, mEllipsize, ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); } else { mHintLayout = new StaticLayout(mHint, mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad); } } else if (shouldEllipsize) { mHintLayout = new StaticLayout(mHint, 0, mHint.length(), mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad, mEllipsize, ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); } else { mHintLayout = new StaticLayout(mHint, mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad); } } if (bringIntoView || (testDirChange && oldDir != mLayout.getParagraphDirection(0))) { registerForPreDraw(); } if (mEllipsize == TruncateAt.MARQUEE) { if (!compressText(ellipsisWidth)) { final int height = mLayoutParams.height; // If the size of the view does not depend on the size of the text, try to // start the marquee immediately if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { startMarquee(); } else { // Defer the start of the marquee until we know our width (see setFrame()) mRestartMarquee = true; } } } // CursorControllers need a non-null mLayout if (mEditor != null) mEditor.prepareCursorControllers(); } private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth, Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize, boolean useSaved) { Layout result = null; if (mText instanceof Spannable) { result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad, getKeyListener() == null ? effectiveEllipsize : null, ellipsisWidth); } else { if (boring == UNKNOWN_BORING) { boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); if (boring != null) { mBoring = boring; } } if (boring != null) { if (boring.width <= wantWidth && (effectiveEllipsize == null || boring.width <= ellipsisWidth)) { if (useSaved && mSavedLayout != null) { result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, wantWidth, alignment, mSpacingMult, mSpacingAdd, boring, mIncludePad); } else { result = BoringLayout.make(mTransformed, mTextPaint, wantWidth, alignment, mSpacingMult, mSpacingAdd, boring, mIncludePad); } if (useSaved) { mSavedLayout = (BoringLayout) result; } } else if (shouldEllipsize && boring.width <= wantWidth) { if (useSaved && mSavedLayout != null) { result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, wantWidth, alignment, mSpacingMult, mSpacingAdd, boring, mIncludePad, effectiveEllipsize, ellipsisWidth); } else { result = BoringLayout.make(mTransformed, mTextPaint, wantWidth, alignment, mSpacingMult, mSpacingAdd, boring, mIncludePad, effectiveEllipsize, ellipsisWidth); } } else if (shouldEllipsize) { result = new StaticLayout(mTransformed, 0, mTransformed.length(), mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad, effectiveEllipsize, ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); } else { result = new StaticLayout(mTransformed, mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad); } } else if (shouldEllipsize) { result = new StaticLayout(mTransformed, 0, mTransformed.length(), mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad, effectiveEllipsize, ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); } else { result = new StaticLayout(mTransformed, mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, mIncludePad); } } return result; } private boolean compressText(float width) { if (isHardwareAccelerated()) return false; // Only compress the text if it hasn't been compressed by the previous pass if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && mTextPaint.getTextScaleX() == 1.0f) { final float textWidth = mLayout.getLineWidth(0); final float overflow = (textWidth + 1.0f - width) / width; if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); post(new Runnable() { public void run() { requestLayout(); } }); return true; } } return false; } private static int desired(Layout layout) { int n = layout.getLineCount(); CharSequence text = layout.getText(); float max = 0; // if any line was wrapped, we can't use it. // but it's ok for the last line not to have a newline for (int i = 0; i < n - 1; i++) { if (text.charAt(layout.getLineEnd(i) - 1) != '\n') return -1; } for (int i = 0; i < n; i++) { max = Math.max(max, layout.getLineWidth(i)); } return (int) FloatMath.ceil(max); } /** * Set whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * The default is true. * * @attr ref android.R.styleable#TextView_includeFontPadding * @see #getIncludeFontPadding() */ public void setIncludeFontPadding(boolean includepad) { if (mIncludePad != includepad) { mIncludePad = includepad; if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Gets whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * * @attr ref android.R.styleable#TextView_includeFontPadding * @see #setIncludeFontPadding(boolean) */ public boolean getIncludeFontPadding() { return mIncludePad; } private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; BoringLayout.Metrics boring = UNKNOWN_BORING; BoringLayout.Metrics hintBoring = UNKNOWN_BORING; if (mTextDir == null) { mTextDir = getTextDirectionHeuristic(); } int des = -1; boolean fromexisting = false; if (widthMode == MeasureSpec.EXACTLY) { // Parent has told us how big to be. So be it. width = widthSize; } else { if (mLayout != null && mEllipsize == null) { des = desired(mLayout); } if (des < 0) { boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); if (boring != null) { mBoring = boring; } } else { fromexisting = true; } if (boring == null || boring == UNKNOWN_BORING) { if (des < 0) { des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); } width = des; } else { width = boring.width; } final Drawables dr = mDrawables; if (dr != null) { width = Math.max(width, dr.mDrawableWidthTop); width = Math.max(width, dr.mDrawableWidthBottom); } if (mHint != null) { int hintDes = -1; int hintWidth; if (mHintLayout != null && mEllipsize == null) { hintDes = desired(mHintLayout); } if (hintDes < 0) { hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring); if (hintBoring != null) { mHintBoring = hintBoring; } } if (hintBoring == null || hintBoring == UNKNOWN_BORING) { if (hintDes < 0) { hintDes = (int) FloatMath.ceil(Layout.getDesiredWidth(mHint, mTextPaint)); } hintWidth = hintDes; } else { hintWidth = hintBoring.width; } if (hintWidth > width) { width = hintWidth; } } width += getCompoundPaddingLeft() + getCompoundPaddingRight(); if (mMaxWidthMode == EMS) { width = Math.min(width, mMaxWidth * getLineHeight()); } else { width = Math.min(width, mMaxWidth); } if (mMinWidthMode == EMS) { width = Math.max(width, mMinWidth * getLineHeight()); } else { width = Math.max(width, mMinWidth); } // Check against our minimum width width = Math.max(width, getSuggestedMinimumWidth()); if (widthMode == MeasureSpec.AT_MOST) { width = Math.min(widthSize, width); } } int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); int unpaddedWidth = want; if (mHorizontallyScrolling) want = VERY_WIDE; int hintWant = want; int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth(); if (mLayout == null) { makeNewLayout(want, hintWant, boring, hintBoring, width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); } else { final boolean layoutChanged = (mLayout.getWidth() != want) || (hintWidth != hintWant) || (mLayout.getEllipsizedWidth() != width - getCompoundPaddingLeft() - getCompoundPaddingRight()); final boolean widthChanged = (mHint == null) && (mEllipsize == null) && (want > mLayout.getWidth()) && (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want)); final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum); if (layoutChanged || maximumChanged) { if (!maximumChanged && widthChanged) { mLayout.increaseWidthTo(want); } else { makeNewLayout(want, hintWant, boring, hintBoring, width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); } } else { // Nothing has changed } } if (heightMode == MeasureSpec.EXACTLY) { // Parent has told us how big to be. So be it. height = heightSize; mDesiredHeightAtMeasure = -1; } else { int desired = getDesiredHeight(); height = desired; mDesiredHeightAtMeasure = desired; if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(desired, heightSize); } } int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); } /* * We didn't let makeNewLayout() register to bring the cursor into view, * so do it here if there is any possibility that it is needed. */ if (mMovement != null || mLayout.getWidth() > unpaddedWidth || mLayout.getHeight() > unpaddedHeight) { registerForPreDraw(); } else { scrollTo(0, 0); } setMeasuredDimension(width, height); } private int getDesiredHeight() { return Math.max(getDesiredHeight(mLayout, true), getDesiredHeight(mHintLayout, mEllipsize != null)); } private int getDesiredHeight(Layout layout, boolean cap) { if (layout == null) { return 0; } int linecount = layout.getLineCount(); int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); int desired = layout.getLineTop(linecount); final Drawables dr = mDrawables; if (dr != null) { desired = Math.max(desired, dr.mDrawableHeightLeft); desired = Math.max(desired, dr.mDrawableHeightRight); } desired += pad; if (mMaxMode == LINES) { /* * Don't cap the hint to a certain number of lines. * (Do cap it, though, if we have a maximum pixel height.) */ if (cap) { if (linecount > mMaximum) { desired = layout.getLineTop(mMaximum); if (dr != null) { desired = Math.max(desired, dr.mDrawableHeightLeft); desired = Math.max(desired, dr.mDrawableHeightRight); } desired += pad; linecount = mMaximum; } } } else { desired = Math.min(desired, mMaximum); } if (mMinMode == LINES) { if (linecount < mMinimum) { desired += getLineHeight() * (mMinimum - linecount); } } else { desired = Math.max(desired, mMinimum); } // Check against our minimum height desired = Math.max(desired, getSuggestedMinimumHeight()); return desired; } /** * Check whether a change to the existing text layout requires a * new view layout. */ private void checkForResize() { boolean sizeChanged = false; if (mLayout != null) { // Check if our width changed if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { sizeChanged = true; invalidate(); } // Check if our height changed if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { int desiredHeight = getDesiredHeight(); if (desiredHeight != this.getHeight()) { sizeChanged = true; } } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { if (mDesiredHeightAtMeasure >= 0) { int desiredHeight = getDesiredHeight(); if (desiredHeight != mDesiredHeightAtMeasure) { sizeChanged = true; } } } } if (sizeChanged) { requestLayout(); // caller will have already invalidated } } /** * Check whether entirely new text requires a new view layout * or merely a new text layout. */ private void checkForRelayout() { // If we have a fixed width, we can just swap in a new text layout // if the text height stays the same or if the view height is fixed. if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && (mHint == null || mHintLayout != null) && (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { // Static width, so try making a new text layout. int oldht = mLayout.getHeight(); int want = mLayout.getWidth(); int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); /* * No need to bring the text into view, since the size is not * changing (unless we do the requestLayout(), in which case it * will happen at measure). */ makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); if (mEllipsize != TruncateAt.MARQUEE) { // In a fixed-height view, so use our new text layout. if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && mLayoutParams.height != LayoutParams.MATCH_PARENT) { invalidate(); return; } // Dynamic height, but height has stayed the same, // so use our new text layout. if (mLayout.getHeight() == oldht && (mHintLayout == null || mHintLayout.getHeight() == oldht)) { invalidate(); return; } } // We lose: the height has changed and we have a dynamic height. // Request a new view layout using our new text layout. requestLayout(); invalidate(); } else { // Dynamic width, so we have no choice but to request a new // view layout with a new text layout. nullLayouts(); requestLayout(); invalidate(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mDeferScroll >= 0) { int curs = mDeferScroll; mDeferScroll = -1; bringPointIntoView(Math.min(curs, mText.length())); } } private boolean isShowingHint() { return TextUtils.isEmpty(mText) && !TextUtils.isEmpty(mHint); } /** * Returns true if anything changed. */ private boolean bringTextIntoView() { Layout layout = isShowingHint() ? mHintLayout : mLayout; int line = 0; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { line = layout.getLineCount() - 1; } Layout.Alignment a = layout.getParagraphAlignment(line); int dir = layout.getParagraphDirection(line); int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); int ht = layout.getHeight(); int scrollx, scrolly; // Convert to left, center, or right alignment. if (a == Layout.Alignment.ALIGN_NORMAL) { a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; } else if (a == Layout.Alignment.ALIGN_OPPOSITE) { a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; } if (a == Layout.Alignment.ALIGN_CENTER) { /* * Keep centered if possible, or, if it is too wide to fit, * keep leading edge in view. */ int left = (int) FloatMath.floor(layout.getLineLeft(line)); int right = (int) FloatMath.ceil(layout.getLineRight(line)); if (right - left < hspace) { scrollx = (right + left) / 2 - hspace / 2; } else { if (dir < 0) { scrollx = right - hspace; } else { scrollx = left; } } } else if (a == Layout.Alignment.ALIGN_RIGHT) { int right = (int) FloatMath.ceil(layout.getLineRight(line)); scrollx = right - hspace; } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) scrollx = (int) FloatMath.floor(layout.getLineLeft(line)); } if (ht < vspace) { scrolly = 0; } else { if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { scrolly = ht - vspace; } else { scrolly = 0; } } if (scrollx != mScrollX || scrolly != mScrollY) { scrollTo(scrollx, scrolly); return true; } else { return false; } } /** * Move the point, specified by the offset, into the view if it is needed. * This has to be called after layout. Returns true if anything changed. */ public boolean bringPointIntoView(int offset) { if (isLayoutRequested()) { mDeferScroll = offset; return false; } boolean changed = false; Layout layout = isShowingHint() ? mHintLayout : mLayout; if (layout == null) return changed; int line = layout.getLineForOffset(offset); int grav; switch (layout.getParagraphAlignment(line)) { case ALIGN_LEFT: grav = 1; break; case ALIGN_RIGHT: grav = -1; break; case ALIGN_NORMAL: grav = layout.getParagraphDirection(line); break; case ALIGN_OPPOSITE: grav = -layout.getParagraphDirection(line); break; case ALIGN_CENTER: default: grav = 0; break; } // We only want to clamp the cursor to fit within the layout width // in left-to-right modes, because in a right to left alignment, // we want to scroll to keep the line-right on the screen, as other // lines are likely to have text flush with the right margin, which // we want to keep visible. // A better long-term solution would probably be to measure both // the full line and a blank-trimmed version, and, for example, use // the latter measurement for centering and right alignment, but for // the time being we only implement the cursor clamping in left to // right where it is most likely to be annoying. final boolean clamped = grav > 0; // FIXME: Is it okay to truncate this, or should we round? final int x = (int) layout.getPrimaryHorizontal(offset, clamped); final int top = layout.getLineTop(line); final int bottom = layout.getLineTop(line + 1); int left = (int) FloatMath.floor(layout.getLineLeft(line)); int right = (int) FloatMath.ceil(layout.getLineRight(line)); int ht = layout.getHeight(); int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); if (!mHorizontallyScrolling && right - left > hspace && right > x) { // If cursor has been clamped, make sure we don't scroll. right = Math.max(x, left + hspace); } int hslack = (bottom - top) / 2; int vslack = hslack; if (vslack > vspace / 4) vslack = vspace / 4; if (hslack > hspace / 4) hslack = hspace / 4; int hs = mScrollX; int vs = mScrollY; if (top - vs < vslack) vs = top - vslack; if (bottom - vs > vspace - vslack) vs = bottom - (vspace - vslack); if (ht - vs < vspace) vs = ht - vspace; if (0 - vs > 0) vs = 0; if (grav != 0) { if (x - hs < hslack) { hs = x - hslack; } if (x - hs > hspace - hslack) { hs = x - (hspace - hslack); } } if (grav < 0) { if (left - hs > 0) hs = left; if (right - hs < hspace) hs = right - hspace; } else if (grav > 0) { if (right - hs < hspace) hs = right - hspace; if (left - hs > 0) hs = left; } else /* grav == 0 */ { if (right - left <= hspace) { /* * If the entire text fits, center it exactly. */ hs = left - (hspace - (right - left)) / 2; } else if (x > right - hslack) { /* * If we are near the right edge, keep the right edge * at the edge of the view. */ hs = right - hspace; } else if (x < left + hslack) { /* * If we are near the left edge, keep the left edge * at the edge of the view. */ hs = left; } else if (left > hs) { /* * Is there whitespace visible at the left? Fix it if so. */ hs = left; } else if (right < hs + hspace) { /* * Is there whitespace visible at the right? Fix it if so. */ hs = right - hspace; } else { /* * Otherwise, float as needed. */ if (x - hs < hslack) { hs = x - hslack; } if (x - hs > hspace - hslack) { hs = x - (hspace - hslack); } } } if (hs != mScrollX || vs != mScrollY) { if (mScroller == null) { scrollTo(hs, vs); } else { long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; int dx = hs - mScrollX; int dy = vs - mScrollY; if (duration > ANIMATED_SCROLL_GAP) { mScroller.startScroll(mScrollX, mScrollY, dx, dy); awakenScrollBars(mScroller.getDuration()); invalidate(); } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } changed = true; } if (isFocused()) { // This offsets because getInterestingRect() is in terms of viewport coordinates, but // requestRectangleOnScreen() is in terms of content coordinates. // The offsets here are to ensure the rectangle we are using is // within our view bounds, in case the cursor is on the far left // or right. If it isn't withing the bounds, then this request // will be ignored. if (mTempRect == null) mTempRect = new Rect(); mTempRect.set(x - 2, top, x + 2, bottom); getInterestingRect(mTempRect, line); mTempRect.offset(mScrollX, mScrollY); if (requestRectangleOnScreen(mTempRect)) { changed = true; } } return changed; } /** * Move the cursor, if needed, so that it is at an offset that is visible * to the user. This will not move the cursor if it represents more than * one character (a selection range). This will only work if the * TextView contains spannable text; otherwise it will do nothing. * * @return True if the cursor was actually moved, false otherwise. */ public boolean moveCursorToVisibleOffset() { if (!(mText instanceof Spannable)) { return false; } int start = getSelectionStart(); int end = getSelectionEnd(); if (start != end) { return false; } // First: make sure the line is visible on screen: int line = mLayout.getLineForOffset(start); final int top = mLayout.getLineTop(line); final int bottom = mLayout.getLineTop(line + 1); final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); int vslack = (bottom - top) / 2; if (vslack > vspace / 4) vslack = vspace / 4; final int vs = mScrollY; if (top < (vs + vslack)) { line = mLayout.getLineForVertical(vs + vslack + (bottom - top)); } else if (bottom > (vspace + vs - vslack)) { line = mLayout.getLineForVertical(vspace + vs - vslack - (bottom - top)); } // Next: make sure the character is visible on screen: final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); final int hs = mScrollX; final int leftChar = mLayout.getOffsetForHorizontal(line, hs); final int rightChar = mLayout.getOffsetForHorizontal(line, hspace + hs); // line might contain bidirectional text final int lowChar = leftChar < rightChar ? leftChar : rightChar; final int highChar = leftChar > rightChar ? leftChar : rightChar; int newStart = start; if (newStart < lowChar) { newStart = lowChar; } else if (newStart > highChar) { newStart = highChar; } if (newStart != start) { Selection.setSelection((Spannable) mText, newStart); return true; } return false; } @Override public void computeScroll() { if (mScroller != null) { if (mScroller.computeScrollOffset()) { mScrollX = mScroller.getCurrX(); mScrollY = mScroller.getCurrY(); invalidateParentCaches(); postInvalidate(); // So we draw again } } } private void getInterestingRect(Rect r, int line) { convertFromViewportToContentCoordinates(r); // Rectangle can can be expanded on first and last line to take // padding into account. // TODO Take left/right padding into account too? if (line == 0) r.top -= getExtendedPaddingTop(); if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); } private void convertFromViewportToContentCoordinates(Rect r) { final int horizontalOffset = viewportToContentHorizontalOffset(); r.left += horizontalOffset; r.right += horizontalOffset; final int verticalOffset = viewportToContentVerticalOffset(); r.top += verticalOffset; r.bottom += verticalOffset; } int viewportToContentHorizontalOffset() { return getCompoundPaddingLeft() - mScrollX; } int viewportToContentVerticalOffset() { int offset = getExtendedPaddingTop() - mScrollY; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { offset += getVerticalOffset(false); } return offset; } @Override public void debug(int depth) { super.debug(depth); String output = debugIndent(depth); output += "frame={" + mLeft + ", " + mTop + ", " + mRight + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY + "} "; if (mText != null) { output += "mText=\"" + mText + "\" "; if (mLayout != null) { output += "mLayout width=" + mLayout.getWidth() + " height=" + mLayout.getHeight(); } } else { output += "mText=NULL"; } Log.d(VIEW_LOG_TAG, output); } /** * Convenience for {@link Selection#getSelectionStart}. */ @ViewDebug.ExportedProperty(category = "text") public int getSelectionStart() { return Selection.getSelectionStart(getText()); } /** * Convenience for {@link Selection#getSelectionEnd}. */ @ViewDebug.ExportedProperty(category = "text") public int getSelectionEnd() { return Selection.getSelectionEnd(getText()); } /** * Return true iff there is a selection inside this text view. */ public boolean hasSelection() { final int selectionStart = getSelectionStart(); final int selectionEnd = getSelectionEnd(); return selectionStart >= 0 && selectionStart != selectionEnd; } /** * Sets the properties of this field (lines, horizontally scrolling, * transformation method) to be for a single-line input. * * @attr ref android.R.styleable#TextView_singleLine */ public void setSingleLine() { setSingleLine(true); } /** * Sets the properties of this field to transform input to ALL CAPS * display. This may use a "small caps" formatting if available. * This setting will be ignored if this field is editable or selectable. * <p> * This call replaces the current transformation method. Disabling this * will not necessarily restore the previous behavior from before this * was enabled. * * @attr ref android.R.styleable#TextView_textAllCaps * @see #setTransformationMethod(TransformationMethod) */ public void setAllCaps(boolean allCaps) { if (allCaps) { setTransformationMethod(new AllCapsTransformationMethod(getContext())); } else { setTransformationMethod(null); } } /** * If true, sets the properties of this field (number of lines, horizontally scrolling, * transformation method) to be for a single-line input; if false, restores these to the default * conditions. * <p> * Note that the default conditions are not necessarily those that were in effect prior this * method, and you may want to reset these properties to your custom values. * * @attr ref android.R.styleable#TextView_singleLine */ @android.view.RemotableViewMethod public void setSingleLine(boolean singleLine) { // Could be used, but may break backward compatibility. // if (mSingleLine == singleLine) return; setInputTypeSingleLine(singleLine); applySingleLine(singleLine, true, true); } /** * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. * * @param singleLine */ private void setInputTypeSingleLine(boolean singleLine) { if (mEditor != null && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { if (singleLine) { mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } else { mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } } } private void applySingleLine(boolean singleLine, boolean applyTransformation, boolean changeMaxLines) { mSingleLine = singleLine; if (singleLine) { setLines(1); setHorizontallyScrolling(true); if (applyTransformation) { setTransformationMethod(SingleLineTransformationMethod.getInstance()); } } else { if (changeMaxLines) { setMaxLines(Integer.MAX_VALUE); } setHorizontallyScrolling(false); if (applyTransformation) { setTransformationMethod(null); } } } /** * Causes words in the text that are longer than the view is wide * to be ellipsized instead of broken in the middle. You may also * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} * to constrain the text to a single line. Use <code>null</code> * to turn off ellipsizing. * <p> * If {@link #setMaxLines} has been used to set two or more lines, * only {@link TruncateAt#END} and * {@link TruncateAt#MARQUEE} are supported * (other ellipsizing types will not do anything). * * @attr ref android.R.styleable#TextView_ellipsize */ public void setEllipsize(TruncateAt where) { // TruncateAt is an enum. != comparison is ok between these singleton objects. if (mEllipsize != where) { mEllipsize = where; if (mLayout != null) { nullLayouts(); requestLayout(); invalidate(); } } } /** * Sets how many times to repeat the marquee animation. Only applied if the * TextView has marquee enabled. Set to -1 to repeat indefinitely. * * @attr ref android.R.styleable#TextView_marqueeRepeatLimit * @see #getMarqueeRepeatLimit() */ public void setMarqueeRepeatLimit(int marqueeLimit) { mMarqueeRepeatLimit = marqueeLimit; } /** * Gets the number of times the marquee animation is repeated. Only meaningful if the * TextView has marquee enabled. * * @return the number of times the marquee animation is repeated. -1 if the animation * repeats indefinitely * @attr ref android.R.styleable#TextView_marqueeRepeatLimit * @see #setMarqueeRepeatLimit(int) */ public int getMarqueeRepeatLimit() { return mMarqueeRepeatLimit; } /** * Returns where, if anywhere, words that are longer than the view * is wide should be ellipsized. */ @ViewDebug.ExportedProperty public TruncateAt getEllipsize() { return mEllipsize; } /** * Set the TextView so that when it takes focus, all the text is * selected. * * @attr ref android.R.styleable#TextView_selectAllOnFocus */ @android.view.RemotableViewMethod public void setSelectAllOnFocus(boolean selectAllOnFocus) { createEditorIfNeeded(); mEditor.mSelectAllOnFocus = selectAllOnFocus; if (selectAllOnFocus && !(mText instanceof Spannable)) { setText(mText, BufferType.SPANNABLE); } } /** * Set whether the cursor is visible. The default is true. Note that this property only * makes sense for editable TextView. * * @attr ref android.R.styleable#TextView_cursorVisible * @see #isCursorVisible() */ @android.view.RemotableViewMethod public void setCursorVisible(boolean visible) { if (visible && mEditor == null) return; // visible is the default value with no edit data createEditorIfNeeded(); if (mEditor.mCursorVisible != visible) { mEditor.mCursorVisible = visible; invalidate(); mEditor.makeBlink(); // InsertionPointCursorController depends on mCursorVisible mEditor.prepareCursorControllers(); } } /** * @return whether or not the cursor is visible (assuming this TextView is editable) * @attr ref android.R.styleable#TextView_cursorVisible * @see #setCursorVisible(boolean) */ public boolean isCursorVisible() { // true is the default value return mEditor == null ? true : mEditor.mCursorVisible; } private boolean canMarquee() { int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); return width > 0 && (mLayout.getLineWidth(0) > width || (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null && mSavedMarqueeModeLayout.getLineWidth(0) > width)); } private void startMarquee() { // Do not ellipsize EditText if (getKeyListener() != null) return; if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { return; } if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && getLineCount() == 1 && canMarquee()) { if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE; final Layout tmp = mLayout; mLayout = mSavedMarqueeModeLayout; mSavedMarqueeModeLayout = tmp; setHorizontalFadingEdgeEnabled(true); requestLayout(); invalidate(); } if (mMarquee == null) mMarquee = new Marquee(this); mMarquee.start(mMarqueeRepeatLimit); } } private void stopMarquee() { if (mMarquee != null && !mMarquee.isStopped()) { mMarquee.stop(); } if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) { mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; final Layout tmp = mSavedMarqueeModeLayout; mSavedMarqueeModeLayout = mLayout; mLayout = tmp; setHorizontalFadingEdgeEnabled(false); requestLayout(); invalidate(); } } private void startStopMarquee(boolean start) { if (mEllipsize == TruncateAt.MARQUEE) { if (start) { startMarquee(); } else { stopMarquee(); } } } /** * This method is called when the text is changed, in case any subclasses * would like to know. * <p> * Within <code>text</code>, the <code>lengthAfter</code> characters * beginning at <code>start</code> have just replaced old text that had * length <code>lengthBefore</code>. It is an error to attempt to make * changes to <code>text</code> from this callback. * * @param text The text the TextView is displaying * @param start The offset of the start of the range of the text that was * modified * @param lengthBefore The length of the former text that has been replaced * @param lengthAfter The length of the replacement modified text */ protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { // intentionally empty, template pattern method can be overridden by subclasses } /** * This method is called when the selection has changed, in case any * subclasses would like to know. * * @param selStart The new selection start location. * @param selEnd The new selection end location. */ protected void onSelectionChanged(int selStart, int selEnd) { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); } /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes. * <p> * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously * not called after {@link #setText} calls. Now, doing {@link #setText} * if there are any text changed listeners forces the buffer type to * Editable if it would not otherwise be and does call this method. */ public void addTextChangedListener(TextWatcher watcher) { if (mListeners == null) { mListeners = new ArrayList<TextWatcher>(); } mListeners.add(watcher); } /** * Removes the specified TextWatcher from the list of those whose * methods are called * whenever this TextView's text changes. */ public void removeTextChangedListener(TextWatcher watcher) { if (mListeners != null) { int i = mListeners.indexOf(watcher); if (i >= 0) { mListeners.remove(i); } } } private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) { if (mListeners != null) { final ArrayList<TextWatcher> list = mListeners; final int count = list.size(); for (int i = 0; i < count; i++) { list.get(i).beforeTextChanged(text, start, before, after); } } // The spans that are inside or intersect the modified region no longer make sense removeIntersectingNonAdjacentSpans(start, start + before, SpellCheckSpan.class); removeIntersectingNonAdjacentSpans(start, start + before, SuggestionSpan.class); } // Removes all spans that are inside or actually overlap the start..end range private <T> void removeIntersectingNonAdjacentSpans(int start, int end, Class<T> type) { if (!(mText instanceof Editable)) return; Editable text = (Editable) mText; T[] spans = text.getSpans(start, end, type); final int length = spans.length; for (int i = 0; i < length; i++) { final int spanStart = text.getSpanStart(spans[i]); final int spanEnd = text.getSpanEnd(spans[i]); if (spanEnd == start || spanStart == end) break; text.removeSpan(spans[i]); } } void removeAdjacentSuggestionSpans(final int pos) { if (!(mText instanceof Editable)) return; final Editable text = (Editable) mText; final SuggestionSpan[] spans = text.getSpans(pos, pos, SuggestionSpan.class); final int length = spans.length; for (int i = 0; i < length; i++) { final int spanStart = text.getSpanStart(spans[i]); final int spanEnd = text.getSpanEnd(spans[i]); if (spanEnd == pos || spanStart == pos) { if (SpellChecker.haveWordBoundariesChanged(text, pos, pos, spanStart, spanEnd)) { text.removeSpan(spans[i]); } } } } /** * Not private so it can be called from an inner class without going * through a thunk. */ void sendOnTextChanged(CharSequence text, int start, int before, int after) { if (mListeners != null) { final ArrayList<TextWatcher> list = mListeners; final int count = list.size(); for (int i = 0; i < count; i++) { list.get(i).onTextChanged(text, start, before, after); } } if (mEditor != null) mEditor.sendOnTextChanged(start, after); } /** * Not private so it can be called from an inner class without going * through a thunk. */ void sendAfterTextChanged(Editable text) { if (mListeners != null) { final ArrayList<TextWatcher> list = mListeners; final int count = list.size(); for (int i = 0; i < count; i++) { list.get(i).afterTextChanged(text); } } hideErrorIfUnchanged(); } void updateAfterEdit() { invalidate(); int curs = getSelectionStart(); if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { registerForPreDraw(); } checkForResize(); if (curs >= 0) { mHighlightPathBogus = true; if (mEditor != null) mEditor.makeBlink(); bringPointIntoView(curs); } } /** * Not private so it can be called from an inner class without going * through a thunk. */ void handleTextChanged(CharSequence buffer, int start, int before, int after) { final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState; if (ims == null || ims.mBatchEditNesting == 0) { updateAfterEdit(); } if (ims != null) { ims.mContentChanged = true; if (ims.mChangedStart < 0) { ims.mChangedStart = start; ims.mChangedEnd = start + before; } else { ims.mChangedStart = Math.min(ims.mChangedStart, start); ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); } ims.mChangedDelta += after - before; } resetErrorChangedFlag(); sendOnTextChanged(buffer, start, before, after); onTextChanged(buffer, start, before, after); } /** * Not private so it can be called from an inner class without going * through a thunk. */ void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { // XXX Make the start and end move together if this ends up // spending too much time invalidating. boolean selChanged = false; int newSelStart = -1, newSelEnd = -1; final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState; if (what == Selection.SELECTION_END) { selChanged = true; newSelEnd = newStart; if (oldStart >= 0 || newStart >= 0) { invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); checkForResize(); registerForPreDraw(); if (mEditor != null) mEditor.makeBlink(); } } if (what == Selection.SELECTION_START) { selChanged = true; newSelStart = newStart; if (oldStart >= 0 || newStart >= 0) { int end = Selection.getSelectionEnd(buf); invalidateCursor(end, oldStart, newStart); } } if (selChanged) { mHighlightPathBogus = true; if (mEditor != null && !isFocused()) mEditor.mSelectionMoved = true; if ((buf.getSpanFlags(what) & Spanned.SPAN_INTERMEDIATE) == 0) { if (newSelStart < 0) { newSelStart = Selection.getSelectionStart(buf); } if (newSelEnd < 0) { newSelEnd = Selection.getSelectionEnd(buf); } onSelectionChanged(newSelStart, newSelEnd); } } if (what instanceof UpdateAppearance || what instanceof ParagraphStyle || what instanceof CharacterStyle) { if (ims == null || ims.mBatchEditNesting == 0) { invalidate(); mHighlightPathBogus = true; checkForResize(); } else { ims.mContentChanged = true; } if (mEditor != null) { if (oldStart >= 0) mEditor.invalidateTextDisplayList(mLayout, oldStart, oldEnd); if (newStart >= 0) mEditor.invalidateTextDisplayList(mLayout, newStart, newEnd); } } if (MetaKeyKeyListener.isMetaTracker(buf, what)) { mHighlightPathBogus = true; if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { ims.mSelectionModeChanged = true; } if (Selection.getSelectionStart(buf) >= 0) { if (ims == null || ims.mBatchEditNesting == 0) { invalidateCursor(); } else { ims.mCursorChanged = true; } } } if (what instanceof ParcelableSpan) { // If this is a span that can be sent to a remote process, // the current extract editor would be interested in it. if (ims != null && ims.mExtractedTextRequest != null) { if (ims.mBatchEditNesting != 0) { if (oldStart >= 0) { if (ims.mChangedStart > oldStart) { ims.mChangedStart = oldStart; } if (ims.mChangedStart > oldEnd) { ims.mChangedStart = oldEnd; } } if (newStart >= 0) { if (ims.mChangedStart > newStart) { ims.mChangedStart = newStart; } if (ims.mChangedStart > newEnd) { ims.mChangedStart = newEnd; } } } else { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " + oldStart + "-" + oldEnd + "," + newStart + "-" + newEnd + " " + what); ims.mContentChanged = true; } } } if (mEditor != null && mEditor.mSpellChecker != null && newStart < 0 && what instanceof SpellCheckSpan) { mEditor.mSpellChecker.onSpellCheckSpanRemoved((SpellCheckSpan) what); } } /** * @hide */ @Override public void dispatchFinishTemporaryDetach() { mDispatchTemporaryDetach = true; super.dispatchFinishTemporaryDetach(); mDispatchTemporaryDetach = false; } @Override public void onStartTemporaryDetach() { super.onStartTemporaryDetach(); // Only track when onStartTemporaryDetach() is called directly, // usually because this instance is an editable field in a list if (!mDispatchTemporaryDetach) mTemporaryDetach = true; // Tell the editor that we are temporarily detached. It can use this to preserve // selection state as needed. if (mEditor != null) mEditor.mTemporaryDetach = true; } @Override public void onFinishTemporaryDetach() { super.onFinishTemporaryDetach(); // Only track when onStartTemporaryDetach() is called directly, // usually because this instance is an editable field in a list if (!mDispatchTemporaryDetach) mTemporaryDetach = false; if (mEditor != null) mEditor.mTemporaryDetach = false; } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (mTemporaryDetach) { // If we are temporarily in the detach state, then do nothing. super.onFocusChanged(focused, direction, previouslyFocusedRect); return; } if (mEditor != null) mEditor.onFocusChanged(focused, direction); if (focused) { if (mText instanceof Spannable) { Spannable sp = (Spannable) mText; MetaKeyKeyListener.resetMetaState(sp); } } startStopMarquee(focused); if (mTransformation != null) { mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); } super.onFocusChanged(focused, direction, previouslyFocusedRect); } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (mEditor != null) mEditor.onWindowFocusChanged(hasWindowFocus); startStopMarquee(hasWindowFocus); } @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (mEditor != null && visibility != VISIBLE) { mEditor.hideControllers(); } } /** * Use {@link BaseInputConnection#removeComposingSpans * BaseInputConnection.removeComposingSpans()} to remove any IME composing * state from this text view. */ public void clearComposingText() { if (mText instanceof Spannable) { BaseInputConnection.removeComposingSpans((Spannable) mText); } } @Override public void setSelected(boolean selected) { boolean wasSelected = isSelected(); super.setSelected(selected); if (selected != wasSelected && mEllipsize == TruncateAt.MARQUEE) { if (selected) { startMarquee(); } else { stopMarquee(); } } } //非TextView只会执行View.onTouchEvent,该函数是另一种将view和输入法绑定的调用 //而TextView会调用imm.showSoftInput会显示输入法 @Override public boolean onTouchEvent(MotionEvent event) { final int action = event.getActionMasked(); if (mEditor != null) mEditor.onTouchEvent(event); final boolean superResult = super.onTouchEvent(event); /* * Don't handle the release after a long press, because it will * move the selection away from whatever the menu action was * trying to affect. */ if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { mEditor.mDiscardNextActionUp = false; return superResult; } final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) && (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused(); if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() && mText instanceof Spannable && mLayout != null) { boolean handled = false; if (mMovement != null) { handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); } final boolean textIsSelectable = isTextSelectable(); if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) { // The LinkMovementMethod which should handle taps on links has not been installed // on non editable text that support text selection. // We reproduce its behavior here to open links for these. ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), getSelectionEnd(), ClickableSpan.class); if (links.length > 0) { links[0].onClick(this); handled = true; } } if (touchIsFinished && (isTextEditable() || textIsSelectable)) { // Show the IME, except when selecting in read-only text. 显示IME,除非选择只读文本。 final InputMethodManager imm = InputMethodManager.peekInstance(); viewClicked(imm); //这个是真正显示输入法的调用 if (!textIsSelectable && mEditor.mShowSoftInputOnFocus) { handled |= imm != null && imm.showSoftInput(this, 0); } // The above condition ensures that the mEditor is not null mEditor.onTouchUpEvent(event); handled = true; } if (handled) { return true; } } return superResult; } @Override public boolean onGenericMotionEvent(MotionEvent event) { if (mMovement != null && mText instanceof Spannable && mLayout != null) { try { if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { return true; } } catch (AbstractMethodError ex) { // onGenericMotionEvent was added to the MovementMethod interface in API 12. // Ignore its absence in case third party applications implemented the // interface directly. } } return super.onGenericMotionEvent(event); } /** * @return True iff this TextView contains a text that can be edited, or if this is * a selectable TextView. */ boolean isTextEditable() { return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); } /** * Returns true, only while processing a touch gesture, if the initial * touch down event caused focus to move to the text view and as a result * its selection changed. Only valid while processing the touch gesture * of interest, in an editable text view. */ public boolean didTouchFocusSelect() { return mEditor != null && mEditor.mTouchFocusSelected; } @Override public void cancelLongPress() { super.cancelLongPress(); if (mEditor != null) mEditor.mIgnoreActionUpEvent = true; } @Override public boolean onTrackballEvent(MotionEvent event) { if (mMovement != null && mText instanceof Spannable && mLayout != null) { if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { return true; } } return super.onTrackballEvent(event); } public void setScroller(Scroller s) { mScroller = s; } @Override protected float getLeftFadingEdgeStrength() { if (mEllipsize == TruncateAt.MARQUEE && mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (mMarquee != null && !mMarquee.isStopped()) { final Marquee marquee = mMarquee; if (marquee.shouldDrawLeftFade()) { final float scroll = marquee.getScroll(); return scroll / getHorizontalFadingEdgeLength(); } else { return 0.0f; } } else if (getLineCount() == 1) { final int layoutDirection = getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: return 0.0f; case Gravity.RIGHT: return (mLayout.getLineRight(0) - (mRight - mLeft) - getCompoundPaddingLeft() - getCompoundPaddingRight() - mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); case Gravity.CENTER_HORIZONTAL: case Gravity.FILL_HORIZONTAL: final int textDirection = mLayout.getParagraphDirection(0); if (textDirection == Layout.DIR_LEFT_TO_RIGHT) { return 0.0f; } else { return (mLayout.getLineRight(0) - (mRight - mLeft) - getCompoundPaddingLeft() - getCompoundPaddingRight() - mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); } } } } return super.getLeftFadingEdgeStrength(); } @Override protected float getRightFadingEdgeStrength() { if (mEllipsize == TruncateAt.MARQUEE && mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { if (mMarquee != null && !mMarquee.isStopped()) { final Marquee marquee = mMarquee; final float maxFadeScroll = marquee.getMaxFadeScroll(); final float scroll = marquee.getScroll(); return (maxFadeScroll - scroll) / getHorizontalFadingEdgeLength(); } else if (getLineCount() == 1) { final int layoutDirection = getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - getCompoundPaddingRight(); final float lineWidth = mLayout.getLineWidth(0); return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); case Gravity.RIGHT: return 0.0f; case Gravity.CENTER_HORIZONTAL: case Gravity.FILL_HORIZONTAL: final int textDirection = mLayout.getParagraphDirection(0); if (textDirection == Layout.DIR_RIGHT_TO_LEFT) { return 0.0f; } else { return (mLayout.getLineWidth(0) - ((mRight - mLeft) - getCompoundPaddingLeft() - getCompoundPaddingRight())) / getHorizontalFadingEdgeLength(); } } } } return super.getRightFadingEdgeStrength(); } @Override protected int computeHorizontalScrollRange() { if (mLayout != null) { return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? (int) mLayout.getLineWidth(0) : mLayout.getWidth(); } return super.computeHorizontalScrollRange(); } @Override protected int computeVerticalScrollRange() { if (mLayout != null) return mLayout.getHeight(); return super.computeVerticalScrollRange(); } @Override protected int computeVerticalScrollExtent() { return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); } @Override public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { super.findViewsWithText(outViews, searched, flags); if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) { String searchedLowerCase = searched.toString().toLowerCase(); String textLowerCase = mText.toString().toLowerCase(); if (textLowerCase.contains(searchedLowerCase)) { outViews.add(this); } } } public enum BufferType { NORMAL, SPANNABLE, EDITABLE, } /** * Returns the TextView_textColor attribute from the TypedArray, if set, or * the TextAppearance_textColor from the TextView_textAppearance attribute, * if TextView_textColor was not set directly. * * @removed */ public static ColorStateList getTextColors(Context context, TypedArray attrs) { if (attrs == null) { // Preserve behavior prior to removal of this API. throw new NullPointerException(); } // It's not safe to use this method from apps. The parameter 'attrs' // must have been obtained using the TextView filter array which is not // available to the SDK. As such, we grab a default TypedArray with the // right filter instead here. final TypedArray a = context.obtainStyledAttributes(R.styleable.TextView); ColorStateList colors = a.getColorStateList(R.styleable.TextView_textColor); if (colors == null) { final int ap = a.getResourceId(R.styleable.TextView_textAppearance, 0); if (ap != 0) { final TypedArray appearance = context.obtainStyledAttributes(ap, R.styleable.TextAppearance); colors = appearance.getColorStateList(R.styleable.TextAppearance_textColor); appearance.recycle(); } } a.recycle(); return colors; } /** * Returns the default color from the TextView_textColor attribute from the * AttributeSet, if set, or the default color from the * TextAppearance_textColor from the TextView_textAppearance attribute, if * TextView_textColor was not set directly. * * @removed */ public static int getTextColor(Context context, TypedArray attrs, int def) { final ColorStateList colors = getTextColors(context, attrs); if (colors == null) { return def; } else { return colors.getDefaultColor(); } } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { switch (keyCode) { case KeyEvent.KEYCODE_A: if (canSelectText()) { return onTextContextMenuItem(ID_SELECT_ALL); } break; case KeyEvent.KEYCODE_X: if (canCut()) { return onTextContextMenuItem(ID_CUT); } break; case KeyEvent.KEYCODE_C: if (canCopy()) { return onTextContextMenuItem(ID_COPY); } break; case KeyEvent.KEYCODE_V: if (canPaste()) { return onTextContextMenuItem(ID_PASTE); } break; } } return super.onKeyShortcut(keyCode, event); } /** * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not * sufficient. */ private boolean canSelectText() { return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController(); } /** * Test based on the <i>intrinsic</i> charateristics of the TextView. * The text must be spannable and the movement method must allow for arbitary selection. * <p> * See also {@link #canSelectText()}. */ boolean textCanBeSelected() { // prepareCursorController() relies on this method. // If you change this condition, make sure prepareCursorController is called anywhere // the value of this condition might be changed. if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; return isTextEditable() || (isTextSelectable() && mText instanceof Spannable && isEnabled()); } private Locale getTextServicesLocale(boolean allowNullLocale) { // Start fetching the text services locale asynchronously. updateTextServicesLocaleAsync(); // If !allowNullLocale and there is no cached text services locale, just return the default // locale. return (mCurrentSpellCheckerLocaleCache == null && !allowNullLocale) ? Locale.getDefault() : mCurrentSpellCheckerLocaleCache; } /** * This is a temporary method. Future versions may support multi-locale text. * Caveat: This method may not return the latest text services locale, but this should be * acceptable and it's more important to make this method asynchronous. * * @return The locale that should be used for a word iterator * in this TextView, based on the current spell checker settings, * the current IME's locale, or the system default locale. * Please note that a word iterator in this TextView is different from another word iterator * used by SpellChecker.java of TextView. This method should be used for the former. * @hide */ // TODO: Support multi-locale // TODO: Update the text services locale immediately after the keyboard locale is switched // by catching intent of keyboard switch event public Locale getTextServicesLocale() { return getTextServicesLocale(false /* allowNullLocale */); } /** * This is a temporary method. Future versions may support multi-locale text. * Caveat: This method may not return the latest spell checker locale, but this should be * acceptable and it's more important to make this method asynchronous. * * @return The locale that should be used for a spell checker in this TextView, * based on the current spell checker settings, the current IME's locale, or the system default * locale. * @hide */ public Locale getSpellCheckerLocale() { return getTextServicesLocale(true /* allowNullLocale */); } private void updateTextServicesLocaleAsync() { // AsyncTask.execute() uses a serial executor which means we don't have // to lock around updateTextServicesLocaleLocked() to prevent it from // being executed n times in parallel. AsyncTask.execute(new Runnable() { @Override public void run() { updateTextServicesLocaleLocked(); } }); } private void updateTextServicesLocaleLocked() { final TextServicesManager textServicesManager = (TextServicesManager) mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true); final Locale locale; if (subtype != null) { locale = SpellCheckerSubtype.constructLocaleFromString(subtype.getLocale()); } else { locale = null; } mCurrentSpellCheckerLocaleCache = locale; } void onLocaleChanged() { // Will be re-created on demand in getWordIterator with the proper new locale mEditor.mWordIterator = null; } /** * This method is used by the ArrowKeyMovementMethod to jump from one word to the other. * Made available to achieve a consistent behavior. * * @hide */ public WordIterator getWordIterator() { if (mEditor != null) { return mEditor.getWordIterator(); } else { return null; } } @Override public void onPopulateAccessibilityEvent(AccessibilityEvent event) { super.onPopulateAccessibilityEvent(event); final boolean isPassword = hasPasswordTransformationMethod(); if (!isPassword || shouldSpeakPasswordsForAccessibility()) { final CharSequence text = getTextForAccessibility(); if (!TextUtils.isEmpty(text)) { event.getText().add(text); } } } /** * @return true if the user has explicitly allowed accessibility services * to speak passwords. */ private boolean shouldSpeakPasswordsForAccessibility() { return (Settings.Secure.getIntForUser(mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0, UserHandle.USER_CURRENT_OR_SELF) == 1); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(TextView.class.getName()); final boolean isPassword = hasPasswordTransformationMethod(); event.setPassword(isPassword); if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { event.setFromIndex(Selection.getSelectionStart(mText)); event.setToIndex(Selection.getSelectionEnd(mText)); event.setItemCount(mText.length()); } } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(TextView.class.getName()); final boolean isPassword = hasPasswordTransformationMethod(); info.setPassword(isPassword); if (!isPassword || shouldSpeakPasswordsForAccessibility()) { info.setText(getTextForAccessibility()); } if (mBufferType == BufferType.EDITABLE) { info.setEditable(true); } if (mEditor != null) { info.setInputType(mEditor.mInputType); if (mEditor.mError != null) { info.setContentInvalid(true); info.setError(mEditor.mError); } } if (!TextUtils.isEmpty(mText)) { info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE); } if (isFocused()) { if (canSelectText()) { info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (canCopy()) { info.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (canPaste()) { info.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (canCut()) { info.addAction(AccessibilityNodeInfo.ACTION_CUT); } } // Check for known input filter types. final int numFilters = mFilters.length; for (int i = 0; i < numFilters; i++) { final InputFilter filter = mFilters[i]; if (filter instanceof InputFilter.LengthFilter) { info.setMaxTextLength(((InputFilter.LengthFilter) filter).getMax()); } } if (!isSingleLine()) { info.setMultiLine(true); } } /** * Performs an accessibility action after it has been offered to the * delegate. * * @hide */ @Override public boolean performAccessibilityActionInternal(int action, Bundle arguments) { switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { boolean handled = false; // Simulate View.onTouchEvent for an ACTION_UP event. if (isClickable() || isLongClickable()) { if (isFocusable() && !isFocused()) { requestFocus(); } performClick(); handled = true; } // Simulate TextView.onTouchEvent for an ACTION_UP event. if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() && mText instanceof Spannable && mLayout != null && (isTextEditable() || isTextSelectable()) && isFocused()) { // Show the IME, except when selecting in read-only text. final InputMethodManager imm = InputMethodManager.peekInstance(); viewClicked(imm); if (!isTextSelectable() && mEditor.mShowSoftInputOnFocus && imm != null) { handled |= imm.showSoftInput(this, 0); } } return handled; } case AccessibilityNodeInfo.ACTION_COPY: { if (isFocused() && canCopy()) { if (onTextContextMenuItem(ID_COPY)) { return true; } } } return false; case AccessibilityNodeInfo.ACTION_PASTE: { if (isFocused() && canPaste()) { if (onTextContextMenuItem(ID_PASTE)) { return true; } } } return false; case AccessibilityNodeInfo.ACTION_CUT: { if (isFocused() && canCut()) { if (onTextContextMenuItem(ID_CUT)) { return true; } } } return false; case AccessibilityNodeInfo.ACTION_SET_SELECTION: { if (isFocused() && canSelectText()) { ensureIterableTextForAccessibilitySelectable(); CharSequence text = getIterableTextForAccessibility(); if (text == null) { return false; } final int start = (arguments != null) ? arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; final int end = (arguments != null) ? arguments.getInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; if ((getSelectionStart() != start || getSelectionEnd() != end)) { // No arguments clears the selection. if (start == end && end == -1) { Selection.removeSelection((Spannable) text); return true; } if (start >= 0 && start <= end && end <= text.length()) { Selection.setSelection((Spannable) text, start, end); // Make sure selection mode is engaged. if (mEditor != null) { mEditor.startSelectionActionMode(); } return true; } } } } return false; case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { ensureIterableTextForAccessibilitySelectable(); return super.performAccessibilityActionInternal(action, arguments); } default: { return super.performAccessibilityActionInternal(action, arguments); } } } @Override public void sendAccessibilityEvent(int eventType) { // Do not send scroll events since first they are not interesting for // accessibility and second such events a generated too frequently. // For details see the implementation of bringTextIntoView(). if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { return; } super.sendAccessibilityEvent(eventType); } /** * Gets the text reported for accessibility purposes. * * @return The accessibility text. * @hide */ public CharSequence getTextForAccessibility() { CharSequence text = getText(); if (TextUtils.isEmpty(text)) { text = getHint(); } return text; } void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, int fromIndex, int removedCount, int addedCount) { AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); event.setFromIndex(fromIndex); event.setRemovedCount(removedCount); event.setAddedCount(addedCount); event.setBeforeText(beforeText); sendAccessibilityEventUnchecked(event); } /** * Returns whether this text view is a current input method target. The * default implementation just checks with {@link InputMethodManager}. */ public boolean isInputMethodTarget() { InputMethodManager imm = InputMethodManager.peekInstance(); return imm != null && imm.isActive(this); } static final int ID_SELECT_ALL = R.id.selectAll; static final int ID_CUT = R.id.cut; static final int ID_COPY = R.id.copy; static final int ID_PASTE = R.id.paste; /** * Called when a context menu option for the text view is selected. Currently * this will be one of {@link R.id#selectAll}, {@link R.id#cut}, * {@link R.id#copy} or {@link R.id#paste}. * * @return true if the context menu item action was performed. */ public boolean onTextContextMenuItem(int id) { int min = 0; int max = mText.length(); if (isFocused()) { final int selStart = getSelectionStart(); final int selEnd = getSelectionEnd(); min = Math.max(0, Math.min(selStart, selEnd)); max = Math.max(0, Math.max(selStart, selEnd)); } switch (id) { case ID_SELECT_ALL: // This does not enter text selection mode. Text is highlighted, so that it can be // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. selectAllText(); return true; case ID_PASTE: paste(min, max); return true; case ID_CUT: setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); deleteText_internal(min, max); stopSelectionActionMode(); return true; case ID_COPY: setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); stopSelectionActionMode(); return true; } return false; } CharSequence getTransformedText(int start, int end) { return removeSuggestionSpans(mTransformed.subSequence(start, end)); } @Override public boolean performLongClick() { boolean handled = false; if (super.performLongClick()) { handled = true; } if (mEditor != null) { handled |= mEditor.performLongClick(handled); } if (handled) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); if (mEditor != null) mEditor.mDiscardNextActionUp = true; } return handled; } @Override protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { super.onScrollChanged(horiz, vert, oldHoriz, oldVert); if (mEditor != null) { mEditor.onScrollChanged(); } } /** * Return whether or not suggestions are enabled on this TextView. The suggestions are generated * by the IME or by the spell checker as the user types. This is done by adding * {@link SuggestionSpan}s to the text. * <p> * When suggestions are enabled (default), this list of suggestions will be displayed when the * user asks for them on these parts of the text. This value depends on the inputType of this * TextView. * <p> * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}. * <p> * In addition, the type variation must be one of * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. * <p> * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. * * @return true if the suggestions popup window is enabled, based on the inputType. */ public boolean isSuggestionsEnabled() { if (mEditor == null) return false; if ((mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) { return false; } if ((mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false; final int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE || variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT); } /** * If provided, this ActionMode.Callback will be used to create the ActionMode when text * selection is initiated in this View. * <p> * The standard implementation populates the menu with a subset of Select All, Cut, Copy and * Paste actions, depending on what this View supports. * <p> * A custom implementation can add new entries in the default menu in its * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and * passing {@link R.id#selectAll}, {@link R.id#cut}, {@link R.id#copy} * or {@link R.id#paste} ids as parameters. * <p> * Returning false from * {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent * the action mode from being started. * <p> * Action click events should be handled by the custom implementation of * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. * <p> * Note that text selection mode is not started when a TextView receives focus and the * {@link R.attr#selectAllOnFocus} flag has been set. The content is highlighted in * that case, to allow for quick replacement. */ public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { createEditorIfNeeded(); mEditor.mCustomSelectionActionModeCallback = actionModeCallback; } /** * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. * * @return The current custom selection callback. */ public ActionMode.Callback getCustomSelectionActionModeCallback() { return mEditor == null ? null : mEditor.mCustomSelectionActionModeCallback; } /** * @hide */ protected void stopSelectionActionMode() { mEditor.stopSelectionActionMode(); } boolean canCut() { if (hasPasswordTransformationMethod()) { return false; } if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null && mEditor.mKeyListener != null) { return true; } return false; } boolean canCopy() { if (hasPasswordTransformationMethod()) { return false; } if (mText.length() > 0 && hasSelection() && mEditor != null) { return true; } return false; } boolean canPaste() { return (mText instanceof Editable && mEditor != null && mEditor.mKeyListener != null && getSelectionStart() >= 0 && getSelectionEnd() >= 0 && ((ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE)). hasPrimaryClip()); } boolean selectAllText() { final int length = mText.length(); Selection.setSelection((Spannable) mText, 0, length); return length > 0; } /** * Paste clipboard content between min and max positions. */ private void paste(int min, int max) { ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { boolean didFirst = false; for (int i = 0; i < clip.getItemCount(); i++) { CharSequence paste = clip.getItemAt(i).coerceToStyledText(getContext()); if (paste != null) { if (!didFirst) { Selection.setSelection((Spannable) mText, max); ((Editable) mText).replace(min, max, paste); didFirst = true; } else { ((Editable) mText).insert(getSelectionEnd(), "\n"); ((Editable) mText).insert(getSelectionEnd(), paste); } } } stopSelectionActionMode(); LAST_CUT_OR_COPY_TIME = 0; } } private void setPrimaryClip(ClipData clip) { ClipboardManager clipboard = (ClipboardManager) getContext(). getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(clip); LAST_CUT_OR_COPY_TIME = SystemClock.uptimeMillis(); } /** * Get the character offset closest to the specified absolute position. A typical use case is to * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. * * @param x The horizontal absolute position of a point on screen * @param y The vertical absolute position of a point on screen * @return the character offset for the character whose position is closest to the specified * position. Returns -1 if there is no layout. */ public int getOffsetForPosition(float x, float y) { if (getLayout() == null) return -1; final int line = getLineAtCoordinate(y); final int offset = getOffsetAtCoordinate(line, x); return offset; } float convertToLocalHorizontalCoordinate(float x) { x -= getTotalPaddingLeft(); // Clamp the position to inside of the view. x = Math.max(0.0f, x); x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); x += getScrollX(); return x; } int getLineAtCoordinate(float y) { y -= getTotalPaddingTop(); // Clamp the position to inside of the view. y = Math.max(0.0f, y); y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); y += getScrollY(); return getLayout().getLineForVertical((int) y); } private int getOffsetAtCoordinate(int line, float x) { x = convertToLocalHorizontalCoordinate(x); return getLayout().getOffsetForHorizontal(line, x); } @Override public boolean onDragEvent(DragEvent event) { switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: return mEditor != null && mEditor.hasInsertionController(); case DragEvent.ACTION_DRAG_ENTERED: TextView.this.requestFocus(); return true; case DragEvent.ACTION_DRAG_LOCATION: final int offset = getOffsetForPosition(event.getX(), event.getY()); Selection.setSelection((Spannable) mText, offset); return true; case DragEvent.ACTION_DROP: if (mEditor != null) mEditor.onDrop(event); return true; case DragEvent.ACTION_DRAG_ENDED: case DragEvent.ACTION_DRAG_EXITED: default: return true; } } boolean isInBatchEditMode() { if (mEditor == null) return false; final Editor.InputMethodState ims = mEditor.mInputMethodState; if (ims != null) { return ims.mBatchEditNesting > 0; } return mEditor.mInBatchEditControllers; } @Override public void onRtlPropertiesChanged(int layoutDirection) { super.onRtlPropertiesChanged(layoutDirection); mTextDir = getTextDirectionHeuristic(); if (mLayout != null) { checkForRelayout(); } } TextDirectionHeuristic getTextDirectionHeuristic() { if (hasPasswordTransformationMethod()) { // passwords fields should be LTR return TextDirectionHeuristics.LTR; } // Always need to resolve layout direction first final boolean defaultIsRtl = (getLayoutDirection() == LAYOUT_DIRECTION_RTL); // Now, we can select the heuristic switch (getTextDirection()) { default: case TEXT_DIRECTION_FIRST_STRONG: return (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : TextDirectionHeuristics.FIRSTSTRONG_LTR); case TEXT_DIRECTION_ANY_RTL: return TextDirectionHeuristics.ANYRTL_LTR; case TEXT_DIRECTION_LTR: return TextDirectionHeuristics.LTR; case TEXT_DIRECTION_RTL: return TextDirectionHeuristics.RTL; case TEXT_DIRECTION_LOCALE: return TextDirectionHeuristics.LOCALE; } } /** * @hide */ @Override public void onResolveDrawables(int layoutDirection) { // No need to resolve twice if (mLastLayoutDirection == layoutDirection) { return; } mLastLayoutDirection = layoutDirection; // Resolve drawables if (mDrawables != null) { mDrawables.resolveWithLayoutDirection(layoutDirection); } } /** * @hide */ protected void resetResolvedDrawables() { super.resetResolvedDrawables(); mLastLayoutDirection = -1; } /** * @hide */ protected void viewClicked(InputMethodManager imm) { if (imm != null) { imm.viewClicked(this); } } /** * Deletes the range of text [start, end[. * * @hide */ protected void deleteText_internal(int start, int end) { ((Editable) mText).delete(start, end); } /** * Replaces the range of text [start, end[ by replacement text * * @hide */ protected void replaceText_internal(int start, int end, CharSequence text) { ((Editable) mText).replace(start, end, text); } /** * Sets a span on the specified range of text * * @hide */ protected void setSpan_internal(Object span, int start, int end, int flags) { ((Editable) mText).setSpan(span, start, end, flags); } /** * Moves the cursor to the specified offset position in text * * @hide */ protected void setCursorPosition_internal(int start, int end) { Selection.setSelection(((Editable) mText), start, end); } /** * An Editor should be created as soon as any of the editable-specific fields (grouped * inside the Editor object) is assigned to a non-default value. * This method will create the Editor if needed. * <p> * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will * have a null Editor, unlike an EditText. Inconsistent in-between states will have an * Editor for backward compatibility, as soon as one of these fields is assigned. * <p> * Also note that for performance reasons, the mEditor is created when needed, but not * reset when no more edit-specific fields are needed. */ private void createEditorIfNeeded() { if (mEditor == null) { mEditor = new Editor(this); } } /** * @hide */ @Override public CharSequence getIterableTextForAccessibility() { return mText; } private void ensureIterableTextForAccessibilitySelectable() { if (!(mText instanceof Spannable)) { setText(mText, BufferType.SPANNABLE); } } /** * @hide */ @Override public TextSegmentIterator getIteratorForGranularity(int granularity) { switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: { Spannable text = (Spannable) getIterableTextForAccessibility(); if (!TextUtils.isEmpty(text) && getLayout() != null) { AccessibilityIterators.LineTextSegmentIterator iterator = AccessibilityIterators.LineTextSegmentIterator.getInstance(); iterator.initialize(text, getLayout()); return iterator; } } break; case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: { Spannable text = (Spannable) getIterableTextForAccessibility(); if (!TextUtils.isEmpty(text) && getLayout() != null) { AccessibilityIterators.PageTextSegmentIterator iterator = AccessibilityIterators.PageTextSegmentIterator.getInstance(); iterator.initialize(this); return iterator; } } break; } return super.getIteratorForGranularity(granularity); } /** * @hide */ @Override public int getAccessibilitySelectionStart() { return getSelectionStart(); } /** * @hide */ public boolean isAccessibilitySelectionExtendable() { return true; } /** * @hide */ @Override public int getAccessibilitySelectionEnd() { return getSelectionEnd(); } /** * @hide */ @Override public void setAccessibilitySelection(int start, int end) { if (getAccessibilitySelectionStart() == start && getAccessibilitySelectionEnd() == end) { return; } // Hide all selection controllers used for adjusting selection // since we are doing so explicitlty by other means and these // controllers interact with how selection behaves. if (mEditor != null) { mEditor.hideControllers(); } CharSequence text = getIterableTextForAccessibility(); if (Math.min(start, end) >= 0 && Math.max(start, end) <= text.length()) { Selection.setSelection((Spannable) text, start, end); } else { Selection.removeSelection((Spannable) text); } } /** * User interface state that is stored by TextView for implementing * {@link View#onSaveInstanceState}. */ public static class SavedState extends BaseSavedState { int selStart; int selEnd; CharSequence text; boolean frozenWithFocus; CharSequence error; SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(selStart); out.writeInt(selEnd); out.writeInt(frozenWithFocus ? 1 : 0); TextUtils.writeToParcel(text, out, flags); if (error == null) { out.writeInt(0); } else { out.writeInt(1); TextUtils.writeToParcel(error, out, flags); } } @Override public String toString() { String str = "TextView.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " start=" + selStart + " end=" + selEnd; if (text != null) { str += " text=" + text; } return str + "}"; } @SuppressWarnings("hiding") public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; private SavedState(Parcel in) { super(in); selStart = in.readInt(); selEnd = in.readInt(); frozenWithFocus = (in.readInt() != 0); text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); if (in.readInt() != 0) { error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); } } } private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations { private char[] mChars; private int mStart, mLength; public CharWrapper(char[] chars, int start, int len) { mChars = chars; mStart = start; mLength = len; } /* package */ void set(char[] chars, int start, int len) { mChars = chars; mStart = start; mLength = len; } public int length() { return mLength; } public char charAt(int off) { return mChars[off + mStart]; } @Override public String toString() { return new String(mChars, mStart, mLength); } public CharSequence subSequence(int start, int end) { if (start < 0 || end < 0 || start > mLength || end > mLength) { throw new IndexOutOfBoundsException(start + ", " + end); } return new String(mChars, start + mStart, end - start); } public void getChars(int start, int end, char[] buf, int off) { if (start < 0 || end < 0 || start > mLength || end > mLength) { throw new IndexOutOfBoundsException(start + ", " + end); } System.arraycopy(mChars, start + mStart, buf, off, end - start); } public void drawText(Canvas c, int start, int end, float x, float y, Paint p) { c.drawText(mChars, start + mStart, end - start, x, y, p); } public void drawTextRun(Canvas c, int start, int end, int contextStart, int contextEnd, float x, float y, boolean isRtl, Paint p) { int count = end - start; int contextCount = contextEnd - contextStart; c.drawTextRun(mChars, start + mStart, count, contextStart + mStart, contextCount, x, y, isRtl, p); } public float measureText(int start, int end, Paint p) { return p.measureText(mChars, start + mStart, end - start); } public int getTextWidths(int start, int end, float[] widths, Paint p) { return p.getTextWidths(mChars, start + mStart, end - start, widths); } public float getTextRunAdvances(int start, int end, int contextStart, int contextEnd, boolean isRtl, float[] advances, int advancesIndex, Paint p) { int count = end - start; int contextCount = contextEnd - contextStart; return p.getTextRunAdvances(mChars, start + mStart, count, contextStart + mStart, contextCount, isRtl, advances, advancesIndex); } public int getTextRunCursor(int contextStart, int contextEnd, int dir, int offset, int cursorOpt, Paint p) { int contextCount = contextEnd - contextStart; return p.getTextRunCursor(mChars, contextStart + mStart, contextCount, dir, offset + mStart, cursorOpt); } } private static final class Marquee { // TODO: Add an option to configure this private static final float MARQUEE_DELTA_MAX = 0.07f; private static final int MARQUEE_DELAY = 1200; private static final int MARQUEE_RESTART_DELAY = 1200; private static final int MARQUEE_DP_PER_SECOND = 30; private static final byte MARQUEE_STOPPED = 0x0; private static final byte MARQUEE_STARTING = 0x1; private static final byte MARQUEE_RUNNING = 0x2; private final WeakReference<TextView> mView; private final Choreographer mChoreographer; private byte mStatus = MARQUEE_STOPPED; private final float mPixelsPerSecond; private float mMaxScroll; private float mMaxFadeScroll; private float mGhostStart; private float mGhostOffset; private float mFadeStop; private int mRepeatLimit; private float mScroll; private long mLastAnimationMs; Marquee(TextView v) { final float density = v.getContext().getResources().getDisplayMetrics().density; mPixelsPerSecond = MARQUEE_DP_PER_SECOND * density; mView = new WeakReference<TextView>(v); mChoreographer = Choreographer.getInstance(); } private Choreographer.FrameCallback mTickCallback = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { tick(); } }; private Choreographer.FrameCallback mStartCallback = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { mStatus = MARQUEE_RUNNING; mLastAnimationMs = mChoreographer.getFrameTime(); tick(); } }; private Choreographer.FrameCallback mRestartCallback = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { if (mStatus == MARQUEE_RUNNING) { if (mRepeatLimit >= 0) { mRepeatLimit--; } start(mRepeatLimit); } } }; void tick() { if (mStatus != MARQUEE_RUNNING) { return; } mChoreographer.removeFrameCallback(mTickCallback); final TextView textView = mView.get(); if (textView != null && (textView.isFocused() || textView.isSelected())) { long currentMs = mChoreographer.getFrameTime(); long deltaMs = currentMs - mLastAnimationMs; mLastAnimationMs = currentMs; float deltaPx = deltaMs / 1000f * mPixelsPerSecond; mScroll += deltaPx; if (mScroll > mMaxScroll) { mScroll = mMaxScroll; mChoreographer.postFrameCallbackDelayed(mRestartCallback, MARQUEE_DELAY); } else { mChoreographer.postFrameCallback(mTickCallback); } textView.invalidate(); } } void stop() { mStatus = MARQUEE_STOPPED; mChoreographer.removeFrameCallback(mStartCallback); mChoreographer.removeFrameCallback(mRestartCallback); mChoreographer.removeFrameCallback(mTickCallback); resetScroll(); } private void resetScroll() { mScroll = 0.0f; final TextView textView = mView.get(); if (textView != null) textView.invalidate(); } void start(int repeatLimit) { if (repeatLimit == 0) { stop(); return; } mRepeatLimit = repeatLimit; final TextView textView = mView.get(); if (textView != null && textView.mLayout != null) { mStatus = MARQUEE_STARTING; mScroll = 0.0f; final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - textView.getCompoundPaddingRight(); final float lineWidth = textView.mLayout.getLineWidth(0); final float gap = textWidth / 3.0f; mGhostStart = lineWidth - textWidth + gap; mMaxScroll = mGhostStart + textWidth; mGhostOffset = lineWidth + gap; mFadeStop = lineWidth + textWidth / 6.0f; mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; textView.invalidate(); mChoreographer.postFrameCallback(mStartCallback); } } float getGhostOffset() { return mGhostOffset; } float getScroll() { return mScroll; } float getMaxFadeScroll() { return mMaxFadeScroll; } boolean shouldDrawLeftFade() { return mScroll <= mFadeStop; } boolean shouldDrawGhost() { return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; } boolean isRunning() { return mStatus == MARQUEE_RUNNING; } boolean isStopped() { return mStatus == MARQUEE_STOPPED; } } private class ChangeWatcher implements TextWatcher, SpanWatcher { private CharSequence mBeforeText; public void beforeTextChanged(CharSequence buffer, int start, int before, int after) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start + " before=" + before + " after=" + after + ": " + buffer); if (AccessibilityManager.getInstance(mContext).isEnabled() && ((!isPasswordInputType(getInputType()) && !hasPasswordTransformationMethod()) || shouldSpeakPasswordsForAccessibility())) { mBeforeText = buffer.toString(); } TextView.this.sendBeforeTextChanged(buffer, start, before, after); } public void onTextChanged(CharSequence buffer, int start, int before, int after) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start + " before=" + before + " after=" + after + ": " + buffer); TextView.this.handleTextChanged(buffer, start, before, after); if (AccessibilityManager.getInstance(mContext).isEnabled() && (isFocused() || isSelected() && isShown())) { sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); mBeforeText = null; } } public void afterTextChanged(Editable buffer) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); TextView.this.sendAfterTextChanged(buffer); if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { MetaKeyKeyListener.stopSelecting(TextView.this, buffer); } } public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e + " st=" + st + " en=" + en + " what=" + what + ": " + buf); TextView.this.spanChange(buf, what, s, st, e, en); } public void onSpanAdded(Spannable buf, Object what, int s, int e) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e + " what=" + what + ": " + buf); TextView.this.spanChange(buf, what, -1, s, -1, e); } public void onSpanRemoved(Spannable buf, Object what, int s, int e) { if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e + " what=" + what + ": " + buf); TextView.this.spanChange(buf, what, s, -1, e, -1); } } }
f0aa861948e77a492247d58911ed5edc30d30b09
fff8f77f810bbd5fb6b4e5f7a654568fd9d3098d
/src/main/java/com/google/android/gms/internal/vision/zzo.java
bbf13b4bad3ee689b640d6b22299948d1b9b3711
[]
no_license
TL148/gorkiy
b6ac8772587e9e643d939ea399bf5e7a42e89f46
da8fbd017277cf72020c8c800326954bb1a0cee3
refs/heads/master
2021-05-21T08:24:39.286900
2020-04-03T02:57:49
2020-04-03T02:57:49
252,618,229
0
0
null
2020-04-03T02:54:39
2020-04-03T02:54:39
null
UTF-8
Java
false
false
1,622
java
package com.google.android.gms.internal.vision; import android.os.Parcel; import android.os.Parcelable; import com.google.android.gms.common.internal.safeparcel.SafeParcelReader; /* compiled from: com.google.android.gms:play-services-vision-common@@19.0.0 */ public final class zzo implements Parcelable.Creator<zzp> { public final /* synthetic */ Object[] newArray(int i) { return new zzp[i]; } public final /* synthetic */ Object createFromParcel(Parcel parcel) { int validateObjectHeader = SafeParcelReader.validateObjectHeader(parcel); int i = 0; int i2 = 0; int i3 = 0; int i4 = 0; long j = 0; while (parcel.dataPosition() < validateObjectHeader) { int readHeader = SafeParcelReader.readHeader(parcel); int fieldId = SafeParcelReader.getFieldId(readHeader); if (fieldId == 2) { i = SafeParcelReader.readInt(parcel, readHeader); } else if (fieldId == 3) { i2 = SafeParcelReader.readInt(parcel, readHeader); } else if (fieldId == 4) { i3 = SafeParcelReader.readInt(parcel, readHeader); } else if (fieldId == 5) { j = SafeParcelReader.readLong(parcel, readHeader); } else if (fieldId != 6) { SafeParcelReader.skipUnknownField(parcel, readHeader); } else { i4 = SafeParcelReader.readInt(parcel, readHeader); } } SafeParcelReader.ensureAtEnd(parcel, validateObjectHeader); return new zzp(i, i2, i3, j, i4); } }
5503e58b46ce53c947542928c83e77c1d11e5d21
9194181617b08a95a7712e524321647302208a87
/ReferenceProject/MiShare1_0/src/com/cmmobi/looklook/common/adapter/VshareListAdapter.java
8f187e8563d5edf5bca18b4a973ee6fde1be77ea
[]
no_license
Lucaziki/WeFlow
2dae5beaa1a156094934f92fc6739562f6fca9ee
08c56de996efad33dc43ee51931d45b03ce77651
refs/heads/master
2021-01-18T20:49:29.591710
2015-05-06T06:23:37
2015-05-06T06:23:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,893
java
package com.cmmobi.looklook.common.adapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.entity.mime.content.ContentBody; import android.content.Context; import android.location.Location; import android.text.Html; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.baidu.platform.comapi.map.l; import com.cmmobi.looklook.R; import com.cmmobi.looklook.common.gson.GsonResponse3.MicListItem; import com.cmmobi.looklook.common.utils.DateUtils; import com.cmmobi.looklook.common.utils.DensityUtil; import com.cmmobi.looklook.common.view.FriendsExpressionView; import com.cmmobi.looklook.common.view.VshareContentThumbnailView; import com.cmmobi.looklook.info.profile.ActiveAccount; import com.cmmobi.looklook.info.profile.TimeHelper; import com.cmmobi.sns.utils.TimeUtil; public class VshareListAdapter extends BaseAdapter { private Context context; private LayoutInflater inflater; private List<MicListItem> list = new ArrayList<MicListItem>(); private int size = 0; public Boolean isForTimer = false; public VshareListAdapter(final Context context) { this.context = context; DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics(); this.size = dm.widthPixels/5; inflater = LayoutInflater.from(context); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate( R.layout.activity_vshare_list_item, null); holder = new ViewHolder(); holder.rl_content = (RelativeLayout) convertView.findViewById(R.id.rl_content); holder.vctv_vshare = (VshareContentThumbnailView) convertView.findViewById(R.id.vctv_vshare); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.vctv_vshare.getLayoutParams(); params.width = size; params.height = size; holder.vctv_vshare.setLayoutParams(params); holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time); holder.tv_count = (TextView) convertView.findViewById(R.id.tv_count); holder.tv_lastMessage = (TextView) convertView.findViewById(R.id.tv_last_message); holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content); holder.iv_jiaobiao = (ImageView) convertView.findViewById(R.id.iv_jiaobiao); holder.iv_error = (ImageView) convertView.findViewById(R.id.iv_error); holder.iv_nodata = (ImageView) convertView.findViewById(R.id.iv_nodata); holder.iv_line = (ImageView) convertView.findViewById(R.id.iv_line); holder.iv_throwaway = (ImageView) convertView.findViewById(R.id.iv_throwaway); params = (RelativeLayout.LayoutParams) holder.iv_line.getLayoutParams(); params.setMargins(size + DensityUtil.dip2px(context, 5), 0, 0, 0); holder.iv_line.setLayoutParams(params); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if(list.size() == 1 && (list.get(0).micuserid == null || list.get(0).micuserid.isEmpty())){ holder.iv_nodata.setVisibility(View.VISIBLE); holder.rl_content.setVisibility(View.GONE); return convertView; }else { holder.iv_nodata.setVisibility(View.GONE); holder.rl_content.setVisibility(View.VISIBLE); } //holder.vctv_vshare.setContentDiaries(null, null, null); holder.tv_time.setText(""); holder.tv_time.setVisibility(View.VISIBLE); holder.tv_count.setText(""); holder.tv_lastMessage.setText(""); holder.tv_content.setText(""); holder.iv_jiaobiao.setVisibility(View.GONE); holder.iv_error.setAnimation(null); holder.iv_error.setVisibility(View.GONE); if("1".equals(list.get(position).capsule) && "1".equals(list.get(position).burn_after_reading)){ holder.iv_throwaway.setVisibility(View.VISIBLE); }else{ holder.iv_throwaway.setVisibility(View.GONE); } holder.tv_time.setText(DateUtils.getMyCommonShowDate(list.get(position).update_time)); holder.iv_jiaobiao.setVisibility(View.GONE); if(list.get(position).commentnum!=null && !list.get(position).commentnum.equals("0")){ if(list.get(position).commentnum.length()>1){ holder.iv_jiaobiao.setVisibility(View.VISIBLE); holder.iv_jiaobiao.setImageResource(R.drawable.jiaobiao_2); }else if(list.get(position).commentnum.length()==1 && !list.get(position).commentnum.trim().equals("0")){ holder.iv_jiaobiao.setVisibility(View.VISIBLE); holder.iv_jiaobiao.setImageResource(R.drawable.jiaobiao_1); } holder.tv_count.setVisibility(View.VISIBLE); holder.tv_count.setText(list.get(position).commentnum); holder.vctv_vshare.setViewIsShowComment(false); }else{ holder.tv_count.setVisibility(View.GONE); holder.iv_jiaobiao.setVisibility(View.GONE); } //(capsule为“0”&& is_clear为“0”)||(capsule为“1” && is_clear为0 && 到期) if(("0".equals(list.get(position).capsule) && "0".equals(list.get(position).is_clear) && !ActiveAccount.getInstance(context).getUID().equals(list.get(position).micuserid)) || ("1".equals(list.get(position).capsule) && "0".equals(list.get(position).is_clear) && TimeHelper.getInstance().now() >= Long.parseLong(list.get(position).capsule_time))){ holder.vctv_vshare.setViewIsShowComment(true); }else{ holder.vctv_vshare.setViewIsShowComment(false); } if("1".equals(list.get(position).capsule) && "0".equals(list.get(position).is_clear)){ String str = "<font color=\"black\">距离开启:</font>" + "<font color=\"" + context.getResources().getColor(R.color.blue)+ "\">" + DateUtils.getCountdown(list.get(position).capsule_time) + "</font>"; holder.tv_lastMessage.setText(Html.fromHtml(str)); }else{ if(TextUtils.isEmpty(list.get(position).newcomment)){ //holder.tv_lastMessage.setText(list.get(position).micusernames); FriendsExpressionView.replacedExpressions(list.get(position).micusernames, holder.tv_lastMessage); }else{ FriendsExpressionView.replacedExpressions(list.get(position).newcomment, holder.tv_lastMessage); } } // holder.tv_content.setText(list.get(position).mic_title); if(TextUtils.isEmpty(list.get(position).content)){ String content = "";// 1视频、2音频 3图片 Boolean hasVideo = false, hasAudio = false, hasPic = false; for(int i=0; i< list.get(position).diarys.length; i++){ if("1".equals(list.get(position).diarys[i].type)){ hasVideo = true; }else if("2".equals(list.get(position).diarys[i].type)){ hasAudio = true; }else if("3".equals(list.get(position).diarys[i].type)){ hasPic = true; } } if(hasVideo) content = "[视频]"; if(hasPic) content = content + "[图片]"; if(hasAudio) content = content + "[音频]"; holder.tv_content.setText(content); }else{ FriendsExpressionView.replacedExpressions(list.get(position).content, holder.tv_content); } if(!isForTimer){ holder.vctv_vshare.setContentDiaries(list.get(position).headimageurl, null, list.get(position).capsule, list.get(position).burn_after_reading, list.get(position).is_clear, list.get(position).diarys); } if("1".equals(list.get(position).is_undisturb)){ holder.vctv_vshare.setViewIsShowUndisturb(true); }else{ holder.vctv_vshare.setViewIsShowUndisturb(false); } if("0".equals(list.get(position).getUpload_status()) || "2".equals(list.get(position).getUpload_status())){ RotateAnimation myAnimation_Rotate=new RotateAnimation(0.0f, 719f, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f); holder.iv_error.setImageResource(R.drawable.vshare_loading); holder.iv_error.setVisibility(View.VISIBLE); myAnimation_Rotate.setDuration(1200); myAnimation_Rotate.setRepeatCount(-1); myAnimation_Rotate.setInterpolator(new LinearInterpolator()); holder.iv_error.setAnimation(myAnimation_Rotate); myAnimation_Rotate.start(); holder.tv_time.setVisibility(View.GONE); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.tv_content.getLayoutParams(); params.rightMargin = DensityUtil.dip2px(context, 35); holder.tv_content.setLayoutParams(params); }else if("1".equals(list.get(position).getUpload_status())){ holder.iv_error.setImageResource(R.drawable.yichang); holder.iv_error.setAnimation(null); holder.iv_error.setVisibility(View.VISIBLE); holder.tv_time.setVisibility(View.GONE); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.tv_content.getLayoutParams(); params.rightMargin = DensityUtil.dip2px(context, 35); holder.tv_content.setLayoutParams(params); }else if("3".equals(list.get(position).getUpload_status()) || "".equals(list.get(position).getUpload_status())){ holder.iv_error.setAnimation(null); holder.iv_error.setImageBitmap(null); holder.tv_time.setVisibility(View.VISIBLE); holder.iv_error.setVisibility(View.GONE); } return convertView; } public void setData(List<MicListItem> data){ if(data != null && data.size()>0){ this.list.clear(); this.list.addAll(data); }else{ this.list.clear(); this.list.add(new MicListItem()); } } /* public void addPreData(List<MicListItem> predata) { if (predata==null ||predata.size() <= 0) { return; } int i = 0; while (i < predata.size()) { list.add(i, predata.get(i)); i++; } notifyDataSetChanged(); } public void addAfterData(List<MicListItem> afterdata) { if (afterdata == null || afterdata.size() <= 0) { return; } list.addAll(afterdata); notifyDataSetChanged(); } */ public boolean isEmpty() { return list.isEmpty(); } public List<MicListItem> getDatas(){ return list; } public MicListItem findItemByPublishId(String publishid){ if(TextUtils.isEmpty(publishid)) return null; for(int i=0;i<list.size();i++){ if(publishid.equals(list.get(i).publishid)){ return list.get(i); } } return null; } public class ViewHolder { VshareContentThumbnailView vctv_vshare; TextView tv_time; TextView tv_lastMessage; TextView tv_count; ImageView iv_jiaobiao; TextView tv_content; ImageView iv_error; ImageView iv_nodata; RelativeLayout rl_content; ImageView iv_line; ImageView iv_throwaway; } }
ed7fb5ecf1efbfd2823c2bf8a5623f67c6db1137
0220b28450688f1a25ec86dbec215a99816bf619
/solution-assets-Resource_Tracking_Management/SourceCode/SpringBoot/ResourceTrackingManagement/src/main/java/com/resourcetrackingmgmt/repository/RoleRepository.java
e95dfac3f94fed599c97529549c0426b020f526e
[]
no_license
13pa1a0505/Resource-Tracking-Management
442897c625193b91c971ed1b9b9db2e9e74cee4c
eabf6dc74eed84bbac13868a3b925a21b83c1cbb
refs/heads/master
2023-02-07T06:22:59.280174
2019-05-30T07:20:44
2019-05-30T07:20:44
189,365,788
0
0
null
2023-02-02T04:17:51
2019-05-30T07:20:04
Rich Text Format
UTF-8
Java
false
false
325
java
package com.resourcetrackingmgmt.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.resourcetrackingmgmt.model.Roles; /** * @author Kranthichandu * */ @Repository public interface RoleRepository extends JpaRepository<Roles, Long> { }
1be56afb10bffae0530a1c16497255fbab80b4e7
ec04f81bd35a5352d12a5dba4b3791ad39a5ae01
/Phone Book/task/src/phonebook/Sort.java
3ddf3785230d9eef523bcedde2c6c8531a3ab50c
[]
no_license
AskarR42/Phone_Book
7aa20e15d9c1d062dc0ce33053b13c4590fb76e8
47f3fa3abc85a9b6a008806d17d5a665b00bb7c5
refs/heads/master
2023-04-29T01:38:07.008682
2021-05-07T15:57:12
2021-05-07T15:57:12
365,282,720
0
0
null
null
null
null
UTF-8
Java
false
false
1,928
java
package phonebook; import java.time.Instant; import java.time.Duration; public class Sort { public static PhoneBook bubbleSortPhoneBookAlphabetically(PhoneBook unsortedPhoneBook, Duration timeOfLinearSearch) { Instant start = Instant.now(); Person[] people = unsortedPhoneBook.getPeople(); for (int i = 0; i < people.length; i++) { if (timeOfLinearSearch.multipliedBy(10).compareTo(Duration.between(start, Instant.now())) < 0) { return null; } for (int j = 0; j < people.length - 1 - i; j++) { if (people[j].getName().compareTo(people[j + 1].getName()) > 0) { swap(people, j, j + 1); } } } return new PhoneBook(people); } public static PhoneBook quickSortPhoneBookAlphabetically(PhoneBook unsortedPhoneBook) { Person[] people = unsortedPhoneBook.getPeople(); quickSort(people, 0, people.length - 1); return new PhoneBook(people); } private static void quickSort(Person[] people, int left, int right) { if (left < right) { int pivotIndex = partition(people, left, right); quickSort(people, left, pivotIndex - 1); quickSort(people, pivotIndex + 1, right); } } private static int partition(Person[] people, int left, int right) { Person pivot = people[right]; int partitionIndex = left; for (int i = left; i < right; i++) { if (people[i].getName().compareTo(pivot.getName()) < 0) { swap(people, i, partitionIndex); partitionIndex++; } } swap(people, partitionIndex, right); return partitionIndex; } private static void swap(Person[] people, int i, int j) { Person t = people[i]; people[i] = people[j]; people[j] = t; } }
f60b455b94d40c64732d37485f55b0421ccfc15b
2db2c724dcaf2bee925baba4f6470ff6671d5015
/src/main/java/com/toy/repository/StudentRepository.java
569b824f5d6e2cbe0da0dd71eb78d12bc69f58b9
[ "Apache-2.0" ]
permissive
ZhangX-Byte/toy-test
81c0ddd2b8114c8ef2323418664d736abf06c200
ee08b1929ab12a70341fd0a53277b527fcb62289
refs/heads/master
2023-04-30T07:12:47.879362
2021-04-19T01:06:09
2021-04-19T01:06:09
357,410,368
2
0
null
null
null
null
UTF-8
Java
false
false
305
java
package com.toy.repository; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.toy.domain.Student; import org.springframework.stereotype.Repository; /** * @author Zhang_Xiang * @since 2021/4/9 11:41:35 */ @Repository public interface StudentRepository extends BaseMapper<Student> { }
306c558abe4b235c58c7ee44cf6ec19b1baade8e
95a78e0766815affcda3d4c61bb995a8235f7659
/html/ScrollBarDemo.java
4db6aa42bb7b19def996b763c4502a0566410941
[]
no_license
Hongclass/Java
480f98d1c77ca95c9b128ce2073e9cb45d62885c
a74a0fcc75063c076e14e80a3507cfb203015b02
refs/heads/master
2021-01-01T04:30:14.555768
2016-05-10T20:57:45
2016-05-10T20:57:45
58,492,821
0
0
null
null
null
null
UTF-8
Java
false
false
1,923
java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ScrollBarDemo extends JFrame { // Create horizontal and vertical scroll bars private JScrollBar jscbHort = new JScrollBar(JScrollBar.HORIZONTAL); private JScrollBar jscbVert = new JScrollBar(JScrollBar.VERTICAL); // Create a MessagePanel private MessagePanel messagePanel = new MessagePanel("Welcome to Java"); public static void main(String[] args) { ScrollBarDemo frame = new ScrollBarDemo(); frame.setTitle("ScrollBarDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public ScrollBarDemo() { // Add scroll bars and message panel to the frame setLayout(new BorderLayout()); add(messagePanel, BorderLayout.CENTER); add(jscbVert, BorderLayout.EAST); add(jscbHort, BorderLayout.SOUTH); // Register listener for the scroll bars jscbHort.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jscbHort.getValue(); double maximumValue = jscbHort.getMaximum(); double newX = (value * messagePanel.getWidth() / maximumValue); messagePanel.setXCoordinate((int) newX); } }); jscbVert.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jscbVert.getValue(); double maximumValue = jscbVert.getMaximum(); double newY = (value * messagePanel.getHeight() / maximumValue); messagePanel.setYCoordinate((int)newY); } }); } }
69e6b0bb608294e269169e4d3f8f1ada06eed85b
183807c477564970236e1c97c71f46c431c3b4f6
/src/iamandroid/ui/dialogs/MapOfStringsInputDialog.java
ec748c0c680949a4f918317737f2d6d54a320855
[]
no_license
bincker/IAmandroid
db2ae5fd0d744206bbd273262b96894e81f2e997
b0e54be02aa45f16da4ae6a3b3e2620702f0d8e6
refs/heads/master
2021-01-16T22:53:33.539850
2014-05-17T20:01:50
2014-05-17T20:01:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
940
java
/** * Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package iamandroid.ui.dialogs; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; /** * @author fabioz */ public abstract class MapOfStringsInputDialog extends AbstractMapOfStringsInputDialog { public MapOfStringsInputDialog(Shell shell, String dialogTitle, String dialogMessage, Map<String, String> map) { super(shell, dialogTitle, dialogMessage, map); } @Override protected String handleBrowseButton() { FileDialog dialog = new FileDialog(getShell(), SWT.OPEN); String file = dialog.open(); return file; } }
a4a25735fb0ec7d18d92b3b2e85419b5a4b73a4b
29874287392d09b015bb2cb784798b76706aaf67
/yydp/src/main/java/org/lf/yydp/etl/loader/BaseLoader.java
6f6b5f9d811672cc590c9c5fda13976382ff6d13
[]
no_license
tanbinh123/yydp
a95d724c439c0459d4b3c7221ca860e68e51afce
a6611c202a0c69a5eb5c43b715167b4e722fe264
refs/heads/master
2023-03-15T13:05:38.317485
2016-12-23T04:35:00
2016-12-23T04:35:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
120
java
package org.lf.yydp.etl.loader; public abstract class BaseLoader { public abstract boolean load(String url); }
9473428edfc53e34fd82983065760de31b4e82f5
1ebd71e2179be8a2baec90ff3f326a3f19b03a54
/hybris/bin/platform/ext/core/testsrc/de/hybris/platform/core/initialization/testbeans/TestPatchBean.java
4eaee1dfb8cd5759023fd9326a10803dde6544a3
[]
no_license
shaikshakeeb785/hybrisNew
c753ac45c6ae264373e8224842dfc2c40a397eb9
228100b58d788d6f3203333058fd4e358621aba1
refs/heads/master
2023-08-15T06:31:59.469432
2021-09-03T09:02:04
2021-09-03T09:02:04
402,680,399
0
0
null
null
null
null
UTF-8
Java
false
false
469
java
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.core.initialization.testbeans; import de.hybris.platform.constants.CoreConstants; import de.hybris.platform.core.initialization.SystemSetup; @SystemSetup(extension = CoreConstants.EXTENSIONNAME) public class TestPatchBean { @SystemSetup(patch = true) public void requiredPatch() { } @SystemSetup(patch = true) public void optionalPatch() { } }
4215c4babc83f825be617ffd14f7b36d886c58d3
b98b68fb955624750d7f25eb1bc6f1ea0ac38a84
/kernel/data-pipeline/api/src/main/java/org/apache/shardingsphere/data/pipeline/api/ingest/position/PrimaryKeyPositionFactory.java
da318934adec24f4f51a08ee30b27c9a219a0718
[ "Apache-2.0" ]
permissive
lastincisor/shardingsphere
0ce291ad528fd2c721d422d7bd17cccbd46e5644
be9d8b2fb1be4ea4c4b2987654e9d6d19b13fd55
refs/heads/master
2023-02-26T15:00:43.046331
2023-02-10T04:02:02
2023-02-10T04:02:02
262,223,192
0
0
null
null
null
null
UTF-8
Java
false
false
2,788
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF 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 org.apache.shardingsphere.data.pipeline.api.ingest.position; import com.google.common.base.Preconditions; import lombok.NonNull; /** * Primary key position factory. */ public final class PrimaryKeyPositionFactory { /** * New instance by string data. * * @param data string data * @return primary key position */ public static IngestPosition<?> newInstance(final String data) { String[] array = data.split(","); Preconditions.checkArgument(3 == array.length, "Unknown primary key position: " + data); Preconditions.checkArgument(1 == array[0].length(), "Invalid primary key position type: " + array[0]); char type = array[0].charAt(0); String beginValue = array[1]; String endValue = array[2]; switch (type) { case 'i': return new IntegerPrimaryKeyPosition(Long.parseLong(beginValue), Long.parseLong(endValue)); case 's': return new StringPrimaryKeyPosition(beginValue, endValue); case 'n': return new NoUniqueKeyPosition(); default: throw new IllegalArgumentException("Unknown primary key position type: " + type); } } /** * New instance by begin value and end value. * * @param beginValue begin value * @param endValue end value * @return ingest position */ public static IngestPosition<?> newInstance(final @NonNull Object beginValue, final @NonNull Object endValue) { if (beginValue instanceof Number) { return new IntegerPrimaryKeyPosition(((Number) beginValue).longValue(), ((Number) endValue).longValue()); } if (beginValue instanceof CharSequence) { return new StringPrimaryKeyPosition(beginValue.toString(), endValue.toString()); } throw new IllegalArgumentException("Unknown begin value type: " + beginValue.getClass().getName()); } }
697086c45fc855f50ec9f62d8589d9391ffc8bfe
148f8ef23a0878bdccb34d13aeac9643de372551
/src/ffm/slc/model/resources/RecognitionDescription.java
c337177283c31e178992f1aae4afd39453d03da0
[]
no_license
hrkipp/slcdemo
27e853136c7e52fe083b7367664ae4af7d9dfe86
54882e359bb59f04d20e67d8a19652840159ee22
refs/heads/master
2021-01-22T11:51:01.945793
2013-01-13T23:07:18
2013-01-13T23:07:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
228
java
package ffm.slc.model.resources; /** * The description of recognition given to the student for accomplishments in a co-curricular, or extra-curricular activity.. */ public class RecognitionDescription extends StringResource{}
eeb4d78453a5b1686c7ea5c66d38325dbfd7483b
b63fae70900031ab7e9de73d59e335b8fa3e4107
/app/src/main/java/com/yocn/meida/gles/render/SimpleColorRender.java
21b682132a8044d25b6c250b0c809dd8104853a7
[ "Apache-2.0" ]
permissive
yocn/AndroidMediaCodec
d12e8e918ebf6e00905c3e51226be2df230499fc
85db839b3dabf8e1e41e54aa4d46f330d3bdd9b5
refs/heads/master
2023-03-08T12:36:03.001295
2023-02-27T12:12:15
2023-02-27T12:12:15
200,152,483
110
44
null
2021-08-14T14:49:56
2019-08-02T02:42:37
C
UTF-8
Java
false
false
672
java
package com.yocn.meida.gles.render; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; public class SimpleColorRender implements GLSurfaceView.Renderer { @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //设置清屏颜色 gl.glClearColor(1.0f, 0.3f, 0.2f, 1.0f); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl) { gl.glClear(GLES20.GL_COLOR_BUFFER_BIT); } }
a93ae4c2210a957cae444ad968f79cfa99decf32
7ee2d8251994c033d259f6cae39b0f2249385714
/OKHTTP/src/main/java/com/cdc/okhttp/OkHttpUtil.java
879f63cf9cc86470dae7ab487f0debe7f0d4a075
[]
no_license
cdcdec/JavaCode
b0bdb8d744f64adcafe01c1d7737bf91e0a37978
00598f1418b5ce01d3ef70267b61bf89559b3791
refs/heads/master
2020-04-22T22:22:55.103540
2019-05-20T03:24:15
2019-05-20T03:24:15
170,706,062
0
0
null
null
null
null
UTF-8
Java
false
false
3,412
java
package com.cdc.okhttp; import okhttp3.*; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import java.io.IOException; import java.util.concurrent.TimeUnit; public class OkHttpUtil { public final MockWebServer server = new MockWebServer(); public OkHttpClient getHttpClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.eventListener(new RecordingEventListener()); builder.connectTimeout(1L, TimeUnit.SECONDS); builder.callTimeout(1L, TimeUnit.SECONDS); OkHttpClient okHttpClient = builder.build(); return okHttpClient; } public Request getRequest(String url) { Request request = new Request.Builder() .get() .url(url) .build(); return request; } public void get(Callback callback, String url) { Call call = getHttpClient().newCall(getRequest(url)); call.enqueue(callback); } /** * post上传参数 键值对 * @param callback * @param url */ public void post(Callback callback, String url) { //Form表单格式的参数传递 FormBody formBody = new FormBody.Builder() .add("mobile", "18903958133") .add("code", "") .add("type", "1") .build(); Request request = new Request.Builder() .post(formBody) .url(url) .build(); Call call = getHttpClient().newCall(request); call.enqueue(callback); } public void postJsonStr(Callback callback){ //上传的字符串 RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{\"username\":\"admin\";\"password\":\"admin\"}"); server.enqueue(new MockResponse() .setResponseCode(200) //返回的字符串 .setBody("{\"username\":\"admin\";\"password\":\"admin\",\"type\":1}")); Request request = new Request.Builder() .post(requestBody) .url(server.url("/")) .build(); Call call = getHttpClient().newCall(request); call.enqueue(callback); } private Request.Builder getRequestBuilder(String path, String... headers){ Request.Builder builder = new Request.Builder(); builder.url(path); for (int i = 0, size = headers.length; i < size; i += 2) { builder.addHeader(headers[i], headers[i + 1]); } return builder; } public void head(){ server.enqueue(new MockResponse() .setResponseCode(200) .setBody("abc") .clearHeaders() .addHeader("content-type: text/plain") .addHeader("content-length", "3") ); Request request = new Request.Builder() .url(server.url("/")) .build(); Call call = getHttpClient().newCall(request); try { Response response=call.execute(); LogUtil.w(response.body().string()); LogUtil.w(response.header("content-type")); LogUtil.w(response.header("content-length")); } catch (IOException e) { e.printStackTrace(); } } }
60c6163350228e2e86047e58fef7526262532e9e
69c00032e21079eb41b86c2085d38b8ba3e6e5cb
/Development_library/05Coding/安卓/andr_c/src/com/huift/hfq/cust/model/ValidatePayPwdTask.java
062f7ff3114e263344000e1aa88bd2f1be8f4207
[]
no_license
qiaobenlaing/coupon
476b90ac9c8a9bb56f4c481c3e0303adc9575133
32a53667f0c496cda0d7df71651e07f0138001d3
refs/heads/master
2023-01-20T03:40:42.118722
2020-11-20T00:59:29
2020-11-20T01:13:28
312,522,162
0
0
null
null
null
null
UTF-8
Java
false
false
2,199
java
package com.huift.hfq.cust.model; import java.util.LinkedHashMap; import net.minidev.json.JSONObject; import android.app.Activity; import android.util.Log; import com.huift.hfq.base.SzException; import com.huift.hfq.base.Util; import com.huift.hfq.base.api.API; import com.huift.hfq.base.data.DB; import com.huift.hfq.base.model.SzAsyncTask; import com.huift.hfq.base.pojo.UserToken; import com.huift.hfq.cust.R; /** * 验证支付密码是否正确 * @author yingchen * */ public class ValidatePayPwdTask extends SzAsyncTask<String, Integer, Integer>{ private static final String TAG = ValidatePayPwdTask.class.getSimpleName(); /**定义一个成功的结果码*/ private static final int RIGHT_CODE = 1; /**定义一个请求失败的结果码*/ private static final int ERROR_CODE = 0; private CallBack mCallBack; private JSONObject mResult; public ValidatePayPwdTask(Activity acti) { super(acti); } public ValidatePayPwdTask(Activity acti, CallBack mCallBack) { super(acti); this.mCallBack = mCallBack; } public interface CallBack{ public void getResult(JSONObject result); } @Override protected Integer doInBackground(String... params) { UserToken userToken = DB.getObj(DB.Key.CUST_USER_TOKEN, UserToken.class); LinkedHashMap<String, Object> reqparams = new LinkedHashMap<String, Object>(); reqparams.put("userCode", userToken.getUserCode()); reqparams.put("payPwd", params[0]); reqparams.put("tokenCode", userToken.getTokenCode()); try { mResult = (JSONObject) API.reqCust("validatePayPwd", reqparams); if(null != mResult){ Log.d(TAG, "ValidatePayPwdTask == "+mResult.toString()); return RIGHT_CODE; }else{ return ERROR_CODE; } } catch (SzException e) { this.mErrCode=e.getErrCode(); return this.mErrCode.getCode(); } } @Override protected void handldBuziRet(int retCode) { switch (retCode) { case RIGHT_CODE: mCallBack.getResult(mResult); break; case ERROR_CODE: mCallBack.getResult(null); Util.getContentValidate(R.string.check_pay_password_fail); default: mCallBack.getResult(null); Util.getContentValidate(R.string.check_pay_password_fail); break; } } }
f488e7e339aff13bbd1db6074d14f14a54afcfbe
0c1613405bec36e9a00470d975617c29b0b3e8dc
/src/main/java/com/ilsid/bfa/graph/FlowChartJsConverter.java
b25b3e10df92f138432367ed80a36fde3f59dbed
[]
no_license
ilsid/BFA
95b66a09e2d0a64d4600d7704e75d5c157968f62
6f394357b68ebbf1a6c6efe132a10de87441737d
refs/heads/master
2022-08-04T03:43:00.246238
2019-12-02T08:55:13
2019-12-02T08:55:13
43,561,765
1
0
null
2022-07-07T22:06:17
2015-10-02T15:49:52
Java
UTF-8
Java
false
false
2,757
java
package com.ilsid.bfa.graph; import java.util.HashMap; import java.util.Map; import com.ilsid.bfa.flow.FlowConstants; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; /** * Converts script's graph representation into <a href="http://flowchart.js.org">flowchart.js</a> format. * * @author illia.sydorovych * */ public class FlowChartJsConverter { private static final String LF = "\n"; private static final String VERTEX_DEF_SEPARATOR = "=>"; private static final String EDGE_ARROW = "->"; private static final String COLON = ": "; private static final char LB = '('; private static final char RB = ')'; private static final Map<String, String> DEF_TYPE_MAP; private static final Map<String, String> LABEL_MAP; static { DEF_TYPE_MAP = new HashMap<>(); DEF_TYPE_MAP.put(FlowConstants.START, "start"); DEF_TYPE_MAP.put(FlowConstants.END, "end"); DEF_TYPE_MAP.put(FlowConstants.OPERATION, "operation"); DEF_TYPE_MAP.put(FlowConstants.CONDITION, "condition"); DEF_TYPE_MAP.put(FlowConstants.SUBFLOW, "subroutine"); LABEL_MAP = new HashMap<>(); LABEL_MAP.put(FlowConstants.YES_LABEL, "yes"); LABEL_MAP.put(FlowConstants.NO_LABEL, "no"); } /** * Build script's flow representation. * * @param source * script's source code * @return flowchart.js representation of script's flow. */ public static String buildFlowChart(String source) { Graph graph = FlowGraphBuilder.buildGraph(source); String flowChartJsCode = convertToFlowChartJs(graph); return flowChartJsCode; } private static String convertToFlowChartJs(Graph graph) { StringBuilder lines = new StringBuilder(); for (Vertex vertex : GraphUtil.getSortedByIdVertices(graph)) { StringBuilder vertexDef = new StringBuilder(); String name = vertex.getProperty(FlowConstants.NAME_PROPERTY); String type = vertex.getProperty(FlowConstants.TYPE_PROPERTY); vertexDef.append(vertex.getId()).append(VERTEX_DEF_SEPARATOR).append(DEF_TYPE_MAP.get(type)).append(COLON) .append(name); lines.append(vertexDef.toString()).append(LF); } lines.append(LF); for (Edge edge : GraphUtil.getSortedByIdEdges(graph)) { StringBuilder edgeDef = new StringBuilder(); edgeDef.append(edge.getVertex(Direction.OUT).getId()); String label = LABEL_MAP.get(edge.getLabel()); if (label != null) { edgeDef.append(LB).append(label).append(RB); } edgeDef.append(EDGE_ARROW).append(edge.getVertex(Direction.IN).getId()); lines.append(edgeDef).append(LF); } return lines.toString(); } }
b53b6c013820281b580bf29f6ee6fad16a2c04c0
c04ddfcec02c7754bd049b44810030d330416fb9
/src/main/java/com/homedepot/pip/input/Price.java
ad4d2dc14a06132120f71ba4574df6b069b36027
[]
no_license
karuppannanp/api-mock
f44c62d35d10ee8596c3547cd9d8712c8b61e81c
0702bba42e32e837840cd32b7ae1197801ec0056
refs/heads/develop
2021-01-11T04:00:33.940447
2016-12-16T22:08:56
2016-12-16T22:08:56
71,261,376
0
0
null
2016-12-08T15:41:09
2016-10-18T15:14:10
Java
UTF-8
Java
false
false
2,039
java
package com.homedepot.pip.input; public class Price { private String uom; private Double originalPrice; private Double specialPrice; private Double specialBuyPrice; private Boolean mapAboveOriginalPrice; private boolean alternatePriceDisplay; private String unitsPerCase = "0.0"; private String caseUnitUom; private Double bulkPrice; private Double bulkPriceThresholdQty; public String getUom() { return uom; } public void setUom(String uom) { this.uom = uom; } public Double getOriginalPrice() { return originalPrice; } public void setOriginalPrice(Double originalPrice) { this.originalPrice = originalPrice; } public Double getSpecialPrice() { return specialPrice; } public void setSpecialPrice(Double specialPrice) { this.specialPrice = specialPrice; } public Double getSpecialBuyPrice() { return specialBuyPrice; } public void setSpecialBuyPrice(Double specialBuyPrice) { this.specialBuyPrice = specialBuyPrice; } public Boolean getMapAboveOriginalPrice() { return mapAboveOriginalPrice; } public void setMapAboveOriginalPrice(Boolean mapAboveOriginalPrice) { this.mapAboveOriginalPrice = mapAboveOriginalPrice; } public Boolean getAlternatePriceDisplay() { return alternatePriceDisplay; } public void setAlternatePriceDisplay(Boolean alternatePriceDisplay) { this.alternatePriceDisplay = alternatePriceDisplay; } public String getUnitsPerCase() { return unitsPerCase; } public void setUnitsPerCase(String unitsPerCase) { this.unitsPerCase = unitsPerCase; } public String getCaseUnitUom() { return caseUnitUom; } public void setCaseUnitUom(String caseUnitUom) { this.caseUnitUom = caseUnitUom; } public Double getBulkPrice() { return bulkPrice; } public void setBulkPrice(Double bulkPrice) { this.bulkPrice = bulkPrice; } public Double getBulkPriceThresholdQty() { return bulkPriceThresholdQty; } public void setBulkPriceThresholdQty(Double bulkPriceThresholdQty) { this.bulkPriceThresholdQty = bulkPriceThresholdQty; } }
d8efa27e09ed21b3abd641807dbd62bdf9991eb1
9757f1fd900277a316bc480a0eed70b0e6310514
/app/src/main/java/boutlinetesttwitter/com/vishnu/boutlinetwitter/FeedsContract.java
6e281770a0b49c7cd69f047c7c2a38ff5512bd7b
[ "MIT" ]
permissive
meggie10cn/WC15Twitter
e5024a43c7f5a2697a9f0e6301c9b17b2367b007
3ccf58a0b9b8609cf4cea595fc9dd263121ac29b
refs/heads/master
2020-12-31T03:02:53.074041
2015-06-26T13:22:47
2015-06-26T13:22:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,089
java
package boutlinetesttwitter.com.vishnu.boutlinetwitter; import android.content.ContentResolver; import android.net.Uri; import android.provider.BaseColumns; /** * Created by Vishnu on 09-Mar-15. */ public class FeedsContract { public static final String DB_NAME = "boutlinetesttwitter.com.vishnu.boutlinetwitter.feeds"; public static final int DB_VERSION = 1; public static final String TABLE = "feeds"; public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/example.tasksDB/" + TABLE; public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/example/tasksDB" + TABLE; public static final String AUTHORITY = "boutlinetesttwitter.com.vishnu.boutlinetwitter.twitterFeeds"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE); public static final int TASKS_LIST = 1; public static final int TASKS_ITEM = 2; public class Columns { public static final String STATUS = "status"; public static final String _ID = BaseColumns._ID; } }
6f66ca1e2f9fbce8f0a8edf0308c9ed165ec3e05
f88f6a591921eeee5ae6c7f5c49cfce1b4823ba3
/app/src/main/java/com/example/limiketang/core/XArrowAtom.java
38e567ba553a0ecd5c443f3f0882d33285e0579c
[]
no_license
awesomeyin/lateX
d6a51e079e06affaa4ec257d863e769a63b225ce
98bf5b025e109e3be3db55e888d88f36d5a32fb1
refs/heads/master
2022-06-14T10:03:08.268562
2020-05-06T01:52:48
2020-05-06T01:52:48
261,625,578
0
0
null
null
null
null
UTF-8
Java
false
false
2,908
java
/* XArrowAtom.java * ========================================================================= * This file is part of the JLaTeXMath Library - http://forge.scilab.org/jlatexmath * * Copyright (C) 2009 DENIZET Calixte * * 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 2 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. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * */ package com.example.limiketang.core; /** * An atom representing an extensible left or right arrow to handle xleftarrow * and xrightarrow commands in LaTeX. */ public class XArrowAtom extends Atom { private Atom over, under; private boolean left; public XArrowAtom(Atom over, Atom under, boolean left) { this.over = over; this.under = under; this.left = left; } public Box createBox(TeXEnvironment env) { TeXFont tf = env.getTeXFont(); int style = env.getStyle(); Box O = over != null ? over.createBox(env.supStyle()) : new StrutBox(0, 0, 0, 0); Box U = under != null ? under.createBox(env.subStyle()) : new StrutBox( 0, 0, 0, 0); Box oside = new SpaceAtom(TeXConstants.UNIT_EM, 1.5f, 0, 0) .createBox(env.supStyle()); Box uside = new SpaceAtom(TeXConstants.UNIT_EM, 1.5f, 0, 0) .createBox(env.subStyle()); Box sep = new SpaceAtom(TeXConstants.UNIT_MU, 0, 2f, 0).createBox(env); float width = Math.max(O.getWidth() + 2 * oside.getWidth(), U.getWidth() + 2 * uside.getWidth()); Box arrow = XLeftRightArrowFactory.create(left, env, width); Box ohb = new HorizontalBox(O, width, TeXConstants.ALIGN_CENTER); Box uhb = new HorizontalBox(U, width, TeXConstants.ALIGN_CENTER); VerticalBox vb = new VerticalBox(); vb.add(ohb); vb.add(sep); vb.add(arrow); vb.add(sep); vb.add(uhb); float h = vb.getHeight() + vb.getDepth(); float d = sep.getHeight() + sep.getDepth() + uhb.getHeight() + uhb.getDepth(); vb.setDepth(d); vb.setHeight(h - d); HorizontalBox hb = new HorizontalBox(vb, vb.getWidth() + 2 * sep.getHeight(), TeXConstants.ALIGN_CENTER); return hb; } }
[ "123qwe890" ]
123qwe890
1e3d04739335826e08b007f153327ee31c373686
bbffc7d397b52c9512bb5b346b4d3b9632d92f5a
/EVA1_PRACTICAS_15551429/EVA1_3_LINEAR_LAYOUT/app/src/main/java/com/example/javierconde/eva1_3_linear_layout/Principal.java
4ed64acd6d648a388591b604c7aa903b97aba709
[]
no_license
javierConde1/PRACTICAS
e44982050308030f413396e6cdd40ca7819bd26b
eb11373c848828e73d2cead11368d36dea18d61f
refs/heads/master
2020-03-30T02:54:57.603197
2018-09-30T18:22:14
2018-09-30T18:22:14
150,658,144
0
0
null
null
null
null
UTF-8
Java
false
false
359
java
package com.example.javierconde.eva1_3_linear_layout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Principal extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_principal); } }
fbd4602c8486a9b9c3486af9f98535c7f30e8e06
b0091bf39351841e74be42333cc723a86cc40c63
/Android/Bakkle/app/src/main/java/com/bakkle/bakkle/Models/FeedItem.java
d67ee23b3cbda91c8d9a9ba627b7807a22c2a645
[]
no_license
BechirAhmed/Bakkle
b5e09cea84c86c6252fdc9c40b43912a4ca729a3
00b1d866f84b835a8c78bf117c80072d46c3aaae
refs/heads/master
2020-12-03T00:41:36.610626
2016-04-26T04:23:01
2016-04-26T04:23:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,327
java
package com.bakkle.bakkle.Models; import com.bakkle.bakkle.Models.Person; import java.io.Serializable; /** * Created by vanshgandhi on 12/5/15. */ public class FeedItem implements Serializable { private String status; private String description; private String price; private String[] image_urls; private String post_date; private String title; private Person seller; private String location; private String method; private int pk; private int numViews; private int numNope; private int numWant; private int numHolding; private int numReport; private int convosWithNewMessage; public FeedItem() { setSeller(new Person()); } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String[] getImage_urls() { return image_urls; } public void setImage_urls(String[] image_urls) { this.image_urls = image_urls; } public String getPost_date() { return post_date; } public void setPost_date(String post_date) { this.post_date = post_date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Person getSeller() { return seller; } public void setSeller(Person seller) { this.seller = seller; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getPk() { return pk; } public void setPk(int pk) { this.pk = pk; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public int getNumViews() { return numViews; } public void setNumViews(int numViews) { this.numViews = numViews; } public int getNumNope() { return numNope; } public void setNumNope(int numNope) { this.numNope = numNope; } public int getNumWant() { return numWant; } public void setNumWant(int numWant) { this.numWant = numWant; } public int getNumHolding() { return numHolding; } public void setNumHolding(int numHolding) { this.numHolding = numHolding; } public int getNumReport() { return numReport; } public void setNumReport(int numReport) { this.numReport = numReport; } public int getConvosWithNewMessage() { return convosWithNewMessage; } public void setConvosWithNewMessage(int convosWithNewMessage) { this.convosWithNewMessage = convosWithNewMessage; } }
b9f9a30eaa331c411327b25ddc3b089c11332c90
b7a34cd20de2a6aaf593de315e82196cf05c57ef
/src/Hilos/HiloCongelar.java
9f59a98737cb7d766ffffe446dd6355365dc2c5e
[]
no_license
pierrfacu/ProyectoTDP_Comision6
3d7c80756d01f77f17d3f8ec15afbd63a5265b95
d5963df063c67fc397e5fcb0a11a32ae8f2926ed
refs/heads/master
2020-03-27T08:12:21.299337
2018-11-28T22:24:41
2018-11-28T22:24:41
146,230,643
0
0
null
null
null
null
UTF-8
Java
false
false
1,190
java
package Hilos; import java.util.HashMap; import java.util.LinkedList; import Entidades.Enemigos.Enemigo; import Inteligencia.Congelado; import Inteligencia.Inteligencia; import Juego.JuegoHilo; /** * Clase HiloCongelar que extiende de Thread. * @author Aldana Casé (104870), Facundo Pierrestegui (99694), Stefania Heinrich (106205). * */ public class HiloCongelar extends Thread{ //Constructor public HiloCongelar(){ } //Metodos public void run() { JuegoHilo juego = JuegoHilo.getInstance(); LinkedList<Enemigo> enemigos = juego.obtenerEnemigos(); HashMap<Enemigo, Inteligencia> backupInt = new HashMap <Enemigo, Inteligencia>(); juego.obtenerGrafica().setCongelarTiempo(true); synchronized(enemigos) { for(Enemigo e : enemigos) { backupInt.put(e, e.obtenerInteligencia()); e.establecerInteligencia(new Congelado(e)); e.setGrafico(1); } } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } enemigos = juego.obtenerEnemigos(); for(Enemigo e : enemigos) { e.establecerInteligencia(backupInt.get(e)); e.setGrafico(0); } juego.obtenerGrafica().setCongelarTiempo(false); } }
70533cd7ebfa81d9937fcecf1d5639fb853537d0
3aaf2576bf1af0964b845bf58bc866111d32efae
/QASandbox/src/test/java/ApiResponseCodeTest.java
0122b367ca5241acad64d69f3b195ba34c9c47ca
[]
no_license
jakovljevicM/QASandboxTest
9961742f6dcfea5d2fe298d2e8e970d9348814e7
a0f654f3568f17c18bb011eaad26b876e904db63
refs/heads/master
2021-07-13T18:00:11.050438
2020-03-17T20:43:45
2020-03-17T20:43:45
248,062,731
0
0
null
null
null
null
UTF-8
Java
false
false
2,281
java
package test.java; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Test; import org.junit.Assert; public class ApiResponseCodeTest { @Test public void getAllUseCases_whenAuthorizationIsNotSet_then401IsReceived() throws ClientProtocolException, IOException { System.out.println("TEST getAllUseCases_whenAuthorizationIsNotSet_then401IsReceived STARTED"); HttpUriRequest request = new HttpGet("https://qa-sandbox.apps.htec.rs/api/usecases/all"); HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); Assert.assertEquals("Response code is not as expected", HttpStatus.SC_UNAUTHORIZED, httpResponse.getStatusLine().getStatusCode()); System.out.println("TEST getAllUseCases_whenAuthorizationIsNotSet_then401IsReceived FINISHED"); } @Test public void getAllUseCases_whenAuthorizationIsSetWrong_then401IsReceived() throws ClientProtocolException, IOException { System.out.println("TEST getAllUseCases_whenAuthorizationIsSetWrong_then401IsReceived STARTED"); HttpUriRequest request = new HttpGet("https://qa-sandbox.apps.htec.rs/api/usecases/all"); request.addHeader("authorization", "Bearer3 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjQ3LCJmdWxsX25hbWUiOiJNaWxpamFuYSBKYWtvdmxqZXZpYyIsImFjdGl2YXRlZCI6dHJ1ZSwiYXZhdGFyIjoiaHR0cHM6Ly9xYS1zYW5kYm94LnMzLmFwcHMuaHRlYy5ycy9pbWFnZS1wcm9kLzE1ODQwOTgyNzQ0NDllN2JkN2Y5NGM4NmJkOTVhNjNhZDcyMTViOWQ1MmE0ODA5ZGQ0M2Q2IiwiY3JlYXRlZF9vbiI6IjIwMjAtMDMtMTNUMTE6MTM6MzUuNDY2WiIsInJvbGUiOiJVc2VyIiwic2NlbmFyaW9faWQiOjEwLCJvZmZpY2UiOjMsImJ1ZyI6IkkgQU0gQSBCVUchIFJFUE9SVCBNRSEiLCJpYXQiOjE1ODQyMTgyODQsImV4cCI6MTU4NDIyMTg4NH0.SGIFwIkedqibUbdsNe16hyPlE_br0wM6SIGnqgAPviQ"); HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); Assert.assertEquals("Response code is not as expected", HttpStatus.SC_UNAUTHORIZED, httpResponse.getStatusLine().getStatusCode()); System.out.println("TEST getAllUseCases_whenAuthorizationIsSetWrong_then401IsReceived FINISHED"); } }
48015c7f59e0bdb34b5c819904dcbb239dfdf332
8fc6fbc0bf858fcc815007a3aa42b8a189953b9f
/test/com/raphael/lc/p150/EvalRPNTest.java
67994ad33147f3a737cb286a2dd0667c0801dee0
[]
no_license
wangchao0502/lc-weekly-contest
79f01eadb118a92c79006285cb320b4bf316c1f9
0ebcd48e816d257ed454e489e9166fbd732ff528
refs/heads/main
2023-05-07T06:32:10.541215
2021-05-30T02:30:05
2021-05-30T02:30:05
327,791,058
0
0
null
null
null
null
UTF-8
Java
false
false
535
java
package com.raphael.lc.p150; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * @author Raphael * @date 2021-03-20 10:53:23 */ class EvalRPNTest { private final EvalRPN solution = new EvalRPN(); @Test void t1() { String[] tokens = {"2", "1", "+", "3", "*"}; Assertions.assertEquals(9, solution.evalRPN(tokens)); } @Test void t2() { String[] tokens = {"4", "13", "5", "/", "+"}; Assertions.assertEquals(6, solution.evalRPN(tokens)); } }
e2bba01850b4dfbaa9c3b08714cbb0292fe40783
6ae37c4936df55c3a9d7227a2e56e498e2a4e327
/project-2/src/test/java/project-2/AppTest.java
e8903e00fde5efa5000bf5707d2798a0039b7feb
[]
no_license
hemanthvaka/rep-02
e15df37e8bd9c175b1ee68a0fc722454ed4d3195
22596cf000f295378bc0aad4b340c860bb129397
refs/heads/master
2020-12-30T15:42:57.405967
2017-07-15T20:29:54
2017-07-15T20:29:54
91,173,449
0
0
null
null
null
null
UTF-8
Java
false
false
637
java
package project-2; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
3b6cf3917038ed841e6b76fc70ed8f08155f46da
eb91dd98c0fd306960614331a11381ad915b3d97
/app/src/main/java/com/lyc/idverification/demo/testActivity.java
884e08ef135bdc3cb452d927066fcd7e88654569
[]
no_license
huangjinping/idverification
969df7aeab6d3cd4102fe0b54eb5cdeecf4cab42
f0bbc029163a1fca8acd890a44264458b512556a
refs/heads/master
2020-03-28T22:11:34.067649
2018-09-14T01:48:38
2018-09-14T01:48:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,510
java
package com.lyc.idverification.demo; import android.Manifest; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.lyc.idverification.app.App; import com.lyc.idverification.camera.CameraActivity; import com.tbruyelle.rxpermissions2.Permission; import com.tbruyelle.rxpermissions2.RxPermissions; import static com.lyc.idverification.camera.CameraActivity.CAMERA_ACTIVITY_TYPE; import static com.lyc.idverification.camera.CameraActivity.RESULT_IMAGER; public class testActivity extends AppCompatActivity { Button mBtnOpen; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test_activity); mBtnOpen = findViewById(R.id.btn_open); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { RxPermissions rxPermission = new RxPermissions(testActivity.this); rxPermission.requestEach( Manifest.permission.WRITE_EXTERNAL_STORAGE,//SD卡写入 Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE//读外部存储的权限 ) .subscribe(new io.reactivex.functions.Consumer<Permission>() { @Override public void accept(Permission permission) throws Exception { if (permission.granted) { // 用户已经同意该权限 } else if (permission.shouldShowRequestPermissionRationale) { // 用户拒绝了该权限,没有选中『不再询问』(Never ask again),那么下次再次启动时,还会提示请求权限的对话框 Toast.makeText(testActivity.this, "您已关闭了SD卡写入以及读取权限,暂无法使用!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(testActivity.this, "您已关闭了SD卡写入以及读取权限,暂无法使用!", Toast.LENGTH_SHORT).show(); } } }); } mBtnOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String path = App.getInstance().getExternalCacheDir().getPath() + "/ID_CARD_POSITIVE.png"; //navToCamera 1、Context 2、图片返回的类型标志 3、图片拍照时候提示框 4、你要拍完图片放在哪里 CameraActivity.navToCamera(testActivity.this, 1, R.mipmap.camera_front, path); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } String imagePath = data.getStringExtra(RESULT_IMAGER); int imageType = data.getIntExtra(CAMERA_ACTIVITY_TYPE,0); if (!TextUtils.isEmpty(imagePath)){ Toast.makeText(testActivity.this,"图片地址:"+imagePath+" 返回图片类型:"+imageType,Toast.LENGTH_LONG).show(); } super.onActivityResult(requestCode, resultCode, data); } }
9bd0eddfa4583da42349e43b3a7a8e6a2dcf642d
598033dcbc6f397ee6503fd1658a1925796a0b44
/src/main/java/lv/tsi/javacourses/carshelf/cars/boundary/NewCarBean.java
06f8e2a735e2cc88dc26c7215724b9c7c97adf9b
[ "MIT" ]
permissive
ArtursVed/carshelf
115394b771cdb713ec1694e0d45686ec466206a8
e89175132a5d5411b356ba710df13b7f3e21b34b
refs/heads/master
2020-04-15T13:21:16.783218
2019-02-01T10:43:34
2019-02-01T10:43:34
164,713,312
0
0
null
null
null
null
UTF-8
Java
false
false
926
java
package lv.tsi.javacourses.carshelf.cars.boundary; import lv.tsi.javacourses.carshelf.cars.model.CarEntity; import javax.faces.view.ViewScoped; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.io.Serializable; @ViewScoped @Named public class NewCarBean implements Serializable { @PersistenceContext private EntityManager em; private CarEntity car = new CarEntity(); private boolean created = false; @Transactional public String createCar() { em.persist(car); car = new CarEntity(); created = true; // return "book-created.xhtml"; return null; } public boolean isCreated() { return created; } public CarEntity getCar() { return car; } public void setCar(CarEntity car) { this.car = car; } }
73b56b230d4493e8bdb75fa1ce2087c412cef3cd
7f8f6ff19264ea7ba91434cf0e6d230063f2c8ee
/app/src/main/java/com/example/tute4/MainActivity.java
79b652f03dde6c6d220af13d1f85d5728c656f96
[]
no_license
ShadiniKalansooriya/MAD_Tute4
c2917514bef68d1c864de39b7644d4656b6b0bfc
a6dca926ff1e0ca07ecc209219fc035ad0a4e4e5
refs/heads/master
2021-05-17T20:48:39.710153
2020-03-29T03:38:32
2020-03-29T03:38:32
250,945,815
0
0
null
null
null
null
UTF-8
Java
false
false
1,111
java
package com.example.tute4; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.tute4.Database.DBHelper; public class MainActivity extends AppCompatActivity { Button btnAdd, btnSignin, btnDelete, btnUpdate; EditText editTextName, editTextPW; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd= findViewById(R.id.buttonAdd); btnSignin = findViewById(R.id.buttonsignin); btnDelete = findViewById(R.id.buttonDelete); btnUpdate = findViewById(R.id.buttonUpdate); editTextName = findViewById(R.id.editTextName); editTextPW = findViewById(R.id.editTextPassword); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DBHelper db1 = new DBHelper(); db1.addInfo(); } }); } }