blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
73bb3bdccf7282c9ed27b88333fbc6bce10519a9
2bf26d40937b2e22a573fdf80bf02d1ed49472d7
/src/br/com/ecolivros/core/impl/negocio/ValidadorDadosObrigatoriosItemPedido.java
c7f5e800a92e31abbf5d0ac0c39173962d7fd1ca
[]
no_license
d3z40/EcoLivros
ea3d1abe17426d643091baacb23f09364bb3a409
b38f504a5265c27fd24d6ef021b1c16595138ebb
refs/heads/master
2020-06-18T11:50:24.110763
2019-07-11T01:14:47
2019-07-11T01:14:47
196,294,324
1
0
null
null
null
null
UTF-8
Java
false
false
1,208
java
package br.com.ecolivros.core.impl.negocio; import br.com.ecolivros.core.IStrategy; import br.com.ecolivros.dominio.EntidadeDominio; import br.com.ecolivros.dominio.ItemPedido; import br.com.ecolivros.enuns.SituacaoItem; public class ValidadorDadosObrigatoriosItemPedido implements IStrategy { @Override public String processar(EntidadeDominio entidade) { if(entidade instanceof ItemPedido){ ItemPedido itemPedido = (ItemPedido) entidade; StringBuilder msg = new StringBuilder(); int idEstoque = itemPedido.getIdEstoque(); int idLivro = itemPedido.getIdLivro(); int qtde = itemPedido.getQtde(); double valor = itemPedido.getValor(); SituacaoItem situacaoItem = itemPedido.getSituacaoItem(); if(idEstoque <= 0) msg.append("IdEstoque null, avise o desenvolvedor!\\n"); if(idLivro <= 0) msg.append("Livro é de preenchimento obrigatório!\n"); if(qtde <= 0 || valor <= 0) msg.append("Qtde e Valor são de preenchimento obrigatório!\\n"); if(situacaoItem == null) msg.append("Situação Item não preenchida, avise o analista de TI!!!\n"); return msg.toString(); } else { return "Deve ser registrado um Item!"; } } }
[ "andre.pereira22@fatec.sp.gov.br" ]
andre.pereira22@fatec.sp.gov.br
35f54d6f9efca5d66309cff000a46e3ff4808718
7bedac8178dda99e2d83915d3aa9ca66caba5658
/src/main/java/com/hackerrank/interview_preparation_kit/linked_lists/SinglyLinkedList.java
efe7254b6cd50ca7e9a1f3f3a76537dab493b48d
[]
no_license
haucongle/hackerrank
d0e738b9f8689736e5f89f35cf493045e729563a
d9fb80c619235641ff30fa7282c2d90b8e80e9e6
refs/heads/master
2020-03-27T07:52:58.331491
2018-11-30T14:55:10
2018-11-30T14:55:10
146,194,824
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package com.hackerrank.interview_preparation_kit.linked_lists; import java.util.ArrayList; import java.util.List; class SinglyLinkedList { SinglyLinkedListNode head; private SinglyLinkedListNode tail; SinglyLinkedList() { this.head = null; this.tail = null; } static void printSinglyLinkedList(SinglyLinkedListNode node) { List<String> l = new ArrayList<>(); while (node != null) { l.add(String.valueOf(node.data)); node = node.next; } System.out.println(String.join("->", l)); } void insertNode(int nodeData) { SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData); if (this.head == null) { this.head = node; } else { this.tail.next = node; } this.tail = node; } }
[ "leconghau.me@gmail.com" ]
leconghau.me@gmail.com
e2fa41711d2ed207a0dc69e9c02b033003e181cc
c4af35f6223d9a7921b485db3f9a5aecb8a57696
/src/it/tredi/auac/MotivoBloccoInvioReinvioDomandaEnum.java
cd464b3e863a3b26e7fb7335a2d921a93666489d
[]
no_license
aziendazero/area
7e84817310e1c40a4ce31e0211652d144280e383
35820721507b7c7616b602035c28059e50ca6692
refs/heads/master
2022-12-21T12:38:05.086250
2020-02-27T15:55:40
2020-02-27T15:55:40
235,974,895
0
1
null
2022-12-16T01:52:22
2020-01-24T09:37:52
Java
UTF-8
Java
false
false
1,013
java
package it.tredi.auac; public enum MotivoBloccoInvioReinvioDomandaEnum { NonApplicabile("motivoBloccoInvioReinvioDomandaEnum.nonApplicabile"), NessunaUdo("motivoBloccoInvioReinvioDomandaEnum.nessunaUdo"), RisposteRequisitiIncomplete("motivoBloccoInvioReinvioDomandaEnum.risposteRequisitiIncomplete"), MancanzaAllegati("motivoBloccoInvioReinvioDomandaEnum.mancanzaAllegati"), UdoSenzaPostiLettoInDomanda("motivoBloccoInvioReinvioDomandaEnum.udoSenzaPostiLettoInDomanda"), UdoTipoModuloSenzaPostiLettoInDomanda("motivoBloccoInvioReinvioDomandaEnum.udoTipoModuloSenzaPostiLettoInDomanda"), AltreDomandeNonConcluseConStesseUoUdo("motivoBloccoInvioReinvioDomandaEnum.altreDomandeNonConcluseConStesseUoUdo"), AltreDomandeNonConcluseConStesseUdo("motivoBloccoInvioReinvioDomandaEnum.altreDomandeNonConcluseConStesseUdo"); private String value; private MotivoBloccoInvioReinvioDomandaEnum(String value) { this.value = value; } public String getValue() { return value; } }
[ "mpascale@3di.it" ]
mpascale@3di.it
ebc89e4a871a79275c43f3f765faa2e6087094c7
6243e0ff082e0e17e0350477b4a991492bdbf02f
/rocket-common/src/main/java/cn/wilton/rocket/common/entity/enums/SexEnum.java
bafdb1363c989b675252ee857c513c648a803c65
[ "Apache-2.0" ]
permissive
Jackjet/Rocket-admin
6d6acd5a1d2256a29ee3adf13cbdd6a8426079ff
8464a3b9012a54a1fce438ee24f440cf53de484d
refs/heads/master
2023-03-31T12:30:24.579352
2021-03-15T10:06:44
2021-03-15T10:06:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,055
java
package cn.wilton.rocket.common.entity.enums; import com.baomidou.mybatisplus.annotation.EnumValue; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import lombok.Getter; import java.util.Objects; /** * <p>性别 * @author Ranger * @email wilton.icp@gmail.com * @since 2021/3/12 */ @Getter public enum SexEnum implements EnumMessage{ SEX_MALE (0L,"男"), SEX_FEMALE (1L,"女"), SEX_UNKNOW (1L,"保密"); /** * 标记数据库存的值是code */ @EnumValue private final Long code; @JsonValue private final String title; SexEnum (Long code,String title){ this.code = code; this.title = title; } @JsonCreator public static SexEnum getByCode(long code) { for (SexEnum value : SexEnum.values()) { if (Objects.equals(code, value.getCode())) { return value; } } return null; } @Override public String getDesc() { return null; } }
[ "wilton.icp@gmail.com" ]
wilton.icp@gmail.com
1911067137ec2e4e4efe9638ccab5193c1a638f9
1987f9ae5778bd3ae14c3209296e653b0ecbc0ed
/app/src/main/java/dev/quoccuong/barberbooking/Fragment/BookingStepFourFragment.java
49027a7c7cdfa0fc9f173ab789aea47ddd87490f
[]
no_license
CuongDuong2710/barber_booking_app
3d41cb7e8e00d07545e85defed8aeced58c79b39
8df67bfbe3eb67233a897acf2403629094bc9e4f
refs/heads/master
2020-05-19T01:47:25.630379
2019-06-11T14:55:16
2019-06-11T14:55:16
184,764,284
0
0
null
null
null
null
UTF-8
Java
false
false
16,058
java
package dev.quoccuong.barberbooking.Fragment; import android.Manifest; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.CalendarContract; import android.quoccuong.barberbooking.R; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.Timestamp; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import dev.quoccuong.barberbooking.Common.Common; import dev.quoccuong.barberbooking.Model.BookingInformation; import dmax.dialog.SpotsDialog; import io.paperdb.Paper; public class BookingStepFourFragment extends Fragment { static BookingStepFourFragment instance; SimpleDateFormat simpleDateFormat; LocalBroadcastManager localBroadcastManager; Unbinder unbinder; AlertDialog dialog; @BindView(R.id.txt_booking_barber_text) TextView txtBarberName; @BindView(R.id.txt_booking_time_text) TextView txtBookingTime; @BindView(R.id.txt_salon_address) TextView txtSalonAddress; @BindView(R.id.txt_salon_name) TextView txtSalonName; @BindView(R.id.txt_salon_open_hours) TextView txtSalonOpenHours; @BindView(R.id.txt_salon_phone) TextView txtSalonPhone; @BindView(R.id.txt_salon_website) TextView txtSalonWebsite; @BindView(R.id.btn_confirm) Button btnConfirm; // "9:00 - 9:30" int startHour; // 9 int startMin; // 00 int endHour; // 9 int endMin; // 30 @OnClick(R.id.btn_confirm) void confirmBooking() { dialog.show(); getStartEndOfHourAndMinute(); Calendar bookingDateWithOurHouse = Calendar.getInstance(); bookingDateWithOurHouse.setTimeInMillis(Common.bookingDate.getTimeInMillis()); bookingDateWithOurHouse.set(Calendar.HOUR_OF_DAY, startHour); bookingDateWithOurHouse.set(Calendar.MINUTE, startMin); // create Timestamp and apply to BookingInformation Timestamp timestamp = new Timestamp(bookingDateWithOurHouse.getTime()); final BookingInformation bookingInformation = new BookingInformation(); bookingInformation.setCity(Common.city); bookingInformation.setTimestamp(timestamp); bookingInformation.setDone(false); // always false, use to filter display on user bookingInformation.setBarberId(Common.currentBarber.getBarberID()); bookingInformation.setBarberName(Common.currentBarber.getName()); bookingInformation.setCustomerName(Common.currentUser.getName()); bookingInformation.setCustomerPhone(Common.currentUser.getPhoneNumber()); bookingInformation.setSalonId(Common.currentSalon.getSalonId()); bookingInformation.setSalonName(Common.currentSalon.getName()); bookingInformation.setSalonAddress(Common.currentSalon.getAddress()); bookingInformation.setTime(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot)) .append(" at ") .append(simpleDateFormat.format(bookingDateWithOurHouse.getTime())).toString()); bookingInformation.setSlot(Long.valueOf(Common.currentTimeSlot)); // submit to Barber document DocumentReference bookingDate = FirebaseFirestore.getInstance() .collection("AllSalon") .document(Common.city) .collection("Branch") .document(Common.currentSalon.getSalonId()) .collection("Barbers") .document(Common.currentBarber.getBarberID()) .collection(Common.simpleDateFormat.format(Common.bookingDate.getTime())) .document(String.valueOf(Common.currentTimeSlot)); // write data bookingDate.set(bookingInformation) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // here we can write an function to check // if already exist an booking, we will prevent new booking addToUserBooking(bookingInformation); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void getStartEndOfHourAndMinute() { // process Timestamp // we will use Timestamp to filter all booking with date is greater today // for only display all future booking String startTime = Common.convertTimeSlotToString(Common.currentTimeSlot); String[] convertTime = startTime.split("-"); // split ex: 9:00-9:30 String[] startTimeConvert = convertTime[0].split(":"); // 9:00 startHour = Integer.parseInt(startTimeConvert[0].trim()); // get '9' startMin = Integer.parseInt(startTimeConvert[1].trim()); // get '00' String[] endTimeConvert = convertTime[1].split(":"); // 9:30 endHour = Integer.parseInt(endTimeConvert[0].trim()); // 9 endMin = Integer.parseInt(endTimeConvert[1].trim()); // 30 } private void addToUserBooking(final BookingInformation bookingInformation) { // first, create new booking for user final CollectionReference userBooking = FirebaseFirestore.getInstance() .collection("User") .document(Common.currentUser.getPhoneNumber()) .collection("Booking"); // get current date Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 0); calendar.add(Calendar.HOUR_OF_DAY, 0); calendar.add(Calendar.MINUTE, 0); Timestamp toDayTimestamp = new Timestamp(calendar.getTime()); // check if exist document in this collection userBooking .whereGreaterThanOrEqualTo("timestamp", toDayTimestamp) .whereEqualTo("done", false) .limit(1) // only take 1 .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.getResult().isEmpty()) { // set data userBooking.document() .set(bookingInformation) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { addToCalenderOfDevice(Common.bookingDate, Common.convertTimeSlotToString(Common.currentTimeSlot)); dismissDialog(); resetDataAndFinish(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { dismissDialog(); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { dismissDialog(); resetDataAndFinish(); } } }); } private void addToCalenderOfDevice(Calendar bookingDate, String startTime) { Calendar startEvent = Calendar.getInstance(); startEvent.setTimeInMillis(bookingDate.getTimeInMillis()); startEvent.set(Calendar.HOUR_OF_DAY, startHour); startEvent.set(Calendar.MINUTE, startMin); Calendar endEvent = Calendar.getInstance(); endEvent.setTimeInMillis(bookingDate.getTimeInMillis()); endEvent.set(Calendar.HOUR_OF_DAY, endHour); endEvent.set(Calendar.MINUTE, endMin); // convert Calendar to String SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm"); String startEventTime = sdf.format(startEvent.getTime()); String endEventTime = sdf.format(endEvent.getTime()); addToDevice(startEventTime, endEventTime, "Haircut Booking", new StringBuilder("Hair cut from") .append(startTime) .append(" with ") .append(Common.currentBarber.getName()) .append(" at ") .append(Common.currentSalon.getName()).toString(), new StringBuilder("Address: ").append(Common.currentSalon.getAddress()).toString()); } private void addToDevice(String startEventTime, String endEventTime, String title, String description, String address) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm"); try { Date start = sdf.parse(startEventTime); Date end = sdf.parse(endEventTime); ContentValues event = new ContentValues(); // put event.put(CalendarContract.Events.CALENDAR_ID, getCalendar(getContext())); event.put(CalendarContract.Events.TITLE, title); event.put(CalendarContract.Events.DESCRIPTION, description); event.put(CalendarContract.Events.EVENT_LOCATION, address); // time event.put(CalendarContract.Events.DTSTART, start.getTime()); event.put(CalendarContract.Events.DTEND, end.getTime()); event.put(CalendarContract.Events.ALL_DAY, 0); event.put(CalendarContract.Events.HAS_ALARM, 1); String timeZone = TimeZone.getDefault().getID(); event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone); Log.d("CuongDNQ", "event: " + event.toString()); Uri uri_save = getActivity().getContentResolver().insert(getCalendarsUri(), event); // save to cache Paper.init(getActivity()); Paper.book().write(Common.EVENT_URI_CACHE, uri_save.toString()); Log.d("CuongDNQ", "Paper.book(): " + Paper.book().toString()); Log.d("CuongDNQ", "Paper.book().write: " + Paper.book().write(Common.EVENT_URI_CACHE, uri_save.toString())); } catch (ParseException e) { e.printStackTrace(); } } private String getCalendar(Context context) { Uri calendars; calendars = Uri.parse("content://com.android.calendar/calendars"); // get default calendar ID of Calendar Gmail String gmailIdCalendar = ""; String protection[] = {"_id", "calendar_displayName"}; ContentResolver contentResolver = context.getContentResolver(); // select all calendar Cursor cursor = contentResolver.query(calendars, protection, null, null, null); if (cursor.moveToFirst()) { String calName; int nameCol = cursor.getColumnIndex(protection[1]); int idCol = cursor.getColumnIndex(protection[0]); do { calName = cursor.getString(nameCol); if (calName.contains("@gmail.com")) { Log.d("CuongDNQ", "calName: " + calName); gmailIdCalendar = cursor.getString(idCol); break; } } while (cursor.moveToNext()); cursor.close(); } return gmailIdCalendar; } private Uri getCalendarsUri() { Uri calendarsUri; if (Build.VERSION.SDK_INT >= 8) calendarsUri = Uri.parse("content://com.android.calendar/events"); else calendarsUri = Uri.parse("content://calendar/events"); Log.d("CuongDNQ", "uri: " + calendarsUri); return calendarsUri; } private void resetDataAndFinish() { resetStaticData(); getActivity().finish(); Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show(); } private void dismissDialog() { if (dialog.isShowing()) dialog.dismiss(); } private void resetStaticData() { Common.step = 0; Common.currentTimeSlot = -1; Common.currentSalon = null; Common.currentBarber = null; Common.bookingDate.add(Calendar.DATE, 0); } public static BookingStepFourFragment getInstance() { if (instance == null) instance = new BookingStepFourFragment(); return instance; } BroadcastReceiver confirmBookingReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setData(); } }; private void setData() { txtBarberName.setText(Common.currentBarber.getName()); txtBookingTime.setText(new StringBuilder(Common.convertTimeSlotToString(Common.currentTimeSlot)) .append(" at ") .append(simpleDateFormat.format(Common.bookingDate.getTime()))); txtSalonAddress.setText(Common.currentSalon.getAddress()); txtSalonWebsite.setText(Common.currentSalon.getWebsite()); txtSalonName.setText(Common.currentSalon.getName()); txtSalonOpenHours.setText(Common.currentSalon.getOpenHours()); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // apply format for date display on Confirm simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); localBroadcastManager = LocalBroadcastManager.getInstance(getContext()); localBroadcastManager.registerReceiver(confirmBookingReceiver, new IntentFilter(Common.KEY_CONFIRM_BOOKING)); dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false).build(); } @Override public void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(confirmBookingReceiver); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View itemView = inflater.inflate(R.layout.fragment_booking_step_four, container, false); unbinder = ButterKnife.bind(this, itemView); return itemView; } }
[ "cuong.duong@titancorpvn.com" ]
cuong.duong@titancorpvn.com
50bf91c667aa05949af74499cce29872a27b3e38
707e080698798063f7073a89b1afd86bf54dd70e
/contrib/izpack/src/lib/com/izforge/izpack/panels/LicencePanel.java
994ab183ee4e488b63b5820a0dc369af1a7f789c
[ "Apache-2.0" ]
permissive
BackupTheBerlios/e-maku-svn
7ea4336a4840261689fa773483b200d634ec6842
f440f9fefc40c32222892054a5e90413e23bada1
refs/heads/master
2020-05-18T02:41:21.491192
2010-06-13T13:57:39
2010-06-13T13:57:39
40,668,812
0
0
null
null
null
null
UTF-8
Java
false
false
4,675
java
/* * IzPack - Copyright 2001-2006 Julien Ponge, All Rights Reserved. * * http://www.izforge.com/izpack/ * http://developer.berlios.de/projects/izpack/ * * Copyright 2002 Jan Blok * * 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.izforge.izpack.panels; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import com.izforge.izpack.gui.LabelFactory; import com.izforge.izpack.installer.InstallData; import com.izforge.izpack.installer.InstallerFrame; import com.izforge.izpack.installer.IzPanel; import com.izforge.izpack.installer.ResourceManager; /** * The license panel. * * @author Julien Ponge */ public class LicencePanel extends IzPanel implements ActionListener { /** * */ private static final long serialVersionUID = 3691043187997552948L; /** The license text. */ private String licence; /** The text area. */ private JTextArea textArea; /** The radio buttons. */ private JRadioButton yesRadio, noRadio; /** The scrolling container. */ private JScrollPane scroller; /** * The constructor. * * @param parent The parent window. * @param idata The installation data. */ public LicencePanel(InstallerFrame parent, InstallData idata) { super(parent, idata); // We initialize our layout setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // We load the licence loadLicence(); // We put our components JLabel infoLabel = LabelFactory.create(parent.langpack.getString("LicencePanel.info"), parent.icons.getImageIcon("history"), JLabel.TRAILING); add(infoLabel); add(Box.createRigidArea(new Dimension(0, 3))); textArea = new JTextArea(licence); textArea.setMargin(new Insets(2, 2, 2, 2)); textArea.setCaretPosition(0); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); scroller = new JScrollPane(textArea); scroller.setAlignmentX(LEFT_ALIGNMENT); add(scroller); ButtonGroup group = new ButtonGroup(); yesRadio = new JRadioButton(parent.langpack.getString("LicencePanel.agree"), false); group.add(yesRadio); add(yesRadio); yesRadio.addActionListener(this); noRadio = new JRadioButton(parent.langpack.getString("LicencePanel.notagree"), true); group.add(noRadio); add(noRadio); noRadio.addActionListener(this); } /** Loads the licence text. */ private void loadLicence() { try { // We read it String resNamePrifix = "LicencePanel.licence"; licence = ResourceManager.getInstance().getTextResource(resNamePrifix); } catch (Exception err) { licence = "Error : could not load the licence text !"; } } /** * Actions-handling method (here it allows the installation). * * @param e The event. */ public void actionPerformed(ActionEvent e) { if (yesRadio.isSelected()) parent.unlockNextButton(); else parent.lockNextButton(); } /** * Indicates wether the panel has been validated or not. * * @return true if the user has agreed. */ public boolean isValidated() { if (noRadio.isSelected()) { parent.exit(); return false; } else return (yesRadio.isSelected()); } /** Called when the panel becomes active. */ public void panelActivate() { if (!yesRadio.isSelected()) parent.lockNextButton(); } }
[ "xtingray@5c60d122-7a0f-0410-b01c-879a277d15ac" ]
xtingray@5c60d122-7a0f-0410-b01c-879a277d15ac
21859031f2f3564012fb9cd65009ac2f3f28025f
7a898aa01231e6205b1af1f692c2e785a7df630c
/src/main/java/com/jingbao/weixin/Utils/MD5Util.java
c14ef806fe958256c95cfd7b6f48b25d82c743b2
[]
no_license
HaiRonin/hospital-lianjiang
ffdef0d203478a60521737248b944ec23ff64ddf
768b541aa47ba29d94992f4974428fd61cdf2e8c
refs/heads/master
2023-03-07T01:26:09.579551
2021-02-14T03:22:17
2021-02-14T03:22:17
295,132,554
0
0
null
null
null
null
UTF-8
Java
false
false
1,122
java
package com.jingbao.weixin.Utils; import java.security.MessageDigest; public class MD5Util { private static String byteArrayToHexString(byte b[]) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) resultSb.append(byteToHexString(b[i])); return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n += 256; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } public static String MD5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) resultString = byteArrayToHexString(md.digest(resultString .getBytes())); else resultString = byteArrayToHexString(md.digest(resultString .getBytes(charsetname))); } catch (Exception exception) { } return resultString; } private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; }
[ "wdwlp999@163.com" ]
wdwlp999@163.com
3544c16af636c4ed7d0142b172da7ccecbc925be
46e4c6911a19858d337102b15e6c3bffdc2c2744
/src/main/java/com/ants/facade/user/service/impl/TMenuInfoFacadeImpl.java
9e1372b6ea341d85da638e67efeed532e2c00efe
[]
no_license
iearl/earl-service-user
4bb9643ece7ab257574440327c30a2277825970c
5232d9cb2801404926c50b83dcf5f053ff8dd74b
refs/heads/master
2020-03-12T01:27:48.414006
2018-05-22T15:54:50
2018-05-22T15:54:50
130,377,055
0
0
null
null
null
null
UTF-8
Java
false
false
1,314
java
package com.ants.facade.user.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ants.facade.user.entity.TMenuInfo; import com.ants.facade.user.service.TMenuInfoFacade; import com.ants.service.user.biz.TMenuInfoBiz; /** * @ClassName: TMenuInfoFacadeImpl * @Description: TODO(菜单对外提供的服务) * @author 马高伟 * @date 2018年4月10日 * */ @Service("tMenuInfoFacede") public class TMenuInfoFacadeImpl implements TMenuInfoFacade{ @Autowired private TMenuInfoBiz tMenuInfoBiz; @Override public List<TMenuInfo> selectListTMenuInfo() { List<TMenuInfo> list = tMenuInfoBiz.selectListTMenuInfo(); List<TMenuInfo> retVal = new ArrayList<>();//最终返回的数据 for(int i=0;i<list.size();i++){ TMenuInfo info = list.get(i); if("N".equals(info.getIsLeaf())){//不是叶子执行 List<TMenuInfo> subMenus = new ArrayList<>(); for(int j=0;j<list.size();j++){ TMenuInfo subInfo = list.get(j); if(info.getMenuId().equals(subInfo.getMotherId())){ subMenus.add(subInfo); } } info.setMenus(subMenus); retVal.add(info); } } return retVal; } }
[ "dc_magaowei@163.com" ]
dc_magaowei@163.com
9b93e24cec3d05eee16aafc0ef87176570a77b4f
53fdbef31efce91dcc33784f8ce287eea3c7a9c1
/app/src/main/java/com/example/clinicappproject/UpcomingSchedule.java
21212768ee2e163194543a0a8e8e533e698bc494
[]
no_license
garychen2002/ClinicAppProject
44c63be66d16ddafce4798362314d13bb3d17c52
f1bcd573871c830ca1b4798969bf8f0ca8b45b2d
refs/heads/master
2023-08-23T05:50:45.652202
2021-09-22T15:16:28
2021-09-22T15:16:28
389,779,885
0
2
null
null
null
null
UTF-8
Java
false
false
1,923
java
package com.example.clinicappproject; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.CalendarView; import java.util.ArrayList; public class UpcomingSchedule extends AppCompatActivity{ ArrayList<Appointment> appointments; Doctor currentDoctor; private CalendarView calendarView; public static final String EXTRA_MESSAGE = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upcoming_schedule); // Intent intent = getIntent(); currentDoctor = UserSingleton.getInstance().getCurrentDoctor(); calendarView = (CalendarView) findViewById(R.id.calendarView); // FirebaseAccess.getScheduleByDoctor(currentDoctor, this); calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) { String m; if (month < 9){ m = "0"+ String.valueOf(month+1); }else{ m = String.valueOf(month+1); } String d; if (dayOfMonth < 10){ d = "0"+ String.valueOf(dayOfMonth); }else{ d = String.valueOf(dayOfMonth); } String date = year + "/" + m + "/" + d; Intent intent1 = new Intent(UpcomingSchedule.this, ScheduleDisplay.class); intent1.putExtra(EXTRA_MESSAGE, date); // intent1.putExtra("com.example.clinicappproject.CurrentDoctor", currentDoctor); startActivity(intent1); } }); } }
[ "zhonghuis2020@gmail.com" ]
zhonghuis2020@gmail.com
c0c091f36723bc5e29975b77e77456c62fda35d7
0aaafb7e16fb0f06467622eff54f8bbeb65b1401
/src/main/java/com/centroclinico/demo/services/EnfermeroService.java
d50207cf56d49b55e5b8368f01f62498006d6532
[]
no_license
Jdmarinr/centroClinico
e71157ccec191567de0f0ea8d3bb1d38371c775a
1205809009affcebb426b02e4fbe5998e824a190
refs/heads/master
2023-05-08T02:28:56.696698
2021-06-03T17:02:27
2021-06-03T17:02:27
373,581,851
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package com.centroclinico.demo.services; import com.centroclinico.demo.Enfermero; import com.centroclinico.demo.Paciente; import java.util.List; public interface EnfermeroService { List<Enfermero> findAll(); Enfermero findById(Long id); Enfermero save(Paciente paciente); }
[ "juandamarinr@gmail.com" ]
juandamarinr@gmail.com
d038e8e1b82a447034a4d78192f4a8a7a1adcb63
dc9ce3f4e0b19b7889f8a473042b5f653b154c7e
/com.wsc20180906/src/com/wsc201809012/dog.java
00e9b42ec4df40cf577a13e52f36c336c417669d
[]
no_license
flywsc/20180906-
3cd09bbbef229f9806c6d4efbe0f2a457e151f29
958f852641b8944b8fec1da5f7b675b48508f14b
refs/heads/master
2020-03-28T03:12:15.784388
2018-09-17T12:30:52
2018-09-17T12:30:52
147,627,074
0
0
null
null
null
null
UTF-8
Java
false
false
519
java
package com.wsc201809012; public class dog extends pet{ public void play() { // TODO Auto-generated method stub this.love=50; System.out.println("去散散步"); } public void fly() { // TODO Auto-generated method stub System.out.println("狗狗与主人玩接飞盘游戏"); System.out.println("亲密度+5"); System.out.println("健康值-6"); } @Override public void eat() { // TODO Auto-generated method stub System.out.println("我在吃东西"); } }
[ "1638743013@qq.com" ]
1638743013@qq.com
d7b4c6d8dc464565c4f02e30ca83005049487e4c
698e2e259c13acf75c7c81809688c83b0f17a1ea
/src/main/java/com/tayyarah/common/util/APIProviderCommonConstant.java
b1998cfeef6066ee2bb7caa763e254b76f7ea8ba
[]
no_license
Ganeshmurthy1/TravelApiResource
50789e80ccaf23be924e6de45e2b2d380fe1e09e
83e4b1a79dba9607d768c56cb364cdace7e05bb6
refs/heads/master
2021-08-23T20:47:14.635194
2017-12-06T13:10:09
2017-12-06T13:10:09
113,316,827
0
0
null
null
null
null
UTF-8
Java
false
false
361
java
/** @Author yogeshsharma 20-Nov-2015 2015 ConstantsApiProvier.java */ /** * */ package com.tayyarah.common.util; public class APIProviderCommonConstant { public static final String BLUESTAR = "Bluestar"; public static final String TRAVELPORT = "Travelport"; public static final String NO_DATA = "NO DATA"; public static final String LINTAS_ID = "1"; }
[ "ganeshmurthy.p@gmail.com" ]
ganeshmurthy.p@gmail.com
bfcb3c738945ba488f7bec4c470be480a002acd4
6811fd178ae01659b5d207b59edbe32acfed45cc
/jira-project/jira-components/jira-plugins/jira-rest/jira-rest-plugin/src/main/java/com/atlassian/jira/rest/v2/avatar/TemporaryAvatarHelper.java
9f116e63172501df267eec82a371596ae5d4af75
[]
no_license
xiezhifeng/mysource
540b09a1e3c62614fca819610841ddb73b12326e
44f29e397a6a2da9340a79b8a3f61b3d51e331d1
refs/heads/master
2023-04-14T00:55:23.536578
2018-04-19T11:08:38
2018-04-19T11:08:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,630
java
package com.atlassian.jira.rest.v2.avatar; import java.io.IOException; import java.io.InputStream; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import com.atlassian.jira.avatar.Avatar; import com.atlassian.jira.avatar.AvatarImageDataProvider; import com.atlassian.jira.avatar.AvatarPickerHelperImpl; import com.atlassian.jira.avatar.TypeAvatarService; import com.atlassian.jira.avatar.CroppingAvatarImageDataProviderFactory; import com.atlassian.jira.avatar.Selection; import com.atlassian.jira.avatar.TemporaryAvatar; import com.atlassian.jira.avatar.UniversalAvatarsService; import com.atlassian.jira.avatar.TemporaryAvatars; import com.atlassian.jira.rest.api.util.ErrorCollection; import com.atlassian.jira.rest.util.AttachmentHelper; import com.atlassian.jira.rest.v2.issue.AvatarBean; import com.atlassian.jira.rest.v2.issue.AvatarBeanFactory; import com.atlassian.jira.rest.v2.issue.AvatarCroppingBean; import com.atlassian.jira.rest.v2.issue.RESTException; import com.atlassian.jira.user.ApplicationUser; import com.atlassian.jira.util.I18nHelper; import com.atlassian.jira.util.IOUtil; import com.atlassian.jira.util.SimpleErrorCollection; import com.atlassian.jira.util.velocity.VelocityRequestContextFactory; import com.atlassian.plugins.rest.common.multipart.FilePart; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import static com.atlassian.jira.rest.api.http.CacheControl.never; @Component public class TemporaryAvatarHelper { private final TemporaryAvatarUploader avatarUploader; private final AttachmentHelper attachmentHelper; private final I18nHelper i18nHelper; private final CroppingAvatarImageDataProviderFactory croppingAvatarImageDataProviderFactory; // can i remove this dep? private final VelocityRequestContextFactory requestContextFactory; private final UniversalAvatarsService avatars; private final TemporaryAvatars temporaryAvatars; @Inject // to many paramters... public TemporaryAvatarHelper( final TemporaryAvatarUploader avatarUploader, final AttachmentHelper attachmentHelper, final TemporaryAvatars temporaryAvatars, final VelocityRequestContextFactory requestContextFactory, final UniversalAvatarsService avatars, final CroppingAvatarImageDataProviderFactory croppingAvatarImageDataProviderFactory, final I18nHelper i18nHelper) { this.avatarUploader = avatarUploader; this.attachmentHelper = attachmentHelper; this.temporaryAvatars = temporaryAvatars; this.requestContextFactory = requestContextFactory; this.avatars = avatars; this.croppingAvatarImageDataProviderFactory = croppingAvatarImageDataProviderFactory; this.i18nHelper = i18nHelper; } public Response storeTemporaryAvatar(final ApplicationUser remoteUser, final Avatar.Type type, final String ownerId, Avatar.Size targetSize, final String filename, final Long size, final HttpServletRequest request) { AttachmentHelper.ValidationResult validationResult = attachmentHelper.validate(request, filename, size); if (!validationResult.isValid()) { throwWebException(validationResult.getErrorMessage(), com.atlassian.jira.util.ErrorCollection.Reason.VALIDATION_FAILED); } try { UploadedAvatar uploadedAvatar = avatarUploader.createUploadedAvatarFromStream( validationResult.getInputStream(), filename, validationResult.getContentType(), validationResult.getSize()); final TemporaryAvatar temporaryAvatar = new TemporaryAvatar( validationResult.getContentType(), uploadedAvatar.getContentType(), filename, uploadedAvatar.getImageFile(), null); temporaryAvatars.storeTemporaryAvatar(remoteUser, temporaryAvatar, type, ownerId); final AvatarPickerHelperImpl.TemporaryAvatarBean temporaryAvatarBean = new AvatarPickerHelperImpl.TemporaryAvatarBean( getTemporaryAvatarUrl(), uploadedAvatar.getWidth(), uploadedAvatar.getHeight(), isCroppingNeeded(uploadedAvatar, targetSize)); final AvatarCroppingBean croppingInstructions = AvatarBeanFactory.createTemporaryAvatarCroppingInstructions(temporaryAvatarBean); if (temporaryAvatarBean.isCroppingNeeded()) { return Response.status(Response.Status.CREATED) .entity(croppingInstructions) .cacheControl(never()).build(); } else { final AvatarBean avatarBean = createAvatarFromTemporary(remoteUser, type, ownerId, croppingInstructions); return Response.status(Response.Status.CREATED).entity(avatarBean).cacheControl(never()).build(); } } catch (ValidationException e) { throwWebException(e.getMessage(), com.atlassian.jira.util.ErrorCollection.Reason.VALIDATION_FAILED); } catch (IOException e) { throwWebException(e.getMessage(), com.atlassian.jira.util.ErrorCollection.Reason.SERVER_ERROR); } catch (IllegalAccessException e) { throwWebException(null, com.atlassian.jira.util.ErrorCollection.Reason.FORBIDDEN); } throw new AssertionError("unreachable!"); } public Response storeTemporaryAvatar(final ApplicationUser remoteUser, final Avatar.Type type, final String ownerId, final Avatar.Size targetSize, final FilePart filePart, final HttpServletRequest request) { final String fullPath = filePart.getName(); final String filename = fullPath.substring(fullPath.lastIndexOf("\\") + 1, fullPath.length()); AttachmentHelper.ValidationResult validationResult = attachmentHelper.validate(request, filename, null); if (!validationResult.isValid()) { throwWebException(validationResult.getErrorMessage(), com.atlassian.jira.util.ErrorCollection.Reason.VALIDATION_FAILED); } try { UploadedAvatar uploadedAvatar = avatarUploader.createUploadedAvatarFromStream( filePart.getInputStream(), filename, filePart.getContentType()); final TemporaryAvatar temporaryAvatar = new TemporaryAvatar( validationResult.getContentType(), uploadedAvatar.getContentType(), filename, uploadedAvatar.getImageFile(), null); temporaryAvatars.storeTemporaryAvatar(remoteUser, temporaryAvatar, type, ownerId); final AvatarPickerHelperImpl.TemporaryAvatarBean temporaryAvatarBean = new AvatarPickerHelperImpl.TemporaryAvatarBean( getTemporaryAvatarUrl(), uploadedAvatar.getWidth(), uploadedAvatar.getHeight(), isCroppingNeeded(uploadedAvatar, targetSize)); final AvatarCroppingBean croppingInstructions = AvatarBeanFactory.createTemporaryAvatarCroppingInstructions(temporaryAvatarBean); if (temporaryAvatarBean.isCroppingNeeded()) { return Response.status(Response.Status.CREATED) .entity("<html><body>" + "<textarea>" + "{" + "\"url\": \"" + temporaryAvatarBean.getUrl() + "\"," + "\"cropperWidth\": \"" + temporaryAvatarBean.getCropperWidth() + "\"," + "\"cropperOffsetX\": \"" + temporaryAvatarBean.getCropperOffsetX() + "\"," + "\"cropperOffsetY\": \"" + temporaryAvatarBean.getCropperOffsetY() + "\"," + "\"isCroppingNeeded\": \"" + temporaryAvatarBean.isCroppingNeeded() + "\"" + "}" + "</textarea>" + "</body></html>") .cacheControl(never()).build(); } else { final AvatarBean avatarBean = createAvatarFromTemporary(remoteUser, type, ownerId, croppingInstructions); return Response.status(Response.Status.CREATED) .entity("<html><body>" + "<textarea>" + "{" + "\"id\": \"" + avatarBean.getId() + "\"" + "}" + "</textarea>" + "</body></html>") .cacheControl(never()).build(); } } catch (ValidationException e) { throwWebException(e.getMessage(), com.atlassian.jira.util.ErrorCollection.Reason.VALIDATION_FAILED); } catch (IOException e) { throwWebException(e.getMessage(), com.atlassian.jira.util.ErrorCollection.Reason.SERVER_ERROR); } catch (IllegalAccessException e) { throwWebException(null, com.atlassian.jira.util.ErrorCollection.Reason.FORBIDDEN); } throw new AssertionError("unreachable!"); } public AvatarBean createAvatarFromTemporary(final ApplicationUser remoteUser, final Avatar.Type type, final String ownerId, final AvatarCroppingBean croppingInstructions) { Selection selection = new Selection(croppingInstructions.getCropperOffsetX(), croppingInstructions.getCropperOffsetY(), croppingInstructions.getCropperWidth(), croppingInstructions.getCropperWidth()); Avatar conversionResult = convertTemporaryToReal(remoteUser, ownerId, type, selection); final AvatarBean avatarBean = AvatarBeanFactory.createAvatarBean(conversionResult); return avatarBean; } private boolean isCroppingNeeded(final UploadedAvatar image, final Avatar.Size targetSize) { final boolean isSquare = image.getHeight() == image.getWidth(); final boolean widthWithinBounds = image.getWidth() <= targetSize.getPixels(); return !widthWithinBounds || !isSquare; } public String getTemporaryAvatarUrl() { // if the user chooses a new temporary avatar we need to keep making this url unique so that the javascript that // ajaxly retrieves this url always gets a unique one, forcing the browser to keep the image fresh return getBaseUrl() + "/secure/temporaryavatar?cropped=true&magic=" + System.currentTimeMillis(); } private String getBaseUrl() { return requestContextFactory.getJiraVelocityRequestContext().getBaseUrl(); } public Avatar convertTemporaryToReal(final ApplicationUser remoteUser, String ownerId, Avatar.Type type, Selection selection) { TemporaryAvatar temporaryAvatar = temporaryAvatars.getCurrentTemporaryAvatar(); if (temporaryAvatar == null) { throwWebException(i18nHelper.getText("avatarpicker.upload.failure"), com.atlassian.jira.util.ErrorCollection.Reason.SERVER_ERROR); } try { final InputStream imageDataStream = temporaryAvatar.getImageData(); try { final AvatarImageDataProvider imageDataProvider = croppingAvatarImageDataProviderFactory.createStreamsFrom(imageDataStream, selection); final TypeAvatarService typeAvatars = avatars.getAvatars(type); if (typeAvatars == null) { throwWebException(i18nHelper.getText("rest.error.invalid.avatar.type", type.getName()), com.atlassian.jira.util.ErrorCollection.Reason.VALIDATION_FAILED); } Avatar newAvatar = typeAvatars.createAvatar(remoteUser, ownerId, imageDataProvider); temporaryAvatars.dispose(temporaryAvatar); return newAvatar; } finally { IOUtils.closeQuietly(imageDataStream); } } catch (IOException e) { throwWebException(i18nHelper.getText("avatarpicker.upload.temp.io", e.getMessage()), com.atlassian.jira.util.ErrorCollection.Reason.SERVER_ERROR); } catch (IllegalAccessException e) { throwWebException(i18nHelper.getText("avatarpicker.upload.temp.io", e.getMessage()), com.atlassian.jira.util.ErrorCollection.Reason.FORBIDDEN); } throw new AssertionError("ureachable"); } private void throwWebException(String message, com.atlassian.jira.util.ErrorCollection.Reason reason) { com.atlassian.jira.util.ErrorCollection errorCollection = new SimpleErrorCollection(); errorCollection.addErrorMessage(message, reason); throwWebException(errorCollection); } private void throwWebException(com.atlassian.jira.util.ErrorCollection errorCollection) { throw new RESTException(ErrorCollection.of(errorCollection)); } }
[ "moink635@gmail.com" ]
moink635@gmail.com
e0ed013149e19db4f7e070db30b1f465a2e5e5b3
b272295f356dd55e577d632f19f113ecc2f86eac
/Labos/LouisLabos/Labo6/src/domain/GeheimshriftEnum.java
1801eb8e1d44c3c4a70e2e7293e31c8285403c33
[]
no_license
Ofrenay/OOO
eb9a9eee127b7859eed4b31414af0f66c990865b
c3e60333eb520fabf5ecdd3f57b9949178f6caba
refs/heads/master
2020-11-24T02:46:56.583933
2020-01-09T20:56:06
2020-01-09T20:56:06
227,931,764
0
0
null
null
null
null
UTF-8
Java
false
false
547
java
package domain; public enum GeheimshriftEnum { CAESAR("Caesar", "domain.GeheimschriftCaesar"), RANDOM("Random", "domain.GeheimschriftRandomKarakter"), SPIEGEL("Spiegel", "domain.GeheimschriftCaesar"); private final String name; private final String klasse; private GeheimshriftEnum(String name, String klasse){ this.name = name; this.klasse = klasse; } public String getName() { return name; } public String getKlasse() { return klasse; } }
[ "oscarfrenay@gmail.com" ]
oscarfrenay@gmail.com
62ad56d0146129749f55053e64b9f058b08566eb
a4b91a51536de763b969352630774b357957f6f4
/persistence-microservice/src/main/java/io/newage/persistence/config/LocaleConfiguration.java
696c38d1a9782d00b208c180f86994d2b29c50bc
[]
no_license
SalivonIvan/distributed-signup
c40751143f776380304a04e341e6a66e919d77c0
3d06c307543a0d214796bafbe1c40140e809696f
refs/heads/master
2021-06-18T22:52:00.149422
2019-08-08T10:54:59
2019-08-08T10:54:59
200,535,594
0
0
null
2021-04-29T21:52:54
2019-08-04T19:55:35
Java
UTF-8
Java
false
false
1,064
java
package io.newage.persistence.config; import io.github.jhipster.config.locale.AngularCookieLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocaleConfiguration implements WebMvcConfigurer { @Bean(name = "localeResolver") public LocaleResolver localeResolver() { AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY"); return cookieLocaleResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); registry.addInterceptor(localeChangeInterceptor); } }
[ "ivan.salyvon@kyivstar.net" ]
ivan.salyvon@kyivstar.net
4803cc9200ddcb399887a3fe2433bfda72bb5904
1db345e7d559fae1e956af44778a1f5f26d3fb5c
/GreenApp/src/com/tutorialsface/audioplayer/StoveActivity.java
a644e2e9e6954de17f2d48afc207aa44b114e3c0
[]
no_license
welcomeking/GreenApp
c56f510a2c5287d95b1cab8d31d0e26512984d32
ca4e312f5d1f054ffcc36762bf7c9f651000c539
refs/heads/master
2020-12-19T06:11:43.249158
2016-06-06T19:10:23
2016-06-06T19:10:23
60,553,991
0
0
null
null
null
null
UTF-8
Java
false
false
3,302
java
package com.tutorialsface.audioplayer; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckedTextView; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.NumberPicker; import android.widget.Toast; public class StoveActivity extends ListActivity { String[] city= { "Electric stove", "Gas stove", "Hot plate", "Kitchen stove " }; NumberPicker picker; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stove); getActionBar().hide(); Button button = (Button)findViewById(R.id.save131); button.setOnClickListener(new OnClickListener() { @SuppressLint("NewApi") @Override public void onClick(View v) { Intent i = new Intent(StoveActivity.this, MainActivity.class); //i.putExtra("name", ); startActivity(i); } }); // -- Display mode of the ListView ListView listview= getListView(); // listview.setChoiceMode(listview.CHOICE_MODE_NONE); // listview.setChoiceMode(listview.CHOICE_MODE_SINGLE); listview.setChoiceMode(listview.CHOICE_MODE_MULTIPLE); //-- text filtering listview.setTextFilterEnabled(true); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked,city)); } public void onListItemClick(ListView parent, View v,int position,long id){ CheckedTextView item = (CheckedTextView) v; Toast.makeText(this, city[position] + " checked : " + item.isChecked(), Toast.LENGTH_SHORT).show(); onClick2(v); } @SuppressLint("NewApi") public void onClick2(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(StoveActivity.this); builder.setCancelable(false); picker = new NumberPicker(StoveActivity.this); picker.setMinValue(0); picker.setMaxValue(10); final FrameLayout parent = new FrameLayout(StoveActivity.this); parent.addView(picker, new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); builder.setView(parent); builder.setIcon(R.drawable.ic_launcher) .setTitle("How many curently switched on") //.setMessage("How many curently switched on") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @SuppressLint("NewApi") @Override public void onClick(DialogInterface dialog, int which) { int number= picker.getValue(); Toast.makeText(StoveActivity.this, "You have "+number, Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(StoveActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show(); } }).show(); } }
[ "welcomeking@outlook.com" ]
welcomeking@outlook.com
8a47cb44ac10f9ef776104fb03d43fded7b731e0
52687cb447d4bda3f63a03fb1c9f45419a7cd3ba
/gym/src/com/vooda/weixin/mp/util/json/WxMpMassVideoAdapter.java
001f071486374ff32edfc4a2fa9fd3d59e1993d1
[]
no_license
simplezpw/gym
f9301b674a6b80e9ad48e5a75d4ce4d0c28ed083
1307dfb5e2e6c1877eeeac8e8eead33643308683
refs/heads/master
2021-04-09T15:15:31.501135
2018-03-16T12:03:11
2018-03-16T12:03:11
125,509,724
0
0
null
null
null
null
UTF-8
Java
false
false
1,167
java
/* * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended only for the use of KINGSTAR MEDIA application * development. Reengineering, reproduction arose from modification of the original source, or other redistribution of this source is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. */ package com.vooda.weixin.mp.util.json; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.vooda.weixin.mp.bean.WxMpMassVideo; import java.lang.reflect.Type; /** * @author */ public class WxMpMassVideoAdapter implements JsonSerializer<WxMpMassVideo> { public JsonElement serialize(WxMpMassVideo message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("media_id", message.getMediaId()); messageJson.addProperty("description", message.getDescription()); messageJson.addProperty("title", message.getTitle()); return messageJson; } }
[ "simplezpw@163.com" ]
simplezpw@163.com
45cb9d612681cf78f0de65ee0edede612c24d7bd
dadef47462f954f985cffb33add99bdadd6197ef
/src/java/Controller/Logout.java
643273067af8c018084b8000bf59e4448b351fbf
[]
no_license
pedromaxado/Frequency-Controller
d3e4f65af5df4eae5e30a7e13ec4d0027e8e0450
accf1ebed7018a66385243b7773f62f8a3fc03e2
refs/heads/master
2021-01-24T06:34:14.136795
2015-04-08T23:53:04
2015-04-08T23:53:04
32,998,893
1
0
null
null
null
null
UTF-8
Java
false
false
1,076
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 Controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author pedro */ @WebServlet("/Logout") public class Logout extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if(session != null && session.getAttribute("currentUser") != null) { session.setAttribute("currentUser", null); session.invalidate(); } response.sendRedirect(request.getServletContext().getContextPath()); } }
[ "p.o.maxado@gmail.com" ]
p.o.maxado@gmail.com
eac731e0a69aa7d63c90c70f271aecbb620ccbbc
0699cf480971e96f9fdbcdfcab16ac5c51c41001
/src/test/java/com/demo/springselenium/googleTests/GoogleTest1.java
980b14cd112fe84f7a887bff94389baa17b6b77d
[]
no_license
sunnysachdeva99/selenium-spring-framework
a4a4eee85be7053be7dbb61fe35ce3b283f92288
128d3528b8235318c9915ff103927ff5c2ac82d2
refs/heads/master
2023-05-13T15:36:41.484929
2020-07-07T09:46:19
2020-07-07T09:46:19
277,777,415
0
0
null
2023-05-09T18:26:24
2020-07-07T09:44:21
HTML
UTF-8
Java
false
false
1,065
java
package com.demo.springselenium.googleTests; import java.io.IOException; import com.demo.springselenium.SpringBaseTestNGTest; import com.demo.springselenium.annotations.LazyAutowired; import com.demo.springselenium.page.google.GooglePage; import com.demo.springselenium.util.ScreenShotUtil; import org.testng.Assert; import org.testng.annotations.Test; public class GoogleTest1 extends SpringBaseTestNGTest { @LazyAutowired private GooglePage googlePage; @LazyAutowired private ScreenShotUtil screenShotUtil; @Test public void TC_001() throws IOException, InterruptedException { this.googlePage.goTo(); Assert.assertTrue(this.googlePage.isAt()); this.googlePage.getSearchComponent().searchFor("spring boot"); Assert.assertTrue(this.googlePage.getSearchResult().isAt()); Assert.assertTrue(this.googlePage.getSearchResult().getCount() > 2); this.screenShotUtil.takeScreenShot(Thread.currentThread() + "_GoogleTest1.png"); Thread.sleep(5000); this.googlePage.close(); } }
[ "sunny.sachdeva@sephora.com" ]
sunny.sachdeva@sephora.com
ec3a378866549129d906f6d6d766b14939cbf373
2793f868539bc5cbdb41f4bc98d4928d4d0b9694
/design-pattern-examples/create/02-factory/src/com/july/factory/BenZFactory.java
87ffee0cbeaafceb898284810b98d6a872ce618f
[]
no_license
houever/examples
0576ad9346b8a631042701ce712df692451c20a6
b505c0a651e76bf53ba5f1a92a80077299415bf7
refs/heads/master
2022-10-16T07:05:28.849908
2019-12-21T06:27:24
2019-12-21T06:27:24
153,788,632
0
0
null
2022-10-04T23:48:53
2018-10-19T13:40:11
JavaScript
UTF-8
Java
false
false
179
java
package com.july.factory; public class BenZFactory implements ICarFactory { @Override public void createCar() { System.out.println("生产奔驰汽车"); } }
[ "349514537@qq.com" ]
349514537@qq.com
4fa11c2c2a10c7b7a94063e0de8e7e557c463319
09af43e311f8e045a2f052a8a835613465e8ee69
/app/src/main/java/ir/jahanmir/araxx/gson/GetUpdateResponse.java
9e087ca0682f02f35760ad67af22bff18e2543a8
[]
no_license
bnjmr/aspall
b8a42c00c8230821ad78c316c36460157cbe22f0
f2ffbb03d2b49ca0292c063dad98256bf89c4923
refs/heads/master
2021-08-19T08:33:05.040704
2017-11-25T14:12:07
2017-11-25T14:12:07
111,995,935
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package ir.jahanmir.araxx.gson; /** * Created by Microsoft on 3/15/2016. */ public class GetUpdateResponse { public String Ver = ""; public String Url = ""; public boolean Force; }
[ "jahanmir.co@gmail.com" ]
jahanmir.co@gmail.com
f9bba2b3e272528bf7f92e8a6b3e7528bb5fdb72
86378600a51012c83906719324ea4117c8353e43
/Week_08/src/main/java/com/hlk/homework/weeks08/testxa/TransactionConfiguration.java
0b27c2f1f93dc88a3139bf79cde19f2dbfa75295
[]
no_license
Huanglk8888/JAVA-000
167195e3db4124a6e5934074ccc49399910dc299
682b2f4b5c09b22ac98bef0f667e2f23cb877d80
refs/heads/main
2023-02-28T05:46:09.017434
2021-02-06T09:50:10
2021-02-06T09:50:10
303,018,989
0
0
null
2020-10-11T01:18:06
2020-10-11T01:18:05
null
UTF-8
Java
false
false
1,557
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 com.hlk.homework.weeks08.testxa; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; @Configuration @EnableTransactionManagement public class TransactionConfiguration { @Bean public PlatformTransactionManager txManager(@Qualifier("shardingDataSource") DataSource shardingDataSource) { return new DataSourceTransactionManager(shardingDataSource); } }
[ "463927289@qq.com" ]
463927289@qq.com
f9b2c40edce58388838e2c82835b2c1c1d0f016e
1e816bd17c18a3553180b43a1a9fee61856eac59
/app/src/main/java/utils/FastBlurUtil.java
53925c3d0f67c34e569e2dea7a79e12632441805
[ "Apache-2.0" ]
permissive
DseSen/MyRepo
cb151b452819ab657cb411c41cf6153fc1504c3e
101a71580f62662c52fd5dfd4b0f77e4265916ce
refs/heads/master
2021-01-23T10:28:58.311831
2018-10-10T08:45:07
2018-10-10T08:45:07
93,062,266
0
0
null
null
null
null
UTF-8
Java
false
false
7,325
java
package utils; import android.graphics.Bitmap; /** * Created by jay on 11/7/15. */ public class FastBlurUtil { public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) { // Stack Blur v1.0 from // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html // // Java Author: Mario Klingemann <mario at quasimondo.com> // http://incubator.quasimondo.com // created Feburary 29, 2004 // Android port : Yahel Bouaziz <yahel at kayenko.com> // http://www.kayenko.com // ported april 5th, 2012 // This is a compromise between Gaussian Blur and Box blur // It creates much better looking blurs than Box Blur, but is // 7x faster than my Gaussian Blur implementation. // // I called it Stack Blur because this describes best how this // filter works internally: it creates a kind of moving stack // of colors whilst scanning through the image. Thereby it // just has to add one new block of color to the right side // of the stack and remove the leftmost color. The remaining // colors on the topmost layer of the stack are either added on // or reduced by one, depending on if they are on the right or // on the left side of the stack. // // If you are using this algorithm in your code please add // the following line: // // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com> Bitmap bitmap; if (canReuseInBitmap) { bitmap = sentBitmap; } else { bitmap = sentBitmap.copy(sentBitmap.getConfig(), true); } if (radius < 1) { return (null); } int w = bitmap.getWidth(); int h = bitmap.getHeight(); int[] pix = new int[w * h]; bitmap.getPixels(pix, 0, w, 0, 0, w, h); int wm = w - 1; int hm = h - 1; int wh = w * h; int div = radius + radius + 1; int r[] = new int[wh]; int g[] = new int[wh]; int b[] = new int[wh]; int rsum, gsum, bsum, x, y, i, p, yp, yi, yw; int vmin[] = new int[Math.max(w, h)]; int divsum = (div + 1) >> 1; divsum *= divsum; int dv[] = new int[256 * divsum]; for (i = 0; i < 256 * divsum; i++) { dv[i] = (i / divsum); } yw = yi = 0; int[][] stack = new int[div][3]; int stackpointer; int stackstart; int[] sir; int rbs; int r1 = radius + 1; int routsum, goutsum, boutsum; int rinsum, ginsum, binsum; for (y = 0; y < h; y++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; for (i = -radius; i <= radius; i++) { p = pix[yi + Math.min(wm, Math.max(i, 0))]; sir = stack[i + radius]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rbs = r1 - Math.abs(i); rsum += sir[0] * rbs; gsum += sir[1] * rbs; bsum += sir[2] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } } stackpointer = radius; for (x = 0; x < w; x++) { r[yi] = dv[rsum]; g[yi] = dv[gsum]; b[yi] = dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (y == 0) { vmin[x] = Math.min(x + radius + 1, wm); } p = pix[yw + vmin[x]]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[(stackpointer) % div]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi++; } yw += w; } for (x = 0; x < w; x++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; yp = -radius * w; for (i = -radius; i <= radius; i++) { yi = Math.max(0, yp) + x; sir = stack[i + radius]; sir[0] = r[yi]; sir[1] = g[yi]; sir[2] = b[yi]; rbs = r1 - Math.abs(i); rsum += r[yi] * rbs; gsum += g[yi] * rbs; bsum += b[yi] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } if (i < hm) { yp += w; } } yi = x; stackpointer = radius; for (y = 0; y < h; y++) { // Preserve alpha channel: ( 0xff000000 & pix[yi] ) pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w; } p = x + vmin[y]; sir[0] = r[p]; sir[1] = g[p]; sir[2] = b[p]; rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[stackpointer]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi += w; } } bitmap.setPixels(pix, 0, w, 0, 0, w, h); return (bitmap); } }
[ "dse498520140@126.com" ]
dse498520140@126.com
22927b89843f1329d3059a48dbabde4e173a7ea2
f87a58ca667e90c16fa0e6007b0b51f5bd09f0e9
/src/main/java/com/market/secondshoes/domain/item/Gender.java
7cbbf1557fc1c8e36463db69dc04a1113305078a
[]
no_license
GwanUk/secondshoes
cc7c22422d809cc4e3db582e43f607cb4a08d82c
34473868e8bee3b6cc674bdeeac6de3fca964716
refs/heads/master
2023-08-20T22:14:16.514817
2021-10-04T14:56:39
2021-10-04T14:56:39
386,248,138
0
0
null
null
null
null
UTF-8
Java
false
false
277
java
package com.market.secondshoes.domain.item; import com.fasterxml.jackson.annotation.JsonCreator; import lombok.Getter; @Getter public enum Gender { MALE("남성"), FEMALE("여성"); private final String sex; Gender(String sex) { this.sex = sex; } }
[ "guk1502012@gmail.com" ]
guk1502012@gmail.com
8a45c496e2bccc5ac5d28a22690fad4f71b37b0e
9365e7eae60753821c128cf05b709c502b5c2ef4
/WifiDemoSonny/app/src/main/java/com/wifidemoSonny/bean/WifiListBean.java
a4557e12ccefb8ab37a7adbc37281b2d71274d87
[ "MIT" ]
permissive
sonny-sworld/wifi_manager
ae203c3bdb637d79583c08542ad85411d34cb068
5e5d6447a0061b717f7ca2fdf8230518a596c3f4
refs/heads/master
2023-09-04T06:34:40.588666
2021-11-01T02:13:50
2021-11-01T02:13:50
291,882,415
0
0
null
null
null
null
UTF-8
Java
false
false
397
java
package com.wifidemoSonny.bean; public class WifiListBean { private String name; private String encrypt; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEncrypt() { return encrypt; } public void setEncrypt(String encrypt) { this.encrypt = encrypt; } }
[ "sgao@adriley.co.nz" ]
sgao@adriley.co.nz
4e63a915b524bfdb624aa6aad6447be3844b32ef
62ece273f8d5270fc6dcdc83d145becc7d38b787
/src/com/ghd/java/TemplatesTest.java
5cea2896be7f2c37f795cebfd5e589a303551462
[]
no_license
gaohaodongaijava/project01
38be270b4d4e236e69e45fafd88995bb22166a39
466f3476bca221af7b349c2f2ece422c716b7e2a
refs/heads/master
2020-03-31T11:03:04.941075
2018-10-08T23:48:38
2018-10-08T23:48:38
152,160,956
0
0
null
null
null
null
UTF-8
Java
false
false
973
java
package com.ghd.java; import java.util.ArrayList; /** * @author ghd * @date 2018/10/8 - 20:50 */ public class TemplatesTest { //模板六:prsf可以生成 private static final private static final ArrayList CUSTOMER = new ArrayList(); //模板一:psvm public static void main(String[] args) { //模板二:sout System.out.println("hello!"); //sout变形:soutp / soutv / xxx.sout System.out.println("args = [" + args + "]"); System.out.println("TemplatesTest.main"); int num = 1; System.out.println(num); System.out.println("num = " + num); //模板三:fori String [] arr = new String[]{"Tom","jj","lsss"}; for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } //变形:iter for (String s : arr) { System.out.println(s); } } }
[ "2633576815@qq.com" ]
2633576815@qq.com
986a77cd7c636455028f88c29abc399eea5d8308
505de4000794b31e6e577141377ecb7589a332d6
/Interface/src/PUBGplayer.java
0f4b89537a9ee3100ff1af4090a537b0ebea8fd3
[]
no_license
nandhak9077/BusinessLogicJava
957592dc1d47bb8a3e3c6d1598c33795dba8ff83
6ce5ff9dfbe0dbf11b65b4062cd80997aa01a774
refs/heads/master
2020-05-25T19:59:16.455671
2019-05-22T05:07:39
2019-05-22T05:07:39
187,963,908
0
0
null
null
null
null
UTF-8
Java
false
false
238
java
public class PUBGplayer { void play() { PUBGgame g = new PUBGgame(); PUBGweapon wpn = g.pressButton(); wpn.use(); } public static void main(String[] args) { PUBGplayer p = new PUBGplayer(); p.play(); } }
[ "nandhak9077@gmail.com" ]
nandhak9077@gmail.com
36cc798e1734b1d3ea7631b922b9c3dc25964509
bb590e42ed463da275b972d63ffb5298a71f57ed
/app/src/main/java/com/hbh/cl/customview/model/SesameModel.java
af403b04b9e9664904f00b99cd703cb5189f294e
[]
no_license
yuyiqiushui/CustomView
48f87165ef6bf2bd5f3fb28f6b43199d3d1e2a2e
a153d12efcc436b09016960f8d85782287505b30
refs/heads/master
2020-04-03T15:08:55.998454
2017-07-03T11:05:03
2017-07-03T11:05:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,672
java
package com.hbh.cl.customview.model; import java.io.Serializable; import java.lang.String;import java.util.ArrayList; /** * Created by hbh on 2017/6/16. */ public class SesameModel implements Serializable { private int AQI_value;//AQI private String level;//污染级别 private int totalMin;//区间最小值 private int totalMax;//区间最大值 private String firstText;//第一个文本值:BETA private String updateTime;//更新时间 private ArrayList<PanelItemModel> panelItemModels; public String getFirstText() { return firstText; } public void setFirstText(String firstText) { this.firstText = firstText; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public int getAQI_value() { return AQI_value; } public void setAQI_value(int AQI_value) { this.AQI_value = AQI_value; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getTotalMin() { return totalMin; } public void setTotalMin(int totalMin) { this.totalMin = totalMin; } public int getTotalMax() { return totalMax; } public void setTotalMax(int totalMax) { this.totalMax = totalMax; } public ArrayList<PanelItemModel> getPanelItemModels() { return panelItemModels; } public void setPanelItemModels(ArrayList<PanelItemModel> panelItemModels) { this.panelItemModels = panelItemModels; } }
[ "523217955@qq.com" ]
523217955@qq.com
13533e2305767fdae6ff4f709d12301d720fc12c
e03b109201dd7247de41c79340f328269531c39e
/src/main/java/sages/bootcamp/example/jooq/Tables.java
3e2629d46c72c5d1f0da4831705b25ae745ad83b
[]
no_license
marcinkrol1024/camp10-cars
ad7c0a032254170f4c4d27a03de89868e5b1dc1c
ea0b925813a9e1f16889e87c0163bdd323f04674
refs/heads/master
2020-12-03T02:02:43.028409
2017-06-30T15:02:08
2017-06-30T15:02:08
95,898,885
0
0
null
null
null
null
UTF-8
Java
false
true
584
java
/* * This file is generated by jOOQ. */ package sages.bootcamp.example.jooq; import javax.annotation.Generated; import sages.bootcamp.example.jooq.tables.Cars; /** * Convenience access to all tables in public */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Tables { /** * The table <code>public.cars</code>. */ public static final Cars CARS = sages.bootcamp.example.jooq.tables.Cars.CARS; }
[ "marcins1024@gmail.com" ]
marcins1024@gmail.com
f82d16e103bc6dac66f0069c6c3bb220f11a99d1
8583d852dc445dea7c5b5fd66e71168178a9c5be
/MedAula/trunk/med-aula/src/main/java/br/com/medaula/entity/Tweet.java
0d93d3ac0ea6b46531a970fdedebfbe58060b078
[]
no_license
DatasetCRION/Sistema-CRION
89543941937a25035eb24800b47c6aa71a4b329b
2d5edf5df04829e7ff6c93afffa8f08c8610d14a
refs/heads/master
2021-05-06T09:20:04.879487
2017-12-13T01:35:07
2017-12-13T01:35:07
114,054,314
0
0
null
null
null
null
UTF-8
Java
false
false
2,941
java
package br.com.medaula.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import br.com.medaula.entity.base.BaseEntityImpl; @Entity @Table(name = "tweet") public class Tweet extends BaseEntityImpl<Tweet> { private static final long serialVersionUID = -90563202302656760L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private int id; @Column(name = "id_tweet") private String nametwet; @Column(name = "name") private String name; @Column(name = "id_usuario") private String idusuario; @Column(name = "ProfileLocation") private String profileLocation; @Column(name = "Text") private String text; @Column(name = "Lat") private double lat; @Column(name = "Lng") private double lng; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the nametwet */ public String getNametwet() { return nametwet; } /** * @param nametwet the nametwet to set */ public void setNametwet(String nametwet) { this.nametwet = nametwet; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the idusuario */ public String getIdusuario() { return idusuario; } /** * @param idusuario the idusuario to set */ public void setIdusuario(String idusuario) { this.idusuario = idusuario; } /** * @return the profileLocation */ public String getProfileLocation() { return profileLocation; } /** * @param profileLocation the profileLocation to set */ public void setProfileLocation(String profileLocation) { this.profileLocation = profileLocation; } /** * @return the text */ public String getText() { return text; } /** * @param text the text to set */ public void setText(String text) { this.text = text; } /** * @return the lat */ public double getLat() { return lat; } /** * @param lat the lat to set */ public void setLat(double lat) { this.lat = lat; } /** * @return the lng */ public double getLng() { return lng; } /** * @param lng the lng to set */ public void setLng(double lng) { this.lng = lng; } }
[ "34493735+Vfsalgado@users.noreply.github.com" ]
34493735+Vfsalgado@users.noreply.github.com
1e498d578faa567ee029b75ba6a8c4dcdf2cef35
442a660162355ae5299a6be811ec09f44d3f8a61
/main/src/main/java/com/brufino/android/playground/components/main/pages/statistics/StatisticsFragment.java
9f55144c547533da2219dc8faece37cdff8076ed
[]
no_license
bernardorufino/android-transfer
a53158450b5a339bd1fdd83f9d29dbbdbfa88991
cf35125a55310191dd1a8b3d25dccc5dbd2b0a1d
refs/heads/master
2021-10-24T23:24:52.796255
2019-03-23T15:21:33
2019-03-23T15:21:33
178,473,904
0
0
null
null
null
null
UTF-8
Java
false
false
1,705
java
package com.brufino.android.playground.components.main.pages.statistics; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import com.brufino.android.playground.databinding.StatisticsFragmentBinding; import com.brufino.android.playground.provision.Provisioners; public class StatisticsFragment extends Fragment { private final StatisticsFragmentProvisioner mProvisioner; private ViewModelProvider.Factory mViewModelFactory; private StatisticsFragmentBinding mBinding; public StatisticsFragment() { mProvisioner = Provisioners.get().getStatisticsFragmentProvisioner(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mViewModelFactory = mProvisioner.getViewModelFactory(); } @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mBinding = StatisticsFragmentBinding.inflate(inflater, container, false); mBinding.setLifecycleOwner(this); return mBinding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); StatisticsViewModel data = ViewModelProviders.of(this, mViewModelFactory).get(StatisticsViewModel.class); mBinding.setViewModel(data); } }
[ "brufino@google.com" ]
brufino@google.com
2812c62afc87bfb3b2ed84334e0dd8a7027c8744
d03074416e5e6b6ed65311baeee1fd84ac4d3c95
/hw04-0036491099/src/main/java/hr/fer/zemris/optjava/dz4/algorithms/Main.java
bf8e05290c8cbe714399dfc0527f93fdb16f8c09
[]
no_license
Masperado/NENR-Project-FER-2019
f62a534deb4d727214d02e198f20972c44f0dc07
614b7aee13279a78802053093293014ea5c74f33
refs/heads/master
2020-04-24T21:32:37.031677
2019-02-24T01:10:44
2019-02-24T01:10:44
172,281,982
0
1
null
null
null
null
UTF-8
Java
false
false
3,278
java
package hr.fer.zemris.optjava.dz4.algorithms; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Random; import hr.fer.zemris.optjava.dz4.api.ICrossing; import hr.fer.zemris.optjava.dz4.api.IFunction; import hr.fer.zemris.optjava.dz4.api.IMutation; import hr.fer.zemris.optjava.dz4.api.ISelection; import hr.fer.zemris.optjava.dz4.impl.*; public class Main { // zad4-dataset1.txt 200 0.000001 1000 true 0.2 false // zad4-dataset2.txt 200 0.000001 1000 true 0.2 false // zad4-dataset1.txt 200 0.000001 1000 false 0.5 false // zad4-dataset2.txt 200 0.000001 1000 false 0.5 false // zad4-dataset1.txt 20 0.000001 10000 false 0.2 true // zad4-dataset2.txt 20 0.000001 10000 false 0.2 true public static void main(String[] args) throws IOException { if (args.length != 7) { System.out.println("Neispravan broj argumenta"); System.exit(1); } List<String> rows = Files.readAllLines(Paths.get(args[0])); double[] consts = new double[rows.size()]; double[][] inputs = new double[rows.size()][2]; for (int i = 0; i < rows.size(); i++) { String[] values = rows.get(i).split("\\s+"); for (int j = 0; j < values.length - 1; j++) { inputs[i][j] = Double.valueOf(values[j]); } consts[i] = Double.valueOf(values[values.length - 1]); } IFunction<double[]> function = new AFFunction(inputs, consts); int populationSize = Integer.valueOf(args[1]); double[][] startingPopulation = generatePopulation(populationSize); double minError = Double.valueOf(args[2]); int maxIterations = Integer.valueOf(args[3]); ISelection<double[]> selectionGeneration = new RouletteWheel(); ISelection<double[]> selectionElimination = new NTournamentDoubleArray(3); boolean elite = Boolean.valueOf(args[4]); double sigma = Double.valueOf(args[5]); IMutation<double[]> mutation = new SigmaMutation(sigma); ICrossing<double[]> crossing = new BLX(0.1); boolean elimination = Boolean.valueOf(args[6]); if (!elimination) { GenerationAlgorithm<double[]> algorithm = new GenerationAlgorithm<>(startingPopulation, function, crossing, mutation, selectionGeneration, elite, minError, maxIterations); algorithm.run(); } else { EliminationAlgorithm<double[]> algorithm = new EliminationAlgorithm<>(startingPopulation, function, crossing, mutation, selectionElimination, minError, maxIterations); algorithm.run(); } } private static double[][] generatePopulation(int populationSize) { double[][] population = new double[populationSize][6]; for (int i = 0; i < populationSize; i++) { population[i] = generateSolution(); } return population; } private static double[] generateSolution() { Random rand = new Random(); double[] solution = new double[5]; for (int i = 0; i < 5; i++) { solution[i] = -4 + rand.nextDouble() * 8; } return solution; } }
[ "masperado@gmail.com" ]
masperado@gmail.com
02f3b95bd34ead95a7aa25b2269844663cee08d2
0344226d2c2399650639b2672c537cb5c69ac8b0
/src/recursividad/ejercicio8.java
6d94a75e83a5b32b5eb8636e23254b36c229d8b8
[]
no_license
Varo95/Recursividad
39803a8d40f96217e43fcdd20da86c598bfd2a1f
58bdde825b45ab6c7ebfae77665547d2c233b788
refs/heads/master
2021-01-07T07:02:52.258772
2020-02-19T12:17:37
2020-02-19T12:17:37
241,614,711
0
0
null
null
null
null
UTF-8
Java
false
false
588
java
package recursividad; public class ejercicio8 { public static void main(String[] args) { int base=24; int exponente=-5; System.out.println(potencia(base,exponente)); } public static double potencia(int base, int exponente) { if (exponente==0) { return 1; } else if (exponente==1) { return base; } else if (exponente<0) { return potencia(base,exponente+1) / base; } else { return base*potencia(base,exponente-1); } } }
[ "Alvaro@Lenovo-y700" ]
Alvaro@Lenovo-y700
a5889fe0a5bf27b5215f4245d6c3e6733f5c1639
c42ad5074aa90a181d5ea061df649d41c76ae98a
/src/threads/TicketHandler.java
4c5104993fc6b9beb12a52691734df4f0aeaf286
[]
no_license
Denky230/HotelStucom
505d1cffa7da552e063f45c17e8037f7593ea25f
0295ca1b4649918592eb3d29195d5a2b7d3ddaad
refs/heads/master
2020-04-18T11:05:12.176129
2019-02-11T13:22:34
2019-02-11T13:22:34
165,681,871
0
0
null
null
null
null
UTF-8
Java
false
false
1,406
java
package threads; import exceptions.MyException; import input.InputHandler; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import management.Manager; public class TicketHandler implements Runnable { private final String FILE_PATH; private final int SPEED; private final InputHandler input = InputHandler.getInstance(); private final Manager manager = Manager.getInstance(); public TicketHandler(String filePath, int speed) { this.FILE_PATH = filePath; this.SPEED = speed; } @Override public void run() { try ( FileReader fr = new FileReader(FILE_PATH); BufferedReader br = new BufferedReader(fr); ) { // Read Customer requests until none are left or money <= 0 String line; while ((line = br.readLine()) != null && manager.getMoney() > 0) { try { // Each hotel cycle (day) Thread.sleep(SPEED); input.processCustomerInput(line); } catch (MyException e) { System.out.println(e.getMessage()); } } } catch (IOException | InterruptedException e) { System.out.println(e.getMessage()); } } }
[ "sorek230@gmail.com" ]
sorek230@gmail.com
9b53c3859140bd4c35cb4968d8269382ec2ea9ad
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-111/u-11-111-1111/u-11-111-1111-f7174.java
19974729f55a41d15b7656ba0081ab30b53478a1
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
106
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 7368563015107
[ "jenkins@khan.paloaltonetworks.local" ]
jenkins@khan.paloaltonetworks.local
a09e4408c2b54b83269307bf59be5e82d12571e6
dc14f1990f70e7cf4c1064847948a0b7f9fc0582
/src/main/java/com/dc/smarteam/modules/oa/web/TestAuditController.java
2e4b7e5fd48abed455edbf990dd98118341cc810
[ "Apache-2.0" ]
permissive
VincentFxz/EAM
2969e39217ec6da483d5257b8d6c07f61d88a2b8
65b503540b92c21529ec7ff61614052112fb5ba4
refs/heads/master
2021-01-10T14:34:40.884062
2015-12-08T01:37:41
2015-12-08T01:37:41
47,590,648
1
5
null
null
null
null
UTF-8
Java
false
false
5,302
java
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.dc.smarteam.modules.oa.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dc.smarteam.common.persistence.Page; import com.dc.smarteam.modules.oa.entity.TestAudit; import com.dc.smarteam.modules.sys.entity.User; import com.dc.smarteam.modules.sys.utils.UserUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.dc.smarteam.common.persistence.Page; import com.dc.smarteam.common.web.BaseController; import com.dc.smarteam.modules.sys.entity.User; import com.dc.smarteam.modules.sys.utils.UserUtils; import com.dc.smarteam.modules.oa.entity.TestAudit; import com.dc.smarteam.modules.oa.service.TestAuditService; /** * 审批Controller * @author thinkgem * @version 2014-05-16 */ @Controller @RequestMapping(value = "${adminPath}/oa/testAudit") public class TestAuditController extends BaseController { @Autowired private TestAuditService testAuditService; @ModelAttribute public TestAudit get(@RequestParam(required=false) String id){//, // @RequestParam(value="act.procInsId", required=false) String procInsId) { TestAudit testAudit = null; if (StringUtils.isNotBlank(id)){ testAudit = testAuditService.get(id); // }else if (StringUtils.isNotBlank(procInsId)){ // testAudit = testAuditService.getByProcInsId(procInsId); } if (testAudit == null){ testAudit = new TestAudit(); } return testAudit; } @RequiresPermissions("oa:testAudit:view") @RequestMapping(value = {"list", ""}) public String list(TestAudit testAudit, HttpServletRequest request, HttpServletResponse response, Model model) { User user = UserUtils.getUser(); if (!user.isAdmin()){ testAudit.setCreateBy(user); } Page<TestAudit> page = testAuditService.findPage(new Page<TestAudit>(request, response), testAudit); model.addAttribute("page", page); return "modules/oa/testAuditList"; } /** * 申请单填写 * @param testAudit * @param model * @return */ @RequiresPermissions("oa:testAudit:view") @RequestMapping(value = "form") public String form(TestAudit testAudit, Model model) { String view = "testAuditForm"; // 查看审批申请单 if (StringUtils.isNotBlank(testAudit.getId())){//.getAct().getProcInsId())){ // 环节编号 String taskDefKey = testAudit.getAct().getTaskDefKey(); // 查看工单 if(testAudit.getAct().isFinishTask()){ view = "testAuditView"; } // 修改环节 else if ("modify".equals(taskDefKey)){ view = "testAuditForm"; } // 审核环节 else if ("audit".equals(taskDefKey)){ view = "testAuditAudit"; // String formKey = "/oa/testAudit"; // return "redirect:" + ActUtils.getFormUrl(formKey, testAudit.getAct()); } // 审核环节2 else if ("audit2".equals(taskDefKey)){ view = "testAuditAudit"; } // 审核环节3 else if ("audit3".equals(taskDefKey)){ view = "testAuditAudit"; } // 审核环节4 else if ("audit4".equals(taskDefKey)){ view = "testAuditAudit"; } // 兑现环节 else if ("apply_end".equals(taskDefKey)){ view = "testAuditAudit"; } } model.addAttribute("testAudit", testAudit); return "modules/oa/" + view; } /** * 申请单保存/修改 * @param testAudit * @param model * @param redirectAttributes * @return */ @RequiresPermissions("oa:testAudit:edit") @RequestMapping(value = "save") public String save(TestAudit testAudit, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, testAudit)){ return form(testAudit, model); } testAuditService.save(testAudit); addMessage(redirectAttributes, "提交审批'" + testAudit.getUser().getName() + "'成功"); return "redirect:" + adminPath + "/act/task/todo/"; } /** * 工单执行(完成任务) * @param testAudit * @param model * @return */ @RequiresPermissions("oa:testAudit:edit") @RequestMapping(value = "saveAudit") public String saveAudit(TestAudit testAudit, Model model) { if (StringUtils.isBlank(testAudit.getAct().getFlag()) || StringUtils.isBlank(testAudit.getAct().getComment())){ addMessage(model, "请填写审核意见。"); return form(testAudit, model); } testAuditService.auditSave(testAudit); return "redirect:" + adminPath + "/act/task/todo/"; } /** * 删除工单 * @param id * @param redirectAttributes * @return */ @RequiresPermissions("oa:testAudit:edit") @RequestMapping(value = "delete") public String delete(TestAudit testAudit, RedirectAttributes redirectAttributes) { testAuditService.delete(testAudit); addMessage(redirectAttributes, "删除审批成功"); return "redirect:" + adminPath + "/oa/testAudit/?repage"; } }
[ "vincent.fxz@gmail.com" ]
vincent.fxz@gmail.com
c76acb057ce594e66246dde421f6b52afce5d46e
03c54c05ebd632ad1462f1e4b2683655603788db
/app/src/main/java/com/mibtech/nirmalDelivery/activity/WebViewActivity.java
8c893389f8cb52da47ea703b61770c194d2f39e5
[]
no_license
anfaas1618/nirmal-delivery-final
36b56b7c844d75c0d086a84453d202b3f02c3615
253a01536eb3617cf57da43755a575c95e220cf8
refs/heads/master
2023-02-26T14:03:25.545202
2021-02-05T19:43:24
2021-02-05T19:43:24
335,311,493
0
1
null
2021-02-04T14:56:31
2021-02-02T14:14:40
Java
UTF-8
Java
false
false
3,137
java
package com.mibtech.nirmalDelivery.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.mibtech.nirmalDelivery.R; import com.mibtech.nirmalDelivery.helper.AppController; public class WebViewActivity extends AppCompatActivity { public WebView mWebView; public String url,title; public Toolbar toolbar; @Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_web_view); toolbar = findViewById (R.id.toolbar); setSupportActionBar (toolbar); getSupportActionBar ().setDisplayHomeAsUpEnabled (true); title = getIntent ().getStringExtra ("title"); toolbar.setTitle(title); url = getIntent ().getStringExtra ("link"); mWebView = findViewById (R.id.webView1); mWebView.getSettings ().setJavaScriptEnabled (true); mWebView.getSettings ().setSupportZoom (true); mWebView.setWebViewClient (new WebViewClient ()); try { if (AppController.isConnected (this)) { findViewById(R.id.progressBar).setVisibility(View.VISIBLE); mWebView.loadUrl (url); findViewById(R.id.progressBar).setVisibility(View.GONE); } } catch (Exception e) { findViewById(R.id.progressBar).setVisibility(View.GONE); e.printStackTrace (); } } @SuppressLint("NewApi") @Override protected void onResume ( ) { super.onResume (); mWebView.onResume (); } @SuppressLint("NewApi") @Override protected void onPause ( ) { mWebView.onPause (); super.onPause (); } @Override protected void onDestroy ( ) { super.onDestroy (); } @Override public boolean onKeyDown ( int keyCode,KeyEvent event ) { if (event.getAction () == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mWebView.canGoBack ()) { mWebView.goBack (); } else { finish (); } return true; } } return super.onKeyDown (keyCode,event); } @Override protected void onActivityResult ( int requestCode,int resultCode,Intent intent ) { super.onActivityResult (requestCode,resultCode,intent); } @Override public boolean onOptionsItemSelected ( MenuItem item ) { if (item.getItemId () == android.R.id.home) { onBackPressed (); return true; } return super.onOptionsItemSelected (item); } @Override public void onBackPressed ( ) { finish (); super.onBackPressed (); } }
[ "Anfaas@123" ]
Anfaas@123
362e0559d2feb49f394dd4f43987e9cf72ff2caa
9e9c99ea453345c48e8817a7dd687de2b3f1001d
/source/anconsd/src/com/andconsd/ui/activity/PicViewSwitcher.java
06d456caaf62c927a396f016e1ff4281f694ddc6
[]
no_license
haoerloveyou/anconsd
62218040b8cd2484ebb0da339d1e7f6e50552136
229beafc90746a298ba2817f34d5af80eff785c0
refs/heads/master
2021-12-07T12:07:50.299023
2015-11-25T05:26:24
2015-11-25T05:26:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,015
java
package com.andconsd.ui.activity; import java.io.File; import com.andconsd.R; import com.andconsd.ui.widget.DuoleCountDownTimer; import com.andconsd.ui.widget.DuoleVideoView; import com.andconsd.ui.widget.ScrollLayout; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ViewSwitcher.ViewFactory; public class PicViewSwitcher extends Activity implements ViewFactory{ int cacheEnd = 0; int cacheStart = 0; RelativeLayout.LayoutParams lp; ScrollLayout slPic; PicViewSwitcher appref; int imgIndex = 0; TextView tvIndex; RelativeLayout rlController; RelativeLayout rlSlidShow; ImageSwitcher iSwitcher; int screenWidth = 0; int screenHeight = 0; ImageView iv ; DuoleVideoView vv; ImageView ivPlay; File tempFile; ImageView ivSlidShow; DuoleCountDownTimer autoPlayerCountDownTimer; private int ImageViewId = 999998; Handler handler = new Handler(); RotateAnimation rotate; ScaleAnimation scale; AlphaAnimation alpha; TranslateAnimation translate; boolean slidshow = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); appref = this; setContentView(R.layout.picview); imgIndex = getIntent().getIntExtra("index", 0); iSwitcher = (ImageSwitcher) findViewById(R.layout.picview); iSwitcher.setFactory(this); } @Override public View makeView() { View view = LayoutInflater.from(appref).inflate(R.layout.picviewitem, null); return null; } }
[ "taoliang@baidu-mgame.com" ]
taoliang@baidu-mgame.com
f0741049a4693c23af8c009d506c5a092115304d
eed260a2b4d526c7ada66ba77c1b046299390eb8
/sb3_gateway_server/src/main/java/com/topkst/gateway/dao/ScanBeaconDAOImpl.java
e49061cacaf3df2b9e80ffac0494427c0e7514f0
[]
no_license
mpanda-kr/sb3_gateway
5adb33fd098491b7f535373d5c1191a3c423b898
52ea4e0eb181ce7ddc7bf5e9abcf2f24c6d21380
refs/heads/master
2020-04-02T23:18:57.451096
2018-10-30T03:30:16
2018-10-30T03:30:16
154,863,396
0
0
null
null
null
null
UTF-8
Java
false
false
680
java
package com.topkst.gateway.dao; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.topkst.gateway.dto.ScanBeacon; @Repository public class ScanBeaconDAOImpl implements ScanBeaconDAO { @Autowired private SqlSessionTemplate sqlSession; @Override public void setScanBeacon_insert(ScanBeacon beacon) { sqlSession.selectList("com.topkst.beacon.mapper.scanBeacon_isert",beacon); } public void setUltraBeacon_insert(ScanBeacon beacon) { sqlSession.selectList("com.topkst.beacon.mapper.ultraBeacon_isert",beacon); } }
[ "miamhchoi@gmail.com" ]
miamhchoi@gmail.com
7355fec72dca908d5979cc4075d19637bab52047
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipseswt_cluster/14705/tar_1.java
34cd4425e28b0a03515596b3c55647750f81692d
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
262,550
java
/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.widgets; import org.eclipse.swt.internal.*; import org.eclipse.swt.internal.win32.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.events.*; /** * Instances of this class provide a selectable user interface object * that displays a hierarchy of items and issues notification when an * item in the hierarchy is selected. * <p> * The item children that may be added to instances of this class * must be of type <code>TreeItem</code>. * </p><p> * Style <code>VIRTUAL</code> is used to create a <code>Tree</code> whose * <code>TreeItem</code>s are to be populated by the client on an on-demand basis * instead of up-front. This can provide significant performance improvements for * trees that are very large or for which <code>TreeItem</code> population is * expensive (for example, retrieving values from an external source). * </p><p> * Here is an example of using a <code>Tree</code> with style <code>VIRTUAL</code>: * <code><pre> * final Tree tree = new Tree(parent, SWT.VIRTUAL | SWT.BORDER); * tree.setItemCount(20); * tree.addListener(SWT.SetData, new Listener() { * public void handleEvent(Event event) { * TreeItem item = (TreeItem)event.item; * TreeItem parentItem = item.getParentItem(); * String text = null; * if (parentItem == null) { * text = "node " + tree.indexOf(item); * } else { * text = parentItem.getText() + " - " + parentItem.indexOf(item); * } * item.setText(text); * System.out.println(text); * item.setItemCount(10); * } * }); * </pre></code> * </p><p> * Note that although this class is a subclass of <code>Composite</code>, * it does not normally make sense to add <code>Control</code> children to * it, or set a layout on it, unless implementing something like a cell * editor. * </p><p> * <dl> * <dt><b>Styles:</b></dt> * <dd>SINGLE, MULTI, CHECK, FULL_SELECTION, VIRTUAL</dd> * <dt><b>Events:</b></dt> * <dd>Selection, DefaultSelection, Collapse, Expand, SetData, MeasureItem, EraseItem, PaintItem</dd> * </dl> * </p><p> * Note: Only one of the styles SINGLE and MULTI may be specified. * </p><p> * IMPORTANT: This class is <em>not</em> intended to be subclassed. * </p> */ public class Tree extends Composite { TreeItem [] items; TreeColumn [] columns; ImageList imageList, headerImageList; TreeItem currentItem; TreeColumn sortColumn; int /*long*/ hwndParent, hwndHeader, hAnchor, hInsert, hSelect; int lastID; int /*long*/ hFirstIndexOf, hLastIndexOf; int lastIndexOf, itemCount, sortDirection; boolean dragStarted, gestureCompleted, insertAfter, shrink, ignoreShrink; boolean ignoreSelect, ignoreExpand, ignoreDeselect, ignoreResize; boolean lockSelection, oldSelected, newSelected, ignoreColumnMove; boolean linesVisible, customDraw, printClient, painted, ignoreItemHeight; boolean ignoreCustomDraw, ignoreDrawForeground, ignoreDrawBackground, ignoreDrawFocus; boolean ignoreDrawSelection, ignoreDrawHot, ignoreFullSelection, explorerTheme; int scrollWidth, selectionForeground; int /*long*/ headerToolTipHandle, itemToolTipHandle; static final int INSET = 3; static final int GRID_WIDTH = 1; static final int SORT_WIDTH = 10; static final int HEADER_MARGIN = 12; static final int HEADER_EXTRA = 3; static final int INCREMENT = 5; static final int EXPLORER_EXTRA = 2; static final boolean EXPLORER_THEME = true; static final int /*long*/ TreeProc; static final TCHAR TreeClass = new TCHAR (0, OS.WC_TREEVIEW, true); static final int /*long*/ HeaderProc; static final TCHAR HeaderClass = new TCHAR (0, OS.WC_HEADER, true); static { WNDCLASS lpWndClass = new WNDCLASS (); OS.GetClassInfo (0, TreeClass, lpWndClass); TreeProc = lpWndClass.lpfnWndProc; OS.GetClassInfo (0, HeaderClass, lpWndClass); HeaderProc = lpWndClass.lpfnWndProc; } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>SWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>SWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see SWT#SINGLE * @see SWT#MULTI * @see SWT#CHECK * @see Widget#checkSubclass * @see Widget#getStyle */ public Tree (Composite parent, int style) { super (parent, checkStyle (style)); } static int checkStyle (int style) { /* * Feature in Windows. It is not possible to create * a tree that scrolls and does not have scroll bars. * The TVS_NOSCROLL style will remove the scroll bars * but the tree will never scroll. Therefore, no matter * what style bits are specified, set the H_SCROLL and * V_SCROLL bits so that the SWT style will match the * widget that Windows creates. */ style |= SWT.H_SCROLL | SWT.V_SCROLL; return checkBits (style, SWT.SINGLE, SWT.MULTI, 0, 0, 0, 0); } void _addListener (int eventType, Listener listener) { super._addListener (eventType, listener); switch (eventType) { case SWT.DragDetect: { if ((state & DRAG_DETECT) != 0) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits &= ~OS.TVS_DISABLEDRAGDROP; OS.SetWindowLong (handle, OS.GWL_STYLE, bits); } break; } case SWT.MeasureItem: case SWT.EraseItem: case SWT.PaintItem: { customDraw = true; style |= SWT.DOUBLE_BUFFERED; OS.SendMessage (handle, OS.TVM_SETSCROLLTIME, 0, 0); int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits |= OS.TVS_NOTOOLTIPS; if (eventType == SWT.MeasureItem) bits |= OS.TVS_NOHSCROLL; /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of any custom drawing. The fix * is to clear TVS_FULLROWSELECT. */ if ((style & SWT.FULL_SELECTION) != 0) { if (eventType != SWT.MeasureItem) { if (!explorerTheme) bits &= ~OS.TVS_FULLROWSELECT; } } if (bits != OS.GetWindowLong (handle, OS.GWL_STYLE)) { OS.SetWindowLong (handle, OS.GWL_STYLE, bits); OS.InvalidateRect (handle, null, true); /* * Bug in Windows. When TVS_NOHSCROLL is set after items * have been inserted into the tree, Windows shows the * scroll bar. The fix is to check for this case and * explicitly hide the scroll bar. */ int count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (count != 0 && (bits & OS.TVS_NOHSCROLL) != 0) { if (!OS.IsWinCE) OS.ShowScrollBar (handle, OS.SB_HORZ, false); } } break; } } } TreeItem _getItem (int /*long*/ hItem) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = hItem; if (OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem) != 0) { return _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); } return null; } TreeItem _getItem (int /*long*/ hItem, int id) { if ((style & SWT.VIRTUAL) == 0) return items [id]; return id != -1 ? items [id] : new TreeItem (this, SWT.NONE, -1, -1, hItem); } void _setBackgroundPixel (int newPixel) { int oldPixel = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETBKCOLOR, 0, 0); if (oldPixel != newPixel) { /* * Bug in Windows. When TVM_SETBKCOLOR is used more * than once to set the background color of a tree, * the background color of the lines and the plus/minus * does not change to the new color. The fix is to set * the background color to the default before setting * the new color. */ if (oldPixel != -1) { OS.SendMessage (handle, OS.TVM_SETBKCOLOR, 0, -1); } /* Set the background color */ OS.SendMessage (handle, OS.TVM_SETBKCOLOR, 0, newPixel); /* * Feature in Windows. When TVM_SETBKCOLOR is used to * set the background color of a tree, the plus/minus * animation draws badly. The fix is to clear the effect. */ if (explorerTheme) { int bits2 = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0); if (newPixel == -1 && findImageControl () == null) { bits2 |= OS.TVS_EX_FADEINOUTEXPANDOS; } else { bits2 &= ~OS.TVS_EX_FADEINOUTEXPANDOS; } OS.SendMessage (handle, OS.TVM_SETEXTENDEDSTYLE, 0, bits2); } /* Set the checkbox image list */ if ((style & SWT.CHECK) != 0) setCheckboxImageList (); } } /** * Adds the listener to the collection of listeners who will * be notified when the user changes the receiver's selection, by sending * it one of the messages defined in the <code>SelectionListener</code> * interface. * <p> * When <code>widgetSelected</code> is called, the item field of the event object is valid. * If the receiver has the <code>SWT.CHECK</code> style and the check selection changes, * the event object detail field contains the value <code>SWT.CHECK</code>. * <code>widgetDefaultSelected</code> is typically called when an item is double-clicked. * The item field of the event object is valid for default selection, but the detail field is not used. * </p> * * @param listener the listener which should be notified when the user changes the receiver's selection * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #removeSelectionListener * @see SelectionEvent */ public void addSelectionListener(SelectionListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Selection, typedListener); addListener (SWT.DefaultSelection, typedListener); } /** * Adds the listener to the collection of listeners who will * be notified when an item in the receiver is expanded or collapsed * by sending it one of the messages defined in the <code>TreeListener</code> * interface. * * @param listener the listener which should be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #removeTreeListener */ public void addTreeListener(TreeListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); TypedListener typedListener = new TypedListener (listener); addListener (SWT.Expand, typedListener); addListener (SWT.Collapse, typedListener); } int /*long*/ borderHandle () { return hwndParent != 0 ? hwndParent : handle; } LRESULT CDDS_ITEMPOSTPAINT (NMTVCUSTOMDRAW nmcd, int /*long*/ wParam, int /*long*/ lParam) { if (ignoreCustomDraw) return null; if (nmcd.left == nmcd.right) return new LRESULT (OS.CDRF_DODEFAULT); int /*long*/ hDC = nmcd.hdc; OS.RestoreDC (hDC, -1); TreeItem item = getItem (nmcd); /* * Feature in Windows. When a new tree item is inserted * using TVM_INSERTITEM and the tree is using custom draw, * a NM_CUSTOMDRAW is sent before TVM_INSERTITEM returns * and before the item is added to the items array. The * fix is to check for null. * * NOTE: This only happens on XP with the version 6.00 of * COMCTL32.DLL, */ if (item == null) return null; /* * Feature in Windows. Under certain circumstances, Windows * sends CDDS_ITEMPOSTPAINT for an empty rectangle. This is * not a problem providing that graphics do not occur outside * the rectangle. The fix is to test for the rectangle and * draw nothing. * * NOTE: This seems to happen when both I_IMAGECALLBACK * and LPSTR_TEXTCALLBACK are used at the same time with * TVM_SETITEM. */ if (nmcd.left >= nmcd.right || nmcd.top >= nmcd.bottom) return null; if (!OS.IsWindowVisible (handle)) return null; if ((style & SWT.FULL_SELECTION) != 0 || findImageControl () != null || ignoreDrawSelection || explorerTheme) { OS.SetBkMode (hDC, OS.TRANSPARENT); } boolean selected = isItemSelected (nmcd); boolean hot = explorerTheme && (nmcd.uItemState & OS.CDIS_HOT) != 0; if (OS.IsWindowEnabled (handle)) { if (explorerTheme) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_TRACKSELECT) != 0) { if ((style & SWT.FULL_SELECTION) != 0 && (selected || hot)) { OS.SetTextColor (hDC, OS.GetSysColor (OS.COLOR_WINDOWTEXT)); } else { OS.SetTextColor (hDC, getForegroundPixel ()); } } } } int count = 0; int [] order = null; RECT clientRect = new RECT (); OS.GetClientRect (scrolledHandle (), clientRect); if (hwndHeader != 0) { OS.MapWindowPoints (hwndParent, handle, clientRect, 2); count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (count != 0) { order = new int [count]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, order); } } int sortIndex = -1, clrSortBk = -1; if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { if (sortColumn != null && sortDirection != SWT.NONE) { if (findImageControl () == null) { sortIndex = indexOf (sortColumn); clrSortBk = getSortColumnPixel (); } } } int x = 0; Point size = null; for (int i=0; i<Math.max (1, count); i++) { int index = order == null ? i : order [i], width = nmcd.right - nmcd.left; if (count > 0 && hwndHeader != 0) { HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); width = hdItem.cxy; } if (i == 0) { if ((style & SWT.FULL_SELECTION) != 0) { boolean clear = !explorerTheme && !ignoreDrawSelection && findImageControl () == null; if (clear || (selected && !ignoreDrawSelection) || (hot && !ignoreDrawHot)) { boolean draw = true; RECT pClipRect = new RECT (); OS.SetRect (pClipRect, width, nmcd.top, nmcd.right, nmcd.bottom); if (explorerTheme) { if (hooks (SWT.EraseItem)) { RECT itemRect = item.getBounds (index, true, true, false, false, true, hDC); itemRect.left -= EXPLORER_EXTRA; itemRect.right += EXPLORER_EXTRA + 1; pClipRect.left = itemRect.left; pClipRect.right = itemRect.right; if (count > 0 && hwndHeader != 0) { HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); pClipRect.right = Math.min (pClipRect.right, nmcd.left + hdItem.cxy); } } RECT pRect = new RECT (); OS.SetRect (pRect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (count > 0 && hwndHeader != 0) { int totalWidth = 0; HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; for (int j=0; j<count; j++) { OS.SendMessage (hwndHeader, OS.HDM_GETITEM, j, hdItem); totalWidth += hdItem.cxy; } if (totalWidth > clientRect.right - clientRect.left) { pRect.left = 0; pRect.right = totalWidth; } else { pRect.left = clientRect.left; pRect.right = clientRect.right; } } draw = false; int /*long*/ hTheme = OS.OpenThemeData (handle, Display.TREEVIEW); int iStateId = selected ? OS.TREIS_SELECTED : OS.TREIS_HOT; if (OS.GetFocus () != handle && selected && !hot) iStateId = OS.TREIS_SELECTEDNOTFOCUS; OS.DrawThemeBackground (hTheme, hDC, OS.TVP_TREEITEM, iStateId, pRect, pClipRect); OS.CloseThemeData (hTheme); } if (draw) fillBackground (hDC, OS.GetBkColor (hDC), pClipRect); } } else { if (explorerTheme && hooks (SWT.EraseItem)) { if ((selected && !ignoreDrawSelection) || (hot && !ignoreDrawHot)) { RECT pRect = item.getBounds (index, true, true, false, false, false, hDC); RECT pClipRect = item.getBounds (index, true, true, false, false, true, hDC); pRect.left -= EXPLORER_EXTRA; pRect.right += EXPLORER_EXTRA; pClipRect.left -= EXPLORER_EXTRA; pClipRect.right += EXPLORER_EXTRA; int /*long*/ hTheme = OS.OpenThemeData (handle, Display.TREEVIEW); int iStateId = selected ? OS.TREIS_SELECTED : OS.TREIS_HOT; if (OS.GetFocus () != handle && selected && !hot) iStateId = OS.TREIS_SELECTEDNOTFOCUS; OS.DrawThemeBackground (hTheme, hDC, OS.TVP_TREEITEM, iStateId, pRect, pClipRect); OS.CloseThemeData (hTheme); } } } } if (x + width > clientRect.left) { RECT rect = new RECT (), backgroundRect = null; boolean drawItem = true, drawText = true, drawImage = true, drawBackground = false; if (i == 0) { drawItem = drawImage = drawText = false; if (findImageControl () != null) { if (explorerTheme) { if (OS.IsWindowEnabled (handle) && !hooks (SWT.EraseItem)) { Image image = null; if (index == 0) { image = item.image; } else { Image [] images = item.images; if (images != null) image = images [index]; } if (image != null) { Rectangle bounds = image.getBounds (); if (size == null) size = getImageSize (); if (!ignoreDrawForeground) { GCData data = new GCData(); data.device = display; GC gc = GC.win32_new (hDC, data); RECT iconRect = item.getBounds (index, false, true, false, false, true, hDC); gc.setClipping (iconRect.left, iconRect.top, iconRect.right - iconRect.left, iconRect.bottom - iconRect.top); gc.drawImage (image, 0, 0, bounds.width, bounds.height, iconRect.left, iconRect.top, size.x, size.y); OS.SelectClipRgn (hDC, 0); gc.dispose (); } } } } else { drawItem = drawText = drawBackground = true; rect = item.getBounds (index, true, false, false, false, true, hDC); if (linesVisible) { rect.right++; rect.bottom++; } } } if (selected && !ignoreDrawSelection && !ignoreDrawBackground) { if (!explorerTheme) fillBackground (hDC, OS.GetBkColor (hDC), rect); drawBackground = false; } backgroundRect = rect; if (hooks (SWT.EraseItem)) { drawItem = drawText = drawImage = true; rect = item.getBounds (index, true, true, false, false, true, hDC); if ((style & SWT.FULL_SELECTION) != 0) { backgroundRect = rect; } else { backgroundRect = item.getBounds (index, true, false, false, false, true, hDC); } } } else { selectionForeground = -1; ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = false; OS.SetRect (rect, x, nmcd.top, x + width, nmcd.bottom); backgroundRect = rect; } int clrText = -1, clrTextBk = -1; int /*long*/ hFont = item.fontHandle (index); if (selectionForeground != -1) clrText = selectionForeground; if (OS.IsWindowEnabled (handle)) { boolean drawForeground = false; if (selected) { if (i != 0 && (style & SWT.FULL_SELECTION) == 0) { OS.SetTextColor (hDC, getForegroundPixel ()); OS.SetBkColor (hDC, getBackgroundPixel ()); drawForeground = drawBackground = true; } } else { drawForeground = drawBackground = true; } if (drawForeground) { clrText = item.cellForeground != null ? item.cellForeground [index] : -1; if (clrText == -1) clrText = item.foreground; } if (drawBackground) { clrTextBk = item.cellBackground != null ? item.cellBackground [index] : -1; if (clrTextBk == -1) clrTextBk = item.background; if (clrTextBk == -1 && index == sortIndex) clrTextBk = clrSortBk; } } else { if (clrTextBk == -1 && index == sortIndex) { drawBackground = true; clrTextBk = clrSortBk; } } if (explorerTheme) { if (selected || (nmcd.uItemState & OS.CDIS_HOT) != 0) { if ((style & SWT.FULL_SELECTION) != 0) { drawBackground = false; } else { if (i == 0) { drawBackground = false; if (!hooks (SWT.EraseItem)) drawText = false; } } } } if (drawItem) { if (i != 0) { if (hooks (SWT.MeasureItem)) { sendMeasureItemEvent (item, index, hDC); if (isDisposed () || item.isDisposed ()) break; } if (hooks (SWT.EraseItem)) { RECT cellRect = item.getBounds (index, true, true, true, true, true, hDC); int nSavedDC = OS.SaveDC (hDC); GCData data = new GCData (); data.device = display; data.foreground = OS.GetTextColor (hDC); data.background = OS.GetBkColor (hDC); if (!selected || (style & SWT.FULL_SELECTION) == 0) { if (clrText != -1) data.foreground = clrText; if (clrTextBk != -1) data.background = clrTextBk; } data.hFont = hFont; data.uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); GC gc = GC.win32_new (hDC, data); Event event = new Event (); event.item = item; event.index = index; event.gc = gc; event.detail |= SWT.FOREGROUND; if (clrTextBk != -1) event.detail |= SWT.BACKGROUND; if ((style & SWT.FULL_SELECTION) != 0) { if (hot) event.detail |= SWT.HOT; if (selected) event.detail |= SWT.SELECTED; if (!explorerTheme) { //if ((nmcd.uItemState & OS.CDIS_FOCUS) != 0) { if (OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0) == nmcd.dwItemSpec) { if (handle == OS.GetFocus ()) { int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if ((uiState & OS.UISF_HIDEFOCUS) == 0) event.detail |= SWT.FOCUSED; } } } } event.x = cellRect.left; event.y = cellRect.top; event.width = cellRect.right - cellRect.left; event.height = cellRect.bottom - cellRect.top; gc.setClipping (event.x, event.y, event.width, event.height); sendEvent (SWT.EraseItem, event); event.gc = null; int newTextClr = data.foreground; gc.dispose (); OS.RestoreDC (hDC, nSavedDC); if (isDisposed () || item.isDisposed ()) break; if (event.doit) { ignoreDrawForeground = (event.detail & SWT.FOREGROUND) == 0; ignoreDrawBackground = (event.detail & SWT.BACKGROUND) == 0; if ((style & SWT.FULL_SELECTION) != 0) { ignoreDrawSelection = (event.detail & SWT.SELECTED) == 0; ignoreDrawFocus = (event.detail & SWT.FOCUSED) == 0; ignoreDrawHot = (event.detail & SWT.HOT) == 0; } } else { ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = true; } if (selected && ignoreDrawSelection) ignoreDrawHot = true; if ((style & SWT.FULL_SELECTION) != 0) { if (ignoreDrawSelection) ignoreFullSelection = true; if (!ignoreDrawSelection || !ignoreDrawHot) { if (!selected && !hot) { selectionForeground = OS.GetSysColor (OS.COLOR_HIGHLIGHTTEXT); } else { if (!explorerTheme) { drawBackground = true; ignoreDrawBackground = false; if (handle == OS.GetFocus () && OS.IsWindowEnabled (handle)) { clrTextBk = OS.GetSysColor (OS.COLOR_HIGHLIGHT); } else { clrTextBk = OS.GetSysColor (OS.COLOR_3DFACE); } if (!ignoreFullSelection && index == count - 1) { RECT selectionRect = new RECT (); OS.SetRect (selectionRect, backgroundRect.left, backgroundRect.top, nmcd.right, backgroundRect.bottom); backgroundRect = selectionRect; } } else { RECT pRect = new RECT (); OS.SetRect (pRect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (count > 0 && hwndHeader != 0) { int totalWidth = 0; HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; for (int j=0; j<count; j++) { OS.SendMessage (hwndHeader, OS.HDM_GETITEM, j, hdItem); totalWidth += hdItem.cxy; } if (totalWidth > clientRect.right - clientRect.left) { pRect.left = 0; pRect.right = totalWidth; } else { pRect.left = clientRect.left; pRect.right = clientRect.right; } if (index == count - 1) { RECT selectionRect = new RECT (); OS.SetRect (selectionRect, backgroundRect.left, backgroundRect.top, pRect.right, backgroundRect.bottom); backgroundRect = selectionRect; } } int /*long*/ hTheme = OS.OpenThemeData (handle, Display.TREEVIEW); int iStateId = selected ? OS.TREIS_SELECTED : OS.TREIS_HOT; if (OS.GetFocus () != handle && selected && !hot) iStateId = OS.TREIS_SELECTEDNOTFOCUS; OS.DrawThemeBackground (hTheme, hDC, OS.TVP_TREEITEM, iStateId, pRect, backgroundRect); OS.CloseThemeData (hTheme); } } } else { if (selected) { selectionForeground = newTextClr; if (!explorerTheme) { if (clrTextBk == -1 && OS.IsWindowEnabled (handle)) { Control control = findBackgroundControl (); if (control == null) control = this; clrTextBk = control.getBackgroundPixel (); } } } } } } if (selectionForeground != -1) clrText = selectionForeground; } if (!ignoreDrawBackground) { if (clrTextBk != -1) { if (drawBackground) fillBackground (hDC, clrTextBk, backgroundRect); } else { Control control = findImageControl (); if (control != null) { if (i == 0) { int right = Math.min (rect.right, width); OS.SetRect (rect, rect.left, rect.top, right, rect.bottom); if (drawBackground) fillImageBackground (hDC, control, rect); } else { if (drawBackground) fillImageBackground (hDC, control, rect); } } } } rect.left += INSET - 1; if (drawImage) { Image image = null; if (index == 0) { image = item.image; } else { Image [] images = item.images; if (images != null) image = images [index]; } int inset = i != 0 ? INSET : 0; int offset = i != 0 ? INSET : INSET + 2; if (image != null) { Rectangle bounds = image.getBounds (); if (size == null) size = getImageSize (); if (!ignoreDrawForeground) { //int y1 = rect.top + (index == 0 ? (getItemHeight () - size.y) / 2 : 0); int y1 = rect.top; int x1 = Math.max (rect.left, rect.left - inset + 1); GCData data = new GCData(); data.device = display; GC gc = GC.win32_new (hDC, data); gc.setClipping (x1, rect.top, rect.right - x1, rect.bottom - rect.top); gc.drawImage (image, 0, 0, bounds.width, bounds.height, x1, y1, size.x, size.y); OS.SelectClipRgn (hDC, 0); gc.dispose (); } OS.SetRect (rect, rect.left + size.x + offset, rect.top, rect.right - inset, rect.bottom); } else { if (i == 0) { if (OS.SendMessage (handle, OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0) != 0) { if (size == null) size = getImageSize (); rect.left = Math.min (rect.left + size.x + offset, rect.right); } } else { OS.SetRect (rect, rect.left + offset, rect.top, rect.right - inset, rect.bottom); } } } if (drawText) { /* * Bug in Windows. When DrawText() is used with DT_VCENTER * and DT_ENDELLIPSIS, the ellipsis can draw outside of the * rectangle when the rectangle is empty. The fix is avoid * all text drawing for empty rectangles. */ if (rect.left < rect.right) { String string = null; if (index == 0) { string = item.text; } else { String [] strings = item.strings; if (strings != null) string = strings [index]; } if (string != null) { if (hFont != -1) hFont = OS.SelectObject (hDC, hFont); if (clrText != -1) clrText = OS.SetTextColor (hDC, clrText); if (clrTextBk != -1) clrTextBk = OS.SetBkColor (hDC, clrTextBk); int flags = OS.DT_NOPREFIX | OS.DT_SINGLELINE | OS.DT_VCENTER; if (i != 0) flags |= OS.DT_ENDELLIPSIS; TreeColumn column = columns != null ? columns [index] : null; if (column != null) { if ((column.style & SWT.CENTER) != 0) flags |= OS.DT_CENTER; if ((column.style & SWT.RIGHT) != 0) flags |= OS.DT_RIGHT; } TCHAR buffer = new TCHAR (getCodePage (), string, false); if (!ignoreDrawForeground) OS.DrawText (hDC, buffer, buffer.length (), rect, flags); OS.DrawText (hDC, buffer, buffer.length (), rect, flags | OS.DT_CALCRECT); if (hFont != -1) hFont = OS.SelectObject (hDC, hFont); if (clrText != -1) clrText = OS.SetTextColor (hDC, clrText); if (clrTextBk != -1) clrTextBk = OS.SetBkColor (hDC, clrTextBk); } } } } if (selectionForeground != -1) clrText = selectionForeground; if (hooks (SWT.PaintItem)) { RECT itemRect = item.getBounds (index, true, true, false, false, false, hDC); int nSavedDC = OS.SaveDC (hDC); GCData data = new GCData (); data.device = display; data.hFont = hFont; data.foreground = OS.GetTextColor (hDC); data.background = OS.GetBkColor (hDC); if (selected && (style & SWT.FULL_SELECTION) != 0) { if (selectionForeground != -1) data.foreground = selectionForeground; } else { if (clrText != -1) data.foreground = clrText; if (clrTextBk != -1) data.background = clrTextBk; } data.uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); GC gc = GC.win32_new (hDC, data); Event event = new Event (); event.item = item; event.index = index; event.gc = gc; event.detail |= SWT.FOREGROUND; if (clrTextBk != -1) event.detail |= SWT.BACKGROUND; if (hot) event.detail |= SWT.HOT; if (selected && (i == 0 /*nmcd.iSubItem == 0*/ || (style & SWT.FULL_SELECTION) != 0)) { event.detail |= SWT.SELECTED; } if (!explorerTheme) { //if ((nmcd.uItemState & OS.CDIS_FOCUS) != 0) { if (OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0) == nmcd.dwItemSpec) { if (i == 0 /*nmcd.iSubItem == 0*/ || (style & SWT.FULL_SELECTION) != 0) { if (handle == OS.GetFocus ()) { int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if ((uiState & OS.UISF_HIDEFOCUS) == 0) event.detail |= SWT.FOCUSED; } } } } event.x = itemRect.left; event.y = itemRect.top; event.width = itemRect.right - itemRect.left; event.height = itemRect.bottom - itemRect.top; RECT cellRect = item.getBounds (index, true, true, true, true, true, hDC); int cellWidth = cellRect.right - cellRect.left; int cellHeight = cellRect.bottom - cellRect.top; gc.setClipping (cellRect.left, cellRect.top, cellWidth, cellHeight); sendEvent (SWT.PaintItem, event); event.gc = null; gc.dispose (); OS.RestoreDC (hDC, nSavedDC); if (isDisposed () || item.isDisposed ()) break; } } x += width; if (x > clientRect.right) break; } if (linesVisible) { if ((style & SWT.FULL_SELECTION) != 0) { if (hwndHeader != 0) { if (OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0) != 0) { HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, 0, hdItem); RECT rect = new RECT (); OS.SetRect (rect, nmcd.left + hdItem.cxy, nmcd.top, nmcd.right, nmcd.bottom); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM); } } } RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM); } if (!explorerTheme) { if (handle == OS.GetFocus ()) { int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if ((uiState & OS.UISF_HIDEFOCUS) == 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem == item.handle) { if (!ignoreDrawFocus && findImageControl () != null) { if ((style & SWT.FULL_SELECTION) != 0) { RECT focusRect = new RECT (); OS.SetRect (focusRect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (count > 0 && hwndHeader != 0) { int width = 0; HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; for (int j=0; j<count; j++) { OS.SendMessage (hwndHeader, OS.HDM_GETITEM, j, hdItem); width += hdItem.cxy; } focusRect.left = 0; RECT rect = new RECT (); OS.GetClientRect (handle, rect); focusRect.right = Math.max (width, rect.right - OS.GetSystemMetrics (OS.SM_CXVSCROLL)); } OS.DrawFocusRect (hDC, focusRect); } else { int index = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0); RECT focusRect = item.getBounds (index, true, false, false, false, false, hDC); RECT clipRect = item.getBounds (index, true, false, false, false, true, hDC); OS.IntersectClipRect (hDC, clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); OS.DrawFocusRect (hDC, focusRect); OS.SelectClipRgn (hDC, 0); } } } } } } return new LRESULT (OS.CDRF_DODEFAULT); } LRESULT CDDS_ITEMPREPAINT (NMTVCUSTOMDRAW nmcd, int /*long*/ wParam, int /*long*/ lParam) { /* * Even when custom draw is being ignored, the font needs * to be selected into the HDC so that the item bounds are * measured correctly. */ TreeItem item = getItem (nmcd); /* * Feature in Windows. When a new tree item is inserted * using TVM_INSERTITEM and the tree is using custom draw, * a NM_CUSTOMDRAW is sent before TVM_INSERTITEM returns * and before the item is added to the items array. The * fix is to check for null. * * NOTE: This only happens on XP with the version 6.00 of * COMCTL32.DLL, */ if (item == null) return null; int /*long*/ hDC = nmcd.hdc; int index = hwndHeader != 0 ? (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0) : 0; int /*long*/ hFont = item.fontHandle (index); if (hFont != -1) OS.SelectObject (hDC, hFont); if (ignoreCustomDraw || nmcd.left == nmcd.right) { return new LRESULT (hFont == -1 ? OS.CDRF_DODEFAULT : OS.CDRF_NEWFONT); } int count = 0; RECT clipRect = null; if (hwndHeader != 0) { count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (count != 0) { boolean clip = !printClient; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { clip = true; } if (clip) { clipRect = new RECT (); HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); OS.SetRect (clipRect, nmcd.left, nmcd.top, nmcd.left + hdItem.cxy, nmcd.bottom); } } } int clrText = -1, clrTextBk = -1; if (OS.IsWindowEnabled (handle)) { clrText = item.cellForeground != null ? item.cellForeground [index] : -1; if (clrText == -1) clrText = item.foreground; clrTextBk = item.cellBackground != null ? item.cellBackground [index] : -1; if (clrTextBk == -1) clrTextBk = item.background; } int clrSortBk = -1; if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { if (sortColumn != null && sortDirection != SWT.NONE) { if (findImageControl () == null) { if (indexOf (sortColumn) == index) { clrSortBk = getSortColumnPixel (); if (clrTextBk == -1) clrTextBk = clrSortBk; } } } } boolean selected = isItemSelected (nmcd); boolean hot = explorerTheme && (nmcd.uItemState & OS.CDIS_HOT) != 0; if (OS.IsWindowVisible (handle) && nmcd.left < nmcd.right && nmcd.top < nmcd.bottom) { if (hFont != -1) OS.SelectObject (hDC, hFont); if (linesVisible) { RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM); } //TODO - BUG - measure and erase sent when first column is clipped if (hooks (SWT.MeasureItem)) { sendMeasureItemEvent (item, index, hDC); if (isDisposed () || item.isDisposed ()) return null; } selectionForeground = -1; ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = ignoreFullSelection = false; if (hooks (SWT.EraseItem)) { RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (OS.IsWindowEnabled (handle) || findImageControl () != null) { drawBackground (hDC, rect); } else { fillBackground (hDC, OS.GetBkColor (hDC), rect); } RECT cellRect = item.getBounds (index, true, true, true, true, true, hDC); if (clrSortBk != -1) { RECT fullRect = item.getBounds (index, true, true, true, true, true, hDC); drawBackground (hDC, fullRect, clrSortBk); } int nSavedDC = OS.SaveDC (hDC); GCData data = new GCData (); data.device = display; if (selected && explorerTheme) { data.foreground = OS.GetSysColor (OS.COLOR_WINDOWTEXT); } else { data.foreground = OS.GetTextColor (hDC); } data.background = OS.GetBkColor (hDC); if (!selected) { if (clrText != -1) data.foreground = clrText; if (clrTextBk != -1) data.background = clrTextBk; } data.uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if (hFont != -1) data.hFont = hFont; GC gc = GC.win32_new (hDC, data); Event event = new Event (); event.index = index; event.item = item; event.gc = gc; event.detail |= SWT.FOREGROUND; if (clrTextBk != -1) event.detail |= SWT.BACKGROUND; if (hot) event.detail |= SWT.HOT; if (selected) event.detail |= SWT.SELECTED; if (!explorerTheme) { //if ((nmcd.uItemState & OS.CDIS_FOCUS) != 0) { if (OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0) == nmcd.dwItemSpec) { if (handle == OS.GetFocus ()) { int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if ((uiState & OS.UISF_HIDEFOCUS) == 0) event.detail |= SWT.FOCUSED; } } } event.x = cellRect.left; event.y = cellRect.top; event.width = cellRect.right - cellRect.left; event.height = cellRect.bottom - cellRect.top; gc.setClipping (event.x, event.y, event.width, event.height); sendEvent (SWT.EraseItem, event); event.gc = null; int newTextClr = data.foreground; gc.dispose (); OS.RestoreDC (hDC, nSavedDC); if (isDisposed () || item.isDisposed ()) return null; if (event.doit) { ignoreDrawForeground = (event.detail & SWT.FOREGROUND) == 0; ignoreDrawBackground = (event.detail & SWT.BACKGROUND) == 0; ignoreDrawSelection = (event.detail & SWT.SELECTED) == 0; ignoreDrawFocus = (event.detail & SWT.FOCUSED) == 0; ignoreDrawHot = (event.detail & SWT.HOT) == 0; } else { ignoreDrawForeground = ignoreDrawBackground = ignoreDrawSelection = ignoreDrawFocus = ignoreDrawHot = true; } if (selected && ignoreDrawSelection) ignoreDrawHot = true; if (!ignoreDrawBackground && clrTextBk != -1) { boolean draw = !selected && !hot; if (!explorerTheme && selected) draw = !ignoreDrawSelection; if (draw) { if (count == 0) { if ((style & SWT.FULL_SELECTION) != 0) { fillBackground (hDC, clrTextBk, rect); } else { RECT textRect = item.getBounds (index, true, false, false, false, true, hDC); fillBackground (hDC, clrTextBk, textRect); } } else { fillBackground (hDC, clrTextBk, cellRect); } } } if (ignoreDrawSelection) ignoreFullSelection = true; if (!ignoreDrawSelection || !ignoreDrawHot) { if (!selected && !hot) { selectionForeground = clrText = OS.GetSysColor (OS.COLOR_HIGHLIGHTTEXT); } if (!explorerTheme) { /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of any custom drawing. The fix * is to emulate TVS_FULLROWSELECT. */ if ((style & SWT.FULL_SELECTION) != 0) { if ((style & SWT.FULL_SELECTION) != 0 && count == 0) { fillBackground (hDC, OS.GetBkColor (hDC), rect); } else { fillBackground (hDC, OS.GetBkColor (hDC), cellRect); } } else { RECT textRect = item.getBounds (index, true, false, false, false, true, hDC); fillBackground (hDC, OS.GetBkColor (hDC), textRect); } } } else { if (selected || hot) { selectionForeground = clrText = newTextClr; ignoreDrawSelection = ignoreDrawHot = true; } if (explorerTheme) { nmcd.uItemState |= OS.CDIS_DISABLED; /* * Feature in Windows. On Vista only, when the text * color is unchanged and an item is asked to draw * disabled, it uses the disabled color. The fix is * to modify the color so that is it no longer equal. */ int newColor = clrText == -1 ? getForegroundPixel () : clrText; if (nmcd.clrText == newColor) { nmcd.clrText |= 0x20000000; if (nmcd.clrText == newColor) nmcd.clrText &= ~0x20000000; } else { nmcd.clrText = newColor; } OS.MoveMemory (lParam, nmcd, NMTVCUSTOMDRAW.sizeof); } } if (explorerTheme) { if (selected || (hot && ignoreDrawHot)) nmcd.uItemState &= ~OS.CDIS_HOT; OS.MoveMemory (lParam, nmcd, NMTVCUSTOMDRAW.sizeof); } RECT itemRect = item.getBounds (index, true, true, false, false, false, hDC); OS.SaveDC (hDC); OS.SelectClipRgn (hDC, 0); if (explorerTheme) { itemRect.left -= EXPLORER_EXTRA; itemRect.right += EXPLORER_EXTRA; } //TODO - bug in Windows selection or SWT itemRect /*if (selected)*/ itemRect.right++; if (linesVisible) itemRect.bottom++; if (clipRect != null) { OS.IntersectClipRect (hDC, clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); } OS.ExcludeClipRect (hDC, itemRect.left, itemRect.top, itemRect.right, itemRect.bottom); return new LRESULT (OS.CDRF_DODEFAULT | OS.CDRF_NOTIFYPOSTPAINT); } /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of any custom drawing. The fix * is to emulate TVS_FULLROWSELECT. */ if ((style & SWT.FULL_SELECTION) != 0) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (selected) { fillBackground (hDC, OS.GetBkColor (hDC), rect); } else { if (OS.IsWindowEnabled (handle)) drawBackground (hDC, rect); } nmcd.uItemState &= ~OS.CDIS_FOCUS; OS.MoveMemory (lParam, nmcd, NMTVCUSTOMDRAW.sizeof); } } } LRESULT result = null; if (clrText == -1 && clrTextBk == -1 && hFont == -1) { result = new LRESULT (OS.CDRF_DODEFAULT | OS.CDRF_NOTIFYPOSTPAINT); } else { result = new LRESULT (OS.CDRF_NEWFONT | OS.CDRF_NOTIFYPOSTPAINT); if (hFont != -1) OS.SelectObject (hDC, hFont); if (OS.IsWindowEnabled (handle) && OS.IsWindowVisible (handle)) { /* * Feature in Windows. Windows does not fill the entire cell * with the background color when TVS_FULLROWSELECT is not set. * The fix is to fill the cell with the background color. */ if (clrTextBk != -1) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { if (count != 0 && hwndHeader != 0) { RECT rect = new RECT (); HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.left + hdItem.cxy, nmcd.bottom); if (OS.COMCTL32_MAJOR < 6 || !OS.IsAppThemed ()) { RECT itemRect = new RECT (); if (OS.TreeView_GetItemRect (handle, item.handle, itemRect, true)) { rect.left = Math.min (itemRect.left, rect.right); } } if ((style & SWT.FULL_SELECTION) != 0) { if (!selected) fillBackground (hDC, clrTextBk, rect); } else { if (explorerTheme) { if (!selected && !hot) fillBackground (hDC, clrTextBk, rect); } else { fillBackground (hDC, clrTextBk, rect); } } } else { if ((style & SWT.FULL_SELECTION) != 0) { RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); if (!selected) fillBackground (hDC, clrTextBk, rect); } } } } if (!selected) { nmcd.clrText = clrText == -1 ? getForegroundPixel () : clrText; nmcd.clrTextBk = clrTextBk == -1 ? getBackgroundPixel () : clrTextBk; OS.MoveMemory (lParam, nmcd, NMTVCUSTOMDRAW.sizeof); } } } if (OS.IsWindowEnabled (handle)) { /* * On Vista only, when an item is asked to draw disabled, * the background of the text is not filled with the * background color of the tree. This is true for both * regular and full selection trees. In order to draw a * background image, mark the item as disabled using * CDIS_DISABLED (when not selected) and set the text * to the regular text color to avoid drawing disabled. */ if (explorerTheme) { if (findImageControl () != null) { if (!selected && (nmcd.uItemState & (OS.CDIS_HOT | OS.CDIS_SELECTED)) == 0) { nmcd.uItemState |= OS.CDIS_DISABLED; /* * Feature in Windows. On Vista only, when the text * color is unchanged and an item is asked to draw * disabled, it uses the disabled color. The fix is * to modify the color so it is no longer equal. */ int newColor = clrText == -1 ? getForegroundPixel () : clrText; if (nmcd.clrText == newColor) { nmcd.clrText |= 0x20000000; if (nmcd.clrText == newColor) nmcd.clrText &= ~0x20000000; } else { nmcd.clrText = newColor; } OS.MoveMemory (lParam, nmcd, NMTVCUSTOMDRAW.sizeof); if (clrTextBk != -1) { if ((style & SWT.FULL_SELECTION) != 0) { RECT rect = new RECT (); if (count != 0) { HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.left + hdItem.cxy, nmcd.bottom); } else { OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); } fillBackground (hDC, clrTextBk, rect); } else { RECT textRect = item.getBounds (index, true, false, true, false, true, hDC); fillBackground (hDC, clrTextBk, textRect); } } } } } } else { /* * Feature in Windows. When the tree is disabled, it draws * with a gray background over the sort column. The fix is * to fill the background with the sort column color. */ if (clrSortBk != -1) { RECT rect = new RECT (); HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.left + hdItem.cxy, nmcd.bottom); fillBackground (hDC, clrSortBk, rect); } } OS.SaveDC (hDC); if (clipRect != null) { int /*long*/ hRgn = OS.CreateRectRgn (clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); POINT lpPoint = new POINT (); OS.GetWindowOrgEx (hDC, lpPoint); OS.OffsetRgn (hRgn, -lpPoint.x, -lpPoint.y); OS.SelectClipRgn (hDC, hRgn); OS.DeleteObject (hRgn); } return result; } LRESULT CDDS_POSTPAINT (NMTVCUSTOMDRAW nmcd, int /*long*/ wParam, int /*long*/ lParam) { if (ignoreCustomDraw) return null; if (OS.IsWindowVisible (handle)) { if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { if (sortColumn != null && sortDirection != SWT.NONE) { if (findImageControl () == null) { int index = indexOf (sortColumn); if (index != -1) { int top = nmcd.top; /* * Bug in Windows. For some reason, during a collapse, * when TVM_GETNEXTITEM is sent with TVGN_LASTVISIBLE * and the collapse causes the item being collapsed * to become the last visible item in the tree, the * message takes a long time to process. In order for * the slowness to happen, the children of the item * must have children. Times of up to 11 seconds have * been observed with 23 children, each having one * child. The fix is to use the bottom partially * visible item rather than the last possible item * that could be visible. * * NOTE: This problem only happens on Vista during * WM_NOTIFY with NM_CUSTOMDRAW and CDDS_POSTPAINT. */ int /*long*/ hItem = 0; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { hItem = getBottomItem (); } else { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0); } if (hItem != 0) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, hItem, rect, false)) { top = rect.bottom; } } RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, top, nmcd.right, nmcd.bottom); RECT headerRect = new RECT (); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, index, headerRect); rect.left = headerRect.left; rect.right = headerRect.right; fillBackground (nmcd.hdc, getSortColumnPixel (), rect); } } } } if (linesVisible) { int /*long*/ hDC = nmcd.hdc; if (hwndHeader != 0) { int x = 0; RECT rect = new RECT (); HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { int index = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, i, 0); OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); OS.SetRect (rect, x, nmcd.top, x + hdItem.cxy, nmcd.bottom); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_RIGHT); x += hdItem.cxy; } } int height = 0; RECT rect = new RECT (); /* * Bug in Windows. For some reason, during a collapse, * when TVM_GETNEXTITEM is sent with TVGN_LASTVISIBLE * and the collapse causes the item being collapsed * to become the last visible item in the tree, the * message takes a long time to process. In order for * the slowness to happen, the children of the item * must have children. Times of up to 11 seconds have * been observed with 23 children, each having one * child. The fix is to use the bottom partially * visible item rather than the last possible item * that could be visible. * * NOTE: This problem only happens on Vista during * WM_NOTIFY with NM_CUSTOMDRAW and CDDS_POSTPAINT. */ int /*long*/ hItem = 0; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { hItem = getBottomItem (); } else { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0); } if (hItem != 0) { if (OS.TreeView_GetItemRect (handle, hItem, rect, false)) { height = rect.bottom - rect.top; } } if (height == 0) { height = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMHEIGHT, 0, 0); OS.GetClientRect (handle, rect); OS.SetRect (rect, rect.left, rect.top, rect.right, rect.top + height); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM); } while (rect.bottom < nmcd.bottom) { int top = rect.top + height; OS.SetRect (rect, rect.left, top, rect.right, top + height); OS.DrawEdge (hDC, rect, OS.BDR_SUNKENINNER, OS.BF_BOTTOM); } } } return new LRESULT (OS.CDRF_DODEFAULT); } LRESULT CDDS_PREPAINT (NMTVCUSTOMDRAW nmcd, int /*long*/ wParam, int /*long*/ lParam) { if (explorerTheme) { if ((OS.IsWindowEnabled (handle) && hooks (SWT.EraseItem)) || findImageControl () != null) { RECT rect = new RECT (); OS.SetRect (rect, nmcd.left, nmcd.top, nmcd.right, nmcd.bottom); drawBackground (nmcd.hdc, rect); } } return new LRESULT (OS.CDRF_NOTIFYITEMDRAW | OS.CDRF_NOTIFYPOSTPAINT); } int /*long*/ callWindowProc (int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) { if (handle == 0) return 0; if (hwndParent != 0 && hwnd == hwndParent) { return OS.DefWindowProc (hwnd, msg, wParam, lParam); } if (hwndHeader != 0 && hwnd == hwndHeader) { return OS.CallWindowProc (HeaderProc, hwnd, msg, wParam, lParam); } switch (msg) { case OS.WM_SETFOCUS: { /* * Feature in Windows. When a tree control processes WM_SETFOCUS, * if no item is selected, the first item in the tree is selected. * This is unexpected and might clear the previous selection. * The fix is to detect that there is no selection and set it to * the first visible item in the tree. If the item was not selected, * only the focus is assigned. */ if ((style & SWT.SINGLE) != 0) break; int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem == 0) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); if (hItem != 0) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); hSelect = hItem; ignoreDeselect = ignoreSelect = lockSelection = true; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hItem); ignoreDeselect = ignoreSelect = lockSelection = false; hSelect = 0; if ((tvItem.state & OS.TVIS_SELECTED) == 0) { OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } break; } } int /*long*/ hItem = 0; boolean redraw = false; switch (msg) { /* Keyboard messages */ case OS.WM_KEYDOWN: if (wParam == OS.VK_CONTROL || wParam == OS.VK_SHIFT) break; //FALL THROUGH case OS.WM_CHAR: case OS.WM_IME_CHAR: case OS.WM_KEYUP: case OS.WM_SYSCHAR: case OS.WM_SYSKEYDOWN: case OS.WM_SYSKEYUP: //FALL THROUGH /* Scroll messages */ case OS.WM_HSCROLL: case OS.WM_VSCROLL: //FALL THROUGH /* Resize messages */ case OS.WM_SIZE: redraw = findImageControl () != null && drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); //FALL THROUGH /* Mouse messages */ case OS.WM_LBUTTONDBLCLK: case OS.WM_LBUTTONDOWN: case OS.WM_LBUTTONUP: case OS.WM_MBUTTONDBLCLK: case OS.WM_MBUTTONDOWN: case OS.WM_MBUTTONUP: case OS.WM_MOUSEHOVER: case OS.WM_MOUSELEAVE: case OS.WM_MOUSEMOVE: case OS.WM_MOUSEWHEEL: case OS.WM_RBUTTONDBLCLK: case OS.WM_RBUTTONDOWN: case OS.WM_RBUTTONUP: case OS.WM_XBUTTONDBLCLK: case OS.WM_XBUTTONDOWN: case OS.WM_XBUTTONUP: //FALL THROUGH /* Other messages */ case OS.WM_SETFONT: case OS.WM_TIMER: { if (findImageControl () != null) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); } break; } } int /*long*/ code = OS.CallWindowProc (TreeProc, hwnd, msg, wParam, lParam); switch (msg) { /* Keyboard messages */ case OS.WM_KEYDOWN: if (wParam == OS.VK_CONTROL || wParam == OS.VK_SHIFT) break; //FALL THROUGH case OS.WM_CHAR: case OS.WM_IME_CHAR: case OS.WM_KEYUP: case OS.WM_SYSCHAR: case OS.WM_SYSKEYDOWN: case OS.WM_SYSKEYUP: //FALL THROUGH /* Scroll messages */ case OS.WM_HSCROLL: case OS.WM_VSCROLL: //FALL THROUGH /* Resize messages */ case OS.WM_SIZE: if (redraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); if (hwndHeader != 0) OS.InvalidateRect (hwndHeader, null, true); } //FALL THROUGH /* Mouse messages */ case OS.WM_LBUTTONDBLCLK: case OS.WM_LBUTTONDOWN: case OS.WM_LBUTTONUP: case OS.WM_MBUTTONDBLCLK: case OS.WM_MBUTTONDOWN: case OS.WM_MBUTTONUP: case OS.WM_MOUSEHOVER: case OS.WM_MOUSELEAVE: case OS.WM_MOUSEMOVE: case OS.WM_MOUSEWHEEL: case OS.WM_RBUTTONDBLCLK: case OS.WM_RBUTTONDOWN: case OS.WM_RBUTTONUP: case OS.WM_XBUTTONDBLCLK: case OS.WM_XBUTTONDOWN: case OS.WM_XBUTTONUP: //FALL THROUGH /* Other messages */ case OS.WM_SETFONT: case OS.WM_TIMER: { if (findImageControl () != null) { if (hItem != OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0)) { OS.InvalidateRect (handle, null, true); } } updateScrollBar (); break; } case OS.WM_PAINT: painted = true; break; } return code; } void checkBuffered () { super.checkBuffered (); if ((style & SWT.VIRTUAL) != 0) { style |= SWT.DOUBLE_BUFFERED; OS.SendMessage (handle, OS.TVM_SETSCROLLTIME, 0, 0); } if (EXPLORER_THEME) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { int exStyle = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0); if ((exStyle & OS.TVS_EX_DOUBLEBUFFER) != 0) style |= SWT.DOUBLE_BUFFERED; } } } boolean checkData (TreeItem item, boolean redraw) { if ((style & SWT.VIRTUAL) == 0) return true; if (!item.cached) { TreeItem parentItem = item.getParentItem (); return checkData (item, parentItem == null ? indexOf (item) : parentItem.indexOf (item), redraw); } return true; } boolean checkData (TreeItem item, int index, boolean redraw) { if ((style & SWT.VIRTUAL) == 0) return true; if (!item.cached) { item.cached = true; Event event = new Event (); event.item = item; event.index = index; TreeItem oldItem = currentItem; currentItem = item; sendEvent (SWT.SetData, event); //widget could be disposed at this point currentItem = oldItem; if (isDisposed () || item.isDisposed ()) return false; if (redraw) item.redraw (); } return true; } boolean checkHandle (int /*long*/ hwnd) { return hwnd == handle || (hwndParent != 0 && hwnd == hwndParent) || (hwndHeader != 0 && hwnd == hwndHeader); } boolean checkScroll (int /*long*/ hItem) { /* * Feature in Windows. If redraw is turned off using WM_SETREDRAW * and a tree item that is not a child of the first root is selected or * scrolled using TVM_SELECTITEM or TVM_ENSUREVISIBLE, then scrolling * does not occur. The fix is to detect this case, and make sure * that redraw is temporarily enabled. To avoid flashing, DefWindowProc() * is called to disable redrawing. * * NOTE: The code that actually works around the problem is in the * callers of this method. */ if (drawCount == 0) return false; int /*long*/ hRoot = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); int /*long*/ hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem); while (hParent != hRoot && hParent != 0) { hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hParent); } return hParent == 0; } protected void checkSubclass () { if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS); } /** * Clears the item at the given zero-relative index in the receiver. * The text, icon and other attributes of the item are set to the default * value. If the tree was created with the <code>SWT.VIRTUAL</code> style, * these attributes are requested again as needed. * * @param index the index of the item to clear * @param all <code>true</code> if all child items of the indexed item should be * cleared recursively, and <code>false</code> otherwise * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData * * @since 3.2 */ public void clear (int index, boolean all) { checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); if (hItem == 0) error (SWT.ERROR_INVALID_RANGE); hItem = findItem (hItem, index); if (hItem == 0) error (SWT.ERROR_INVALID_RANGE); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; clear (hItem, tvItem); if (all) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); clearAll (hItem, tvItem, all); } } void clear (int /*long*/ hItem, TVITEM tvItem) { tvItem.hItem = hItem; TreeItem item = null; if (OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem) != 0) { item = tvItem.lParam != -1 ? items [(int)/*64*/tvItem.lParam] : null; } if (item != null) { item.clear (); item.redraw (); } } /** * Clears all the items in the receiver. The text, icon and other * attributes of the items are set to their default values. If the * tree was created with the <code>SWT.VIRTUAL</code> style, these * attributes are requested again as needed. * * @param all <code>true</code> if all child items should be cleared * recursively, and <code>false</code> otherwise * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SWT#VIRTUAL * @see SWT#SetData * * @since 3.2 */ public void clearAll (boolean all) { checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); if (hItem == 0) return; TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; clearAll (hItem, tvItem, all); } void clearAll (int /*long*/ hItem, TVITEM tvItem, boolean all) { while (hItem != 0) { clear (hItem, tvItem); int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); if (all) clearAll (hFirstItem, tvItem, all); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } } int /*long*/ CompareFunc (int /*long*/ lParam1, int /*long*/ lParam2, int /*long*/ lParamSort) { TreeItem item1 = items [(int)/*64*/lParam1], item2 = items [(int)/*64*/lParam2]; String text1 = item1.getText ((int)/*64*/lParamSort), text2 = item2.getText ((int)/*64*/lParamSort); return sortDirection == SWT.UP ? text1.compareTo (text2) : text2.compareTo (text1); } public Point computeSize (int wHint, int hHint, boolean changed) { checkWidget (); int width = 0, height = 0; if (hwndHeader != 0) { HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_WIDTH; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { OS.SendMessage (hwndHeader, OS.HDM_GETITEM, i, hdItem); width += hdItem.cxy; } RECT rect = new RECT (); OS.GetWindowRect (hwndHeader, rect); height += rect.bottom - rect.top; } RECT rect = new RECT (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); while (hItem != 0) { if ((style & SWT.VIRTUAL) == 0 && !painted) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_TEXT; tvItem.hItem = hItem; tvItem.pszText = OS.LPSTR_TEXTCALLBACK; ignoreCustomDraw = true; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); ignoreCustomDraw = false; } if (OS.TreeView_GetItemRect (handle, hItem, rect, true)) { width = Math.max (width, rect.right); height += rect.bottom - rect.top; } hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem); } if (width == 0) width = DEFAULT_WIDTH; if (height == 0) height = DEFAULT_HEIGHT; if (wHint != SWT.DEFAULT) width = wHint; if (hHint != SWT.DEFAULT) height = hHint; int border = getBorderWidth (); width += border * 2; height += border * 2; if ((style & SWT.V_SCROLL) != 0) { width += OS.GetSystemMetrics (OS.SM_CXVSCROLL); } if ((style & SWT.H_SCROLL) != 0) { height += OS.GetSystemMetrics (OS.SM_CYHSCROLL); } return new Point (width, height); } void createHandle () { super.createHandle (); state &= ~(CANVAS | THEME_BACKGROUND); /* Use the Explorer theme */ if (EXPLORER_THEME) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { explorerTheme = true; OS.SetWindowTheme (handle, Display.EXPLORER, null); int bits = OS.TVS_EX_DOUBLEBUFFER | OS.TVS_EX_FADEINOUTEXPANDOS | OS.TVS_EX_RICHTOOLTIP; if ((style & SWT.FULL_SELECTION) == 0) bits |= OS.TVS_EX_AUTOHSCROLL; OS.SendMessage (handle, OS.TVM_SETEXTENDEDSTYLE, 0, bits); /* * Bug in Windows. When the tree is using the explorer * theme, it does not use COLOR_WINDOW_TEXT for the * default foreground color. The fix is to explicitly * set the foreground. */ setForegroundPixel (-1); } } /* * Feature in Windows. In version 5.8 of COMCTL32.DLL, * if the font is changed for an item, the bounds for the * item are not updated, causing the text to be clipped. * The fix is to detect the version of COMCTL32.DLL, and * if it is one of the versions with the problem, then * use version 5.00 of the control (a version that does * not have the problem). This is the recommended work * around from the MSDN. */ if (!OS.IsWinCE) { if (OS.COMCTL32_MAJOR < 6) { OS.SendMessage (handle, OS.CCM_SETVERSION, 5, 0); } } /* Set the checkbox image list */ if ((style & SWT.CHECK) != 0) setCheckboxImageList (); /* * Feature in Windows. When the control is created, * it does not use the default system font. A new HFONT * is created and destroyed when the control is destroyed. * This means that a program that queries the font from * this control, uses the font in another control and then * destroys this control will have the font unexpectedly * destroyed in the other control. The fix is to assign * the font ourselves each time the control is created. * The control will not destroy a font that it did not * create. */ int /*long*/ hFont = OS.GetStockObject (OS.SYSTEM_FONT); OS.SendMessage (handle, OS.WM_SETFONT, hFont, 0); } void createHeaderToolTips () { if (OS.IsWinCE) return; if (headerToolTipHandle != 0) return; headerToolTipHandle = OS.CreateWindowEx ( 0, new TCHAR (0, OS.TOOLTIPS_CLASS, true), null, OS.TTS_NOPREFIX, OS.CW_USEDEFAULT, 0, OS.CW_USEDEFAULT, 0, handle, 0, OS.GetModuleHandle (null), null); if (headerToolTipHandle == 0) error (SWT.ERROR_NO_HANDLES); /* * Feature in Windows. Despite the fact that the * tool tip text contains \r\n, the tooltip will * not honour the new line unless TTM_SETMAXTIPWIDTH * is set. The fix is to set TTM_SETMAXTIPWIDTH to * a large value. */ OS.SendMessage (headerToolTipHandle, OS.TTM_SETMAXTIPWIDTH, 0, 0x7FFF); } void createItem (TreeColumn column, int index) { if (hwndHeader == 0) createParent (); int columnCount = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (!(0 <= index && index <= columnCount)) error (SWT.ERROR_INVALID_RANGE); if (columnCount == columns.length) { TreeColumn [] newColumns = new TreeColumn [columns.length + 4]; System.arraycopy (columns, 0, newColumns, 0, columns.length); columns = newColumns; } for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { String [] strings = item.strings; if (strings != null) { String [] temp = new String [columnCount + 1]; System.arraycopy (strings, 0, temp, 0, index); System.arraycopy (strings, index, temp, index + 1, columnCount - index); item.strings = temp; } Image [] images = item.images; if (images != null) { Image [] temp = new Image [columnCount + 1]; System.arraycopy (images, 0, temp, 0, index); System.arraycopy (images, index, temp, index + 1, columnCount - index); item.images = temp; } if (index == 0) { if (columnCount != 0) { if (strings == null) { item.strings = new String [columnCount + 1]; item.strings [1] = item.text; } item.text = ""; if (images == null) { item.images = new Image [columnCount + 1]; item.images [1] = item.image; } item.image = null; } } if (item.cellBackground != null) { int [] cellBackground = item.cellBackground; int [] temp = new int [columnCount + 1]; System.arraycopy (cellBackground, 0, temp, 0, index); System.arraycopy (cellBackground, index, temp, index + 1, columnCount - index); temp [index] = -1; item.cellBackground = temp; } if (item.cellForeground != null) { int [] cellForeground = item.cellForeground; int [] temp = new int [columnCount + 1]; System.arraycopy (cellForeground, 0, temp, 0, index); System.arraycopy (cellForeground, index, temp, index + 1, columnCount - index); temp [index] = -1; item.cellForeground = temp; } if (item.cellFont != null) { Font [] cellFont = item.cellFont; Font [] temp = new Font [columnCount + 1]; System.arraycopy (cellFont, 0, temp, 0, index); System.arraycopy (cellFont, index, temp, index + 1, columnCount- index); item.cellFont = temp; } } } System.arraycopy (columns, index, columns, index + 1, columnCount - index); columns [index] = column; /* * Bug in Windows. For some reason, when HDM_INSERTITEM * is used to insert an item into a header without text, * if is not possible to set the text at a later time. * The fix is to insert the item with an empty string. */ int /*long*/ hHeap = OS.GetProcessHeap (); int /*long*/ pszText = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, TCHAR.sizeof); HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_TEXT | OS.HDI_FORMAT; hdItem.pszText = pszText; if ((column.style & SWT.LEFT) == SWT.LEFT) hdItem.fmt = OS.HDF_LEFT; if ((column.style & SWT.CENTER) == SWT.CENTER) hdItem.fmt = OS.HDF_CENTER; if ((column.style & SWT.RIGHT) == SWT.RIGHT) hdItem.fmt = OS.HDF_RIGHT; OS.SendMessage (hwndHeader, OS.HDM_INSERTITEM, index, hdItem); if (pszText != 0) OS.HeapFree (hHeap, 0, pszText); /* When the first column is created, hide the horizontal scroll bar */ if (columnCount == 0) { scrollWidth = 0; int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits |= OS.TVS_NOHSCROLL; OS.SetWindowLong (handle, OS.GWL_STYLE, bits); /* * Bug in Windows. When TVS_NOHSCROLL is set after items * have been inserted into the tree, Windows shows the * scroll bar. The fix is to check for this case and * explicitly hide the scroll bar explicitly. */ int count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (count != 0) { if (!OS.IsWinCE) OS.ShowScrollBar (handle, OS.SB_HORZ, false); } if (itemToolTipHandle != 0) { OS.SendMessage (itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_AUTOMATIC, -1); } } setScrollWidth (); updateImageList (); updateScrollBar (); /* Redraw to hide the items when the first column is created */ if (columnCount == 0 && OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0) != 0) { OS.InvalidateRect (handle, null, true); } /* Add the tool tip item for the header */ if (headerToolTipHandle != 0) { RECT rect = new RECT (); if (OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, index, rect) != 0) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; lpti.uFlags = OS.TTF_SUBCLASS; lpti.hwnd = hwndHeader; lpti.uId = column.id = display.nextToolTipId++; lpti.left = rect.left; lpti.top = rect.top; lpti.right = rect.right; lpti.bottom = rect.bottom; lpti.lpszText = OS.LPSTR_TEXTCALLBACK; OS.SendMessage (headerToolTipHandle, OS.TTM_ADDTOOL, 0, lpti); } } } void createItem (TreeItem item, int /*long*/ hParent, int /*long*/ hInsertAfter, int /*long*/ hItem) { int id = -1; if (item != null) { id = lastID < items.length ? lastID : 0; while (id < items.length && items [id] != null) id++; if (id == items.length) { /* * Grow the array faster when redraw is off or the * table is not visible. When the table is painted, * the items array is resized to be smaller to reduce * memory usage. */ int length = 0; if (drawCount == 0 && OS.IsWindowVisible (handle)) { length = items.length + 4; } else { shrink = true; length = Math.max (4, items.length * 3 / 2); } TreeItem [] newItems = new TreeItem [length]; System.arraycopy (items, 0, newItems, 0, items.length); items = newItems; } lastID = id + 1; } int /*long*/ hNewItem = 0; int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hParent); boolean fixParent = hFirstItem == 0; if (hItem == 0) { TVINSERTSTRUCT tvInsert = new TVINSERTSTRUCT (); tvInsert.hParent = hParent; tvInsert.hInsertAfter = hInsertAfter; tvInsert.lParam = id; tvInsert.pszText = OS.LPSTR_TEXTCALLBACK; tvInsert.iImage = tvInsert.iSelectedImage = OS.I_IMAGECALLBACK; tvInsert.mask = OS.TVIF_TEXT | OS.TVIF_IMAGE | OS.TVIF_SELECTEDIMAGE | OS.TVIF_HANDLE | OS.TVIF_PARAM; if ((style & SWT.CHECK) != 0) { tvInsert.mask = tvInsert.mask | OS.TVIF_STATE; tvInsert.state = 1 << 12; tvInsert.stateMask = OS.TVIS_STATEIMAGEMASK; } ignoreCustomDraw = true; hNewItem = OS.SendMessage (handle, OS.TVM_INSERTITEM, 0, tvInsert); ignoreCustomDraw = false; if (hNewItem == 0) error (SWT.ERROR_ITEM_NOT_ADDED); /* * This code is intentionally commented. */ // if (hParent != 0) { // int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); // bits |= OS.TVS_LINESATROOT; // OS.SetWindowLong (handle, OS.GWL_STYLE, bits); // } } else { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = hNewItem = hItem; tvItem.lParam = id; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } if (item != null) { item.handle = hNewItem; items [id] = item; } if (hFirstItem == 0) { if (hInsertAfter == OS.TVI_FIRST || hInsertAfter == OS.TVI_LAST) { hFirstIndexOf = hLastIndexOf = hFirstItem = hNewItem; itemCount = lastIndexOf = 0; } } if (hFirstItem == hFirstIndexOf && itemCount != -1) itemCount++; if (hItem == 0) { /* * Bug in Windows. When a child item is added to a parent item * that has no children outside of WM_NOTIFY with control code * TVN_ITEMEXPANDED, the tree widget does not redraw the +/- * indicator. The fix is to detect the case when the first * child is added to a visible parent item and redraw the parent. */ if (fixParent) { if (drawCount == 0 && OS.IsWindowVisible (handle)) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, hParent, rect, false)) { OS.InvalidateRect (handle, rect, true); } } } /* * Bug in Windows. When a new item is added while Windows * is requesting data a tree item using TVN_GETDISPINFO, * outstanding damage for items that are below the new item * is not scrolled. The fix is to explicitly damage the * new area. */ if ((style & SWT.VIRTUAL) != 0) { if (currentItem != null) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, hNewItem, rect, false)) { RECT damageRect = new RECT (); boolean damaged = OS.GetUpdateRect (handle, damageRect, true); if (damaged && damageRect.top < rect.bottom) { if (OS.IsWinCE) { OS.OffsetRect (damageRect, 0, rect.bottom - rect.top); OS.InvalidateRect (handle, damageRect, true); } else { int /*long*/ rgn = OS.CreateRectRgn (0, 0, 0, 0); int result = OS.GetUpdateRgn (handle, rgn, true); if (result != OS.NULLREGION) { OS.OffsetRgn (rgn, 0, rect.bottom - rect.top); OS.InvalidateRgn (handle, rgn, true); } OS.DeleteObject (rgn); } } } } } updateScrollBar (); } } void createItemToolTips () { if (OS.IsWinCE) return; if (itemToolTipHandle != 0) return; int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits |= OS.TVS_NOTOOLTIPS; OS.SetWindowLong (handle, OS.GWL_STYLE, bits); itemToolTipHandle = OS.CreateWindowEx ( OS.WS_EX_TRANSPARENT, new TCHAR (0, OS.TOOLTIPS_CLASS, true), null, OS.TTS_NOPREFIX, OS.CW_USEDEFAULT, 0, OS.CW_USEDEFAULT, 0, handle, 0, OS.GetModuleHandle (null), null); if (itemToolTipHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.SendMessage (itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_INITIAL, 0); TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; lpti.hwnd = handle; lpti.uId = handle; lpti.uFlags = OS.TTF_SUBCLASS | OS.TTF_TRANSPARENT; lpti.lpszText = OS.LPSTR_TEXTCALLBACK; OS.SendMessage (itemToolTipHandle, OS.TTM_ADDTOOL, 0, lpti); } void createParent () { forceResize (); RECT rect = new RECT (); OS.GetWindowRect (handle, rect); OS.MapWindowPoints (0, parent.handle, rect, 2); int oldStyle = OS.GetWindowLong (handle, OS.GWL_STYLE); int newStyle = super.widgetStyle () & ~OS.WS_VISIBLE; if ((oldStyle & OS.WS_DISABLED) != 0) newStyle |= OS.WS_DISABLED; // if ((oldStyle & OS.WS_VISIBLE) != 0) newStyle |= OS.WS_VISIBLE; hwndParent = OS.CreateWindowEx ( super.widgetExtStyle (), super.windowClass (), null, newStyle, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, parent.handle, 0, OS.GetModuleHandle (null), null); if (hwndParent == 0) error (SWT.ERROR_NO_HANDLES); OS.SetWindowLongPtr (hwndParent, OS.GWLP_ID, hwndParent); int bits = 0; if (OS.WIN32_VERSION >= OS.VERSION (4, 10)) { bits |= OS.WS_EX_NOINHERITLAYOUT; if ((style & SWT.RIGHT_TO_LEFT) != 0) bits |= OS.WS_EX_LAYOUTRTL; } hwndHeader = OS.CreateWindowEx ( bits, HeaderClass, null, OS.HDS_BUTTONS | OS.HDS_FULLDRAG | OS.HDS_DRAGDROP | OS.HDS_HIDDEN | OS.WS_CHILD | OS.WS_CLIPSIBLINGS, 0, 0, 0, 0, hwndParent, 0, OS.GetModuleHandle (null), null); if (hwndHeader == 0) error (SWT.ERROR_NO_HANDLES); OS.SetWindowLongPtr (hwndHeader, OS.GWLP_ID, hwndHeader); if (OS.IsDBLocale) { int /*long*/ hIMC = OS.ImmGetContext (handle); OS.ImmAssociateContext (hwndParent, hIMC); OS.ImmAssociateContext (hwndHeader, hIMC); OS.ImmReleaseContext (handle, hIMC); } //This code is intentionally commented // if (!OS.IsPPC) { // if ((style & SWT.BORDER) != 0) { // int oldExStyle = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); // oldExStyle &= ~OS.WS_EX_CLIENTEDGE; // OS.SetWindowLong (handle, OS.GWL_EXSTYLE, oldExStyle); // } // } int /*long*/ hFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); if (hFont != 0) OS.SendMessage (hwndHeader, OS.WM_SETFONT, hFont, 0); int /*long*/ hwndInsertAfter = OS.GetWindow (handle, OS.GW_HWNDPREV); int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; SetWindowPos (hwndParent, hwndInsertAfter, 0, 0, 0, 0, flags); SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_RANGE | OS.SIF_PAGE; OS.GetScrollInfo (hwndParent, OS.SB_HORZ, info); info.nPage = info.nMax + 1; OS.SetScrollInfo (hwndParent, OS.SB_HORZ, info, true); OS.GetScrollInfo (hwndParent, OS.SB_VERT, info); info.nPage = info.nMax + 1; OS.SetScrollInfo (hwndParent, OS.SB_VERT, info, true); customDraw = true; deregister (); if ((oldStyle & OS.WS_VISIBLE) != 0) { OS.ShowWindow (hwndParent, OS.SW_SHOW); } int /*long*/ hwndFocus = OS.GetFocus (); if (hwndFocus == handle) OS.SetFocus (hwndParent); OS.SetParent (handle, hwndParent); if (hwndFocus == handle) OS.SetFocus (handle); register (); subclass (); createItemToolTips (); } void createWidget () { super.createWidget (); items = new TreeItem [4]; columns = new TreeColumn [4]; itemCount = -1; } int defaultBackground () { return OS.GetSysColor (OS.COLOR_WINDOW); } void deregister () { super.deregister (); if (hwndParent != 0) display.removeControl (hwndParent); if (hwndHeader != 0) display.removeControl (hwndHeader); } void deselect (int /*long*/ hItem, TVITEM tvItem, int /*long*/ hIgnoreItem) { while (hItem != 0) { if (hItem != hIgnoreItem) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); deselect (hFirstItem, tvItem, hIgnoreItem); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } } /** * Deselects an item in the receiver. If the item was already * deselected, it remains deselected. * * @param item the item to be deselected * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.4 */ public void deselect (TreeItem item) { checkWidget (); if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } /** * Deselects all selected items in the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void deselectAll () { checkWidget (); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; if ((style & SWT.SINGLE) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } else { int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); deselect (hItem, tvItem, 0); } else { for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); } } void destroyItem (TreeColumn column) { if (hwndHeader == 0) error (SWT.ERROR_ITEM_NOT_REMOVED); int columnCount = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); int index = 0; while (index < columnCount) { if (columns [index] == column) break; index++; } int [] oldOrder = new int [columnCount]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, columnCount, oldOrder); int orderIndex = 0; while (orderIndex < columnCount) { if (oldOrder [orderIndex] == index) break; orderIndex++; } RECT headerRect = new RECT (); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, index, headerRect); if (OS.SendMessage (hwndHeader, OS.HDM_DELETEITEM, index, 0) == 0) { error (SWT.ERROR_ITEM_NOT_REMOVED); } System.arraycopy (columns, index + 1, columns, index, --columnCount - index); columns [columnCount] = null; for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { if (columnCount == 0) { item.strings = null; item.images = null; item.cellBackground = null; item.cellForeground = null; item.cellFont = null; } else { if (item.strings != null) { String [] strings = item.strings; if (index == 0) { item.text = strings [1] != null ? strings [1] : ""; } String [] temp = new String [columnCount]; System.arraycopy (strings, 0, temp, 0, index); System.arraycopy (strings, index + 1, temp, index, columnCount - index); item.strings = temp; } else { if (index == 0) item.text = ""; } if (item.images != null) { Image [] images = item.images; if (index == 0) item.image = images [1]; Image [] temp = new Image [columnCount]; System.arraycopy (images, 0, temp, 0, index); System.arraycopy (images, index + 1, temp, index, columnCount - index); item.images = temp; } else { if (index == 0) item.image = null; } if (item.cellBackground != null) { int [] cellBackground = item.cellBackground; int [] temp = new int [columnCount]; System.arraycopy (cellBackground, 0, temp, 0, index); System.arraycopy (cellBackground, index + 1, temp, index, columnCount - index); item.cellBackground = temp; } if (item.cellForeground != null) { int [] cellForeground = item.cellForeground; int [] temp = new int [columnCount]; System.arraycopy (cellForeground, 0, temp, 0, index); System.arraycopy (cellForeground, index + 1, temp, index, columnCount - index); item.cellForeground = temp; } if (item.cellFont != null) { Font [] cellFont = item.cellFont; Font [] temp = new Font [columnCount]; System.arraycopy (cellFont, 0, temp, 0, index); System.arraycopy (cellFont, index + 1, temp, index, columnCount - index); item.cellFont = temp; } } } } /* * When the last column is deleted, show the horizontal * scroll bar. Otherwise, left align the first column * and redraw the columns to the right. */ if (columnCount == 0) { scrollWidth = 0; if (!hooks (SWT.MeasureItem)) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits &= ~OS.TVS_NOHSCROLL; OS.SetWindowLong (handle, OS.GWL_STYLE, bits); OS.InvalidateRect (handle, null, true); } if (itemToolTipHandle != 0) { OS.SendMessage (itemToolTipHandle, OS.TTM_SETDELAYTIME, OS.TTDT_INITIAL, 0); } } else { if (index == 0) { columns [0].style &= ~(SWT.LEFT | SWT.RIGHT | SWT.CENTER); columns [0].style |= SWT.LEFT; HDITEM hdItem = new HDITEM (); hdItem.mask = OS.HDI_FORMAT | OS.HDI_IMAGE; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, index, hdItem); hdItem.fmt &= ~OS.HDF_JUSTIFYMASK; hdItem.fmt |= OS.HDF_LEFT; OS.SendMessage (hwndHeader, OS.HDM_SETITEM, index, hdItem); } RECT rect = new RECT (); OS.GetClientRect (handle, rect); rect.left = headerRect.left; OS.InvalidateRect (handle, rect, true); } setScrollWidth (); updateImageList (); updateScrollBar (); if (columnCount != 0) { int [] newOrder = new int [columnCount]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, columnCount, newOrder); TreeColumn [] newColumns = new TreeColumn [columnCount - orderIndex]; for (int i=orderIndex; i<newOrder.length; i++) { newColumns [i - orderIndex] = columns [newOrder [i]]; newColumns [i - orderIndex].updateToolTip (newOrder [i]); } for (int i=0; i<newColumns.length; i++) { if (!newColumns [i].isDisposed ()) { newColumns [i].sendEvent (SWT.Move); } } } /* Remove the tool tip item for the header */ if (headerToolTipHandle != 0) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; lpti.uId = column.id; lpti.hwnd = hwndHeader; OS.SendMessage (headerToolTipHandle, OS.TTM_DELTOOL, 0, lpti); } } void destroyItem (TreeItem item, int /*long*/ hItem) { hFirstIndexOf = hLastIndexOf = 0; itemCount = -1; /* * Feature in Windows. When an item is removed that is not * visible in the tree because it belongs to a collapsed branch, * Windows redraws the tree causing a flash for each item that * is removed. The fix is to detect whether the item is visible, * force the widget to be fully painted, turn off redraw, remove * the item and validate the damage caused by the removing of * the item. * * NOTE: This fix is not necessary when double buffering and * can cause problems for virtual trees due to the call to * UpdateWindow() that flushes outstanding WM_PAINT events, * allowing application code to add or remove items during * this remove operation. */ int /*long*/ hParent = 0; boolean fixRedraw = false; if ((style & SWT.DOUBLE_BUFFERED) == 0) { if (drawCount == 0 && OS.IsWindowVisible (handle)) { RECT rect = new RECT (); fixRedraw = !OS.TreeView_GetItemRect (handle, hItem, rect, false); } } if (fixRedraw) { hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem); OS.UpdateWindow (handle); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); /* * This code is intentionally commented. */ // OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } if ((style & SWT.MULTI) != 0) { ignoreDeselect = ignoreSelect = lockSelection = true; } /* * Feature in Windows. When an item is deleted and a tool tip * is showing, Window requests the new text for the new item * that is under the cursor right away. This means that when * multiple items are deleted, the tool tip flashes, showing * each new item in the tool tip as it is scrolled into view. * The fix is to hide tool tips when any item is deleted. * * NOTE: This only happens on Vista. */ if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { int /*long*/ hwndToolTip = OS.SendMessage (handle, OS.TVM_GETTOOLTIPS, 0, 0); if (hwndToolTip != 0) OS.SendMessage (hwndToolTip, OS.TTM_POP, 0 ,0); } shrink = ignoreShrink = true; OS.SendMessage (handle, OS.TVM_DELETEITEM, 0, hItem); ignoreShrink = false; if ((style & SWT.MULTI) != 0) { ignoreDeselect = ignoreSelect = lockSelection = false; } if (fixRedraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.ValidateRect (handle, null); /* * If the item that was deleted was the last child of a tree item that * is visible, redraw the parent item to force the +/- to be updated. */ if (OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hParent) == 0) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, hParent, rect, false)) { OS.InvalidateRect (handle, rect, true); } } } int count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (count == 0) { if (imageList != null) { OS.SendMessage (handle, OS.TVM_SETIMAGELIST, 0, 0); display.releaseImageList (imageList); } imageList = null; if (hwndParent == 0 && !linesVisible) { if (!hooks (SWT.MeasureItem) && !hooks (SWT.EraseItem) && !hooks (SWT.PaintItem)) { customDraw = false; } } items = new TreeItem [4]; scrollWidth = 0; setScrollWidth (); } updateScrollBar (); } void enableDrag (boolean enabled) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if (enabled && hooks (SWT.DragDetect)) { bits &= ~OS.TVS_DISABLEDRAGDROP; } else { bits |= OS.TVS_DISABLEDRAGDROP; } OS.SetWindowLong (handle, OS.GWL_STYLE, bits); } void enableWidget (boolean enabled) { super.enableWidget (enabled); /* * Feature in Windows. When a tree is given a background color * using TVM_SETBKCOLOR and the tree is disabled, Windows draws * the tree using the background color rather than the disabled * colors. This is different from the table which draws grayed. * The fix is to set the default background color while the tree * is disabled and restore it when enabled. */ Control control = findBackgroundControl (); /* * Bug in Windows. On Vista only, Windows does not draw using * the background color when the tree is disabled. The fix is * to set the default color, even when the color has not been * changed, causing Windows to draw correctly. */ if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { if (control == null) control = this; } if (control != null) { if (control.backgroundImage == null) { _setBackgroundPixel (enabled ? control.getBackgroundPixel () : -1); } } if (hwndParent != 0) OS.EnableWindow (hwndParent, enabled); /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of the sort column color. The fix * is to clear TVS_FULLROWSELECT when a their is * as sort column. */ updateFullSelection (); } boolean findCell (int x, int y, TreeItem [] item, int [] index, RECT [] cellRect, RECT [] itemRect) { boolean found = false; TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = x; lpht.y = y; OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem != 0) { item [0] = _getItem (lpht.hItem); POINT pt = new POINT (); pt.x = x; pt.y = y; int /*long*/ hDC = OS.GetDC (handle); int /*long*/ oldFont = 0, newFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); if (newFont != 0) oldFont = OS.SelectObject (hDC, newFont); RECT rect = new RECT (); if (hwndParent != 0) { OS.GetClientRect (hwndParent, rect); OS.MapWindowPoints (hwndParent, handle, rect, 2); } else { OS.GetClientRect (handle, rect); } int count = 1; if (hwndHeader != 0) { count = Math.max (1, (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0)); } int [] order = new int [count]; if (hwndHeader != 0) OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, order); index [0] = 0; boolean quit = false; while (index [0] < count && !quit) { int /*long*/ hFont = item [0].fontHandle (order [index [0]]); if (hFont != -1) hFont = OS.SelectObject (hDC, hFont); cellRect [0] = item [0].getBounds (order [index [0]], true, false, true, false, true, hDC); if (cellRect [0].left > rect.right) { quit = true; } else { cellRect [0].right = Math.min (cellRect [0].right, rect.right); if (OS.PtInRect (cellRect [0], pt)) { if (hooks (SWT.MeasureItem) || hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) { Event event = sendMeasureItemEvent (item [0], order [index [0]], hDC); if (isDisposed () || item [0].isDisposed ()) break; itemRect [0] = new RECT (); itemRect [0].left = event.x; itemRect [0].right = event.x + event.width; itemRect [0].top = event.y; itemRect [0].bottom = event.y + event.height; } else { itemRect [0] = item [0].getBounds (order [index [0]], true, false, false, false, false, hDC); } if (itemRect [0].right > cellRect [0].right) found = true; quit = true; } } if (hFont != -1) OS.SelectObject (hDC, hFont); if (!found) index [0]++; } if (newFont != 0) OS.SelectObject (hDC, oldFont); OS.ReleaseDC (handle, hDC); } return found; } int findIndex (int /*long*/ hFirstItem, int /*long*/ hItem) { if (hFirstItem == 0) return -1; if (hFirstItem == hFirstIndexOf) { if (hFirstIndexOf == hItem) { hLastIndexOf = hFirstIndexOf; return lastIndexOf = 0; } if (hLastIndexOf == hItem) return lastIndexOf; int /*long*/ hPrevItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf); if (hPrevItem == hItem) { hLastIndexOf = hPrevItem; return --lastIndexOf; } int /*long*/ hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf); if (hNextItem == hItem) { hLastIndexOf = hNextItem; return ++lastIndexOf; } int previousIndex = lastIndexOf - 1; while (hPrevItem != 0 && hPrevItem != hItem) { hPrevItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hPrevItem); --previousIndex; } if (hPrevItem == hItem) { hLastIndexOf = hPrevItem; return lastIndexOf = previousIndex; } int nextIndex = lastIndexOf + 1; while (hNextItem != 0 && hNextItem != hItem) { hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem); nextIndex++; } if (hNextItem == hItem) { hLastIndexOf = hNextItem; return lastIndexOf = nextIndex; } return -1; } int index = 0; int /*long*/ hNextItem = hFirstItem; while (hNextItem != 0 && hNextItem != hItem) { hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem); index++; } if (hNextItem == hItem) { itemCount = -1; hFirstIndexOf = hFirstItem; hLastIndexOf = hNextItem; return lastIndexOf = index; } return -1; } Widget findItem (int /*long*/ hItem) { return _getItem (hItem); } int /*long*/ findItem (int /*long*/ hFirstItem, int index) { if (hFirstItem == 0) return 0; if (hFirstItem == hFirstIndexOf) { if (index == 0) { lastIndexOf = 0; return hLastIndexOf = hFirstIndexOf; } if (lastIndexOf == index) return hLastIndexOf; if (lastIndexOf - 1 == index) { --lastIndexOf; return hLastIndexOf = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf); } if (lastIndexOf + 1 == index) { lastIndexOf++; return hLastIndexOf = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf); } if (index < lastIndexOf) { int previousIndex = lastIndexOf - 1; int /*long*/ hPrevItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hLastIndexOf); while (hPrevItem != 0 && index < previousIndex) { hPrevItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUS, hPrevItem); --previousIndex; } if (index == previousIndex) { lastIndexOf = previousIndex; return hLastIndexOf = hPrevItem; } } else { int nextIndex = lastIndexOf + 1; int /*long*/ hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hLastIndexOf); while (hNextItem != 0 && nextIndex < index) { hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem); nextIndex++; } if (index == nextIndex) { lastIndexOf = nextIndex; return hLastIndexOf = hNextItem; } } return 0; } int nextIndex = 0; int /*long*/ hNextItem = hFirstItem; while (hNextItem != 0 && nextIndex < index) { hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hNextItem); nextIndex++; } if (index == nextIndex) { itemCount = -1; lastIndexOf = nextIndex; hFirstIndexOf = hFirstItem; return hLastIndexOf = hNextItem; } return 0; } TreeItem getFocusItem () { // checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); return hItem != 0 ? _getItem (hItem) : null; } /** * Returns the width in pixels of a grid line. * * @return the width of a grid line in pixels * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public int getGridLineWidth () { checkWidget (); return GRID_WIDTH; } /** * Returns the height of the receiver's header * * @return the height of the header or zero if the header is not visible * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public int getHeaderHeight () { checkWidget (); if (hwndHeader == 0) return 0; RECT rect = new RECT (); OS.GetWindowRect (hwndHeader, rect); return rect.bottom - rect.top; } /** * Returns <code>true</code> if the receiver's header is visible, * and <code>false</code> otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, this method * may still indicate that it is considered visible even though * it may not actually be showing. * </p> * * @return the receiver's header's visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public boolean getHeaderVisible () { checkWidget (); if (hwndHeader == 0) return false; int bits = OS.GetWindowLong (hwndHeader, OS.GWL_STYLE); return (bits & OS.WS_VISIBLE) != 0; } Point getImageSize () { if (imageList != null) return imageList.getImageSize (); return new Point (0, getItemHeight ()); } int /*long*/ getBottomItem () { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); if (hItem == 0) return 0; int index = 0, count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETVISIBLECOUNT, 0, 0); while (index < count) { int /*long*/ hNextItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem); if (hNextItem == 0) return hItem; hItem = hNextItem; index++; } return hItem; } /** * Returns the column at the given, zero-relative index in the * receiver. Throws an exception if the index is out of range. * Columns are returned in the order that they were created. * If no <code>TreeColumn</code>s were created by the programmer, * this method will throw <code>ERROR_INVALID_RANGE</code> despite * the fact that a single column of data may be visible in the tree. * This occurs when the programmer uses the tree like a list, adding * items but never creating a column. * * @param index the index of the column to return * @return the column at the given index * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#getColumnOrder() * @see Tree#setColumnOrder(int[]) * @see TreeColumn#getMoveable() * @see TreeColumn#setMoveable(boolean) * @see SWT#Move * * @since 3.1 */ public TreeColumn getColumn (int index) { checkWidget (); if (hwndHeader == 0) error (SWT.ERROR_INVALID_RANGE); int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (!(0 <= index && index < count)) error (SWT.ERROR_INVALID_RANGE); return columns [index]; } /** * Returns the number of columns contained in the receiver. * If no <code>TreeColumn</code>s were created by the programmer, * this value is zero, despite the fact that visually, one column * of items may be visible. This occurs when the programmer uses * the tree like a list, adding items but never creating a column. * * @return the number of columns * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public int getColumnCount () { checkWidget (); if (hwndHeader == 0) return 0; return (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); } /** * Returns an array of zero-relative integers that map * the creation order of the receiver's items to the * order in which they are currently being displayed. * <p> * Specifically, the indices of the returned array represent * the current visual order of the items, and the contents * of the array represent the creation order of the items. * </p><p> * Note: This is not the actual structure used by the receiver * to maintain its list of items, so modifying the array will * not affect the receiver. * </p> * * @return the current visual order of the receiver's items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#setColumnOrder(int[]) * @see TreeColumn#getMoveable() * @see TreeColumn#setMoveable(boolean) * @see SWT#Move * * @since 3.2 */ public int[] getColumnOrder () { checkWidget (); if (hwndHeader == 0) return new int [0]; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); int [] order = new int [count]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, order); return order; } /** * Returns an array of <code>TreeColumn</code>s which are the * columns in the receiver. Columns are returned in the order * that they were created. If no <code>TreeColumn</code>s were * created by the programmer, the array is empty, despite the fact * that visually, one column of items may be visible. This occurs * when the programmer uses the tree like a list, adding items but * never creating a column. * <p> * Note: This is not the actual structure used by the receiver * to maintain its list of items, so modifying the array will * not affect the receiver. * </p> * * @return the items in the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#getColumnOrder() * @see Tree#setColumnOrder(int[]) * @see TreeColumn#getMoveable() * @see TreeColumn#setMoveable(boolean) * @see SWT#Move * * @since 3.1 */ public TreeColumn [] getColumns () { checkWidget (); if (hwndHeader == 0) return new TreeColumn [0]; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); TreeColumn [] result = new TreeColumn [count]; System.arraycopy (columns, 0, result, 0, count); return result; } /** * Returns the item at the given, zero-relative index in the * receiver. Throws an exception if the index is out of range. * * @param index the index of the item to return * @return the item at the given index * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public TreeItem getItem (int index) { checkWidget (); if (index < 0) error (SWT.ERROR_INVALID_RANGE); int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); if (hFirstItem == 0) error (SWT.ERROR_INVALID_RANGE); int /*long*/ hItem = findItem (hFirstItem, index); if (hItem == 0) error (SWT.ERROR_INVALID_RANGE); return _getItem (hItem); } TreeItem getItem (NMTVCUSTOMDRAW nmcd) { /* * Bug in Windows. If the lParam field of TVITEM * is changed during custom draw using TVM_SETITEM, * the lItemlParam field of the NMTVCUSTOMDRAW struct * is not updated until the next custom draw. The * fix is to query the field from the item instead * of using the struct. */ int id = (int)/*64*/nmcd.lItemlParam; if ((style & SWT.VIRTUAL) != 0) { if (id == -1) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = nmcd.dwItemSpec; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); id = (int)/*64*/tvItem.lParam; } } return _getItem (nmcd.dwItemSpec, id); } /** * Returns the item at the given point in the receiver * or null if no such item exists. The point is in the * coordinate system of the receiver. * <p> * The item that is returned represents an item that could be selected by the user. * For example, if selection only occurs in items in the first column, then null is * returned if the point is outside of the item. * Note that the SWT.FULL_SELECTION style hint, which specifies the selection policy, * determines the extent of the selection. * </p> * * @param point the point used to locate the item * @return the item at the given point, or null if the point is not in a selectable item * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the point is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public TreeItem getItem (Point point) { checkWidget (); if (point == null) error (SWT.ERROR_NULL_ARGUMENT); TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = point.x; lpht.y = point.y; OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem != 0) { if ((style & SWT.FULL_SELECTION) != 0 || (lpht.flags & OS.TVHT_ONITEM) != 0) { return _getItem (lpht.hItem); } } return null; } /** * Returns the number of items contained in the receiver * that are direct item children of the receiver. The * number that is returned is the number of roots in the * tree. * * @return the number of items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getItemCount () { checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); if (hItem == 0) return 0; return getItemCount (hItem); } int getItemCount (int /*long*/ hItem) { int count = 0; int /*long*/ hFirstItem = hItem; if (hItem == hFirstIndexOf) { if (itemCount != -1) return itemCount; hFirstItem = hLastIndexOf; count = lastIndexOf; } while (hFirstItem != 0) { hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hFirstItem); count++; } if (hItem == hFirstIndexOf) itemCount = count; return count; } /** * Returns the height of the area which would be used to * display <em>one</em> of the items in the tree. * * @return the height of one item * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getItemHeight () { checkWidget (); return (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMHEIGHT, 0, 0); } /** * Returns a (possibly empty) array of items contained in the * receiver that are direct item children of the receiver. These * are the roots of the tree. * <p> * Note: This is not the actual structure used by the receiver * to maintain its list of items, so modifying the array will * not affect the receiver. * </p> * * @return the items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public TreeItem [] getItems () { checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); if (hItem == 0) return new TreeItem [0]; return getItems (hItem); } TreeItem [] getItems (int /*long*/ hTreeItem) { int count = 0; int /*long*/ hItem = hTreeItem; while (hItem != 0) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); count++; } int index = 0; TreeItem [] result = new TreeItem [count]; TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = hTreeItem; /* * Feature in Windows. In some cases an expand or collapse message * can occur from within TVM_DELETEITEM. When this happens, the item * being destroyed has been removed from the list of items but has not * been deleted from the tree. The fix is to check for null items and * remove them from the list. */ while (tvItem.hItem != 0) { OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); TreeItem item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); if (item != null) result [index++] = item; tvItem.hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, tvItem.hItem); } if (index != count) { TreeItem [] newResult = new TreeItem [index]; System.arraycopy (result, 0, newResult, 0, index); result = newResult; } return result; } /** * Returns <code>true</code> if the receiver's lines are visible, * and <code>false</code> otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, this method * may still indicate that it is considered visible even though * it may not actually be showing. * </p> * * @return the visibility state of the lines * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public boolean getLinesVisible () { checkWidget (); return linesVisible; } int /*long*/ getNextSelection (int /*long*/ hItem, TVITEM tvItem) { while (hItem != 0) { int state = 0; if (OS.IsWinCE) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) return hItem; int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); int /*long*/ hSelected = getNextSelection (hFirstItem, tvItem); if (hSelected != 0) return hSelected; hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } return 0; } /** * Returns the receiver's parent item, which must be a * <code>TreeItem</code> or null when the receiver is a * root. * * @return the receiver's parent item * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public TreeItem getParentItem () { checkWidget (); return null; } int getSelection (int /*long*/ hItem, TVITEM tvItem, TreeItem [] selection, int index, int count, boolean bigSelection, boolean all) { while (hItem != 0) { if (OS.IsWinCE || bigSelection) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) != 0) { if (selection != null && index < selection.length) { selection [index] = _getItem (hItem, (int)/*64*/tvItem.lParam); } index++; } } else { int state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); if ((state & OS.TVIS_SELECTED) != 0) { if (tvItem != null && selection != null && index < selection.length) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); selection [index] = _getItem (hItem, (int)/*64*/tvItem.lParam); } index++; } } if (index == count) break; if (all) { int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); if ((index = getSelection (hFirstItem, tvItem, selection, index, count, bigSelection, all)) == count) { break; } hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } else { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem); } } return index; } /** * Returns an array of <code>TreeItem</code>s that are currently * selected in the receiver. The order of the items is unspecified. * An empty array indicates that no items are selected. * <p> * Note: This is not the actual structure used by the receiver * to maintain its selection, so modifying the array will * not affect the receiver. * </p> * @return an array representing the selection * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public TreeItem [] getSelection () { checkWidget (); if ((style & SWT.SINGLE) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem == 0) return new TreeItem [0]; TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE; tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) == 0) return new TreeItem [0]; return new TreeItem [] {_getItem (tvItem.hItem, (int)/*64*/tvItem.lParam)}; } int count = 0; TreeItem [] guess = new TreeItem [(style & SWT.VIRTUAL) != 0 ? 8 : 1]; int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE; int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); count = getSelection (hItem, tvItem, guess, 0, -1, false, true); } else { TVITEM tvItem = null; if (OS.IsWinCE) { tvItem = new TVITEM (); tvItem.mask = OS.TVIF_STATE; } for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { int /*long*/ hItem = item.handle; int state = 0; if (OS.IsWinCE) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) { if (count < guess.length) guess [count] = item; count++; } } } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); if (count == 0) return new TreeItem [0]; if (count == guess.length) return guess; TreeItem [] result = new TreeItem [count]; if (count < guess.length) { System.arraycopy (guess, 0, result, 0, count); return result; } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE; int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); int itemCount = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); boolean bigSelection = result.length > itemCount / 2; if (count != getSelection (hItem, tvItem, result, 0, count, bigSelection, false)) { getSelection (hItem, tvItem, result, 0, count, bigSelection, true); } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); return result; } /** * Returns the number of selected items contained in the receiver. * * @return the number of selected items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public int getSelectionCount () { checkWidget (); if ((style & SWT.SINGLE) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem == 0) return 0; int state = 0; if (OS.IsWinCE) { TVITEM tvItem = new TVITEM (); tvItem.hItem = hItem; tvItem.mask = OS.TVIF_STATE; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } return (state & OS.TVIS_SELECTED) == 0 ? 0 : 1; } int count = 0; int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); TVITEM tvItem = null; if (OS.IsWinCE) { tvItem = new TVITEM (); tvItem.mask = OS.TVIF_STATE; } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); count = getSelection (hItem, tvItem, null, 0, -1, false, true); } else { for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { int /*long*/ hItem = item.handle; int state = 0; if (OS.IsWinCE) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) count++; } } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); return count; } /** * Returns the column which shows the sort indicator for * the receiver. The value may be null if no column shows * the sort indicator. * * @return the sort indicator * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setSortColumn(TreeColumn) * * @since 3.2 */ public TreeColumn getSortColumn () { checkWidget (); return sortColumn; } int getSortColumnPixel () { int pixel = OS.IsWindowEnabled (handle) ? getBackgroundPixel () : OS.GetSysColor (OS.COLOR_3DFACE); int red = pixel & 0xFF; int green = (pixel & 0xFF00) >> 8; int blue = (pixel & 0xFF0000) >> 16; if (red > 240 && green > 240 && blue > 240) { red -= 8; green -= 8; blue -= 8; } else { red = Math.min (0xFF, (red / 10) + red); green = Math.min (0xFF, (green / 10) + green); blue = Math.min (0xFF, (blue / 10) + blue); } return (red & 0xFF) | ((green & 0xFF) << 8) | ((blue & 0xFF) << 16); } /** * Returns the direction of the sort indicator for the receiver. * The value will be one of <code>UP</code>, <code>DOWN</code> * or <code>NONE</code>. * * @return the sort direction * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setSortDirection(int) * * @since 3.2 */ public int getSortDirection () { checkWidget (); return sortDirection; } /** * Returns the item which is currently at the top of the receiver. * This item can change when items are expanded, collapsed, scrolled * or new items are added or removed. * * @return the item at the top of the receiver * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 2.1 */ public TreeItem getTopItem () { checkWidget (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); return hItem != 0 ? _getItem (hItem) : null; } int imageIndex (Image image, int index) { if (image == null) return OS.I_IMAGENONE; if (imageList == null) { Rectangle bounds = image.getBounds (); imageList = display.getImageList (style & SWT.RIGHT_TO_LEFT, bounds.width, bounds.height); } int imageIndex = imageList.indexOf (image); if (imageIndex == -1) imageIndex = imageList.add (image); if (hwndHeader == 0 || OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0) == index) { int /*long*/ hImageList = imageList.getHandle (); int /*long*/ hOldImageList = OS.SendMessage (handle, OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0); if (hOldImageList != hImageList) { OS.SendMessage (handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, hImageList); updateScrollBar (); } } return imageIndex; } int imageIndexHeader (Image image) { if (image == null) return OS.I_IMAGENONE; if (headerImageList == null) { Rectangle bounds = image.getBounds (); headerImageList = display.getImageList (style & SWT.RIGHT_TO_LEFT, bounds.width, bounds.height); int index = headerImageList.indexOf (image); if (index == -1) index = headerImageList.add (image); int /*long*/ hImageList = headerImageList.getHandle (); if (hwndHeader != 0) { OS.SendMessage (hwndHeader, OS.HDM_SETIMAGELIST, 0, hImageList); } updateScrollBar (); return index; } int index = headerImageList.indexOf (image); if (index != -1) return index; return headerImageList.add (image); } /** * Searches the receiver's list starting at the first column * (index 0) until a column is found that is equal to the * argument, and returns the index of that column. If no column * is found, returns -1. * * @param column the search column * @return the index of the column * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the column is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public int indexOf (TreeColumn column) { checkWidget (); if (column == null) error (SWT.ERROR_NULL_ARGUMENT); if (column.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); if (hwndHeader == 0) return -1; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { if (columns [i] == column) return i; } return -1; } /** * Searches the receiver's list starting at the first item * (index 0) until an item is found that is equal to the * argument, and returns the index of that item. If no item * is found, returns -1. * * @param item the search item * @return the index of the item * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public int indexOf (TreeItem item) { checkWidget (); if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); return hItem == 0 ? -1 : findIndex (hItem, item.handle); } boolean isItemSelected (NMTVCUSTOMDRAW nmcd) { boolean selected = false; if (OS.IsWindowEnabled (handle)) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.hItem = nmcd.dwItemSpec; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & (OS.TVIS_SELECTED | OS.TVIS_DROPHILITED)) != 0) { selected = true; /* * Feature in Windows. When the mouse is pressed and the * selection is first drawn for a tree, the previously * selected item is redrawn but the the TVIS_SELECTED bits * are not cleared. When the user moves the mouse slightly * and a drag and drop operation is not started, the item is * drawn again and this time with TVIS_SELECTED is cleared. * This means that an item that contains colored cells will * not draw with the correct background until the mouse is * moved. The fix is to test for the selection colors and * guess that the item is not selected. * * NOTE: This code does not work when the foreground and * background of the tree are set to the selection colors * but this does not happen in a regular application. */ if (handle == OS.GetFocus ()) { if (OS.GetTextColor (nmcd.hdc) != OS.GetSysColor (OS.COLOR_HIGHLIGHTTEXT)) { selected = false; } else { if (OS.GetBkColor (nmcd.hdc) != OS.GetSysColor (OS.COLOR_HIGHLIGHT)) { selected = false; } } } } else { if (nmcd.dwDrawStage == OS.CDDS_ITEMPOSTPAINT) { /* * Feature in Windows. When the mouse is pressed and the * selection is first drawn for a tree, the item is drawn * selected, but the TVIS_SELECTED bits for the item are * not set. When the user moves the mouse slightly and * a drag and drop operation is not started, the item is * drawn again and this time TVIS_SELECTED is set. This * means that an item that is in a tree that has the style * TVS_FULLROWSELECT and that also contains colored cells * will not draw the entire row selected until the user * moves the mouse. The fix is to test for the selection * colors and guess that the item is selected. * * NOTE: This code does not work when the foreground and * background of the tree are set to the selection colors * but this does not happen in a regular application. */ if (OS.GetTextColor (nmcd.hdc) == OS.GetSysColor (OS.COLOR_HIGHLIGHTTEXT)) { if (OS.GetBkColor (nmcd.hdc) == OS.GetSysColor (OS.COLOR_HIGHLIGHT)) { selected = true; } } } } } return selected; } void redrawSelection () { if ((style & SWT.SINGLE) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, hItem, rect, false)) { OS.InvalidateRect (handle, rect, true); } } } else { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); if (hItem != 0) { TVITEM tvItem = null; if (OS.IsWinCE) { tvItem = new TVITEM (); tvItem.mask = OS.TVIF_STATE; } RECT rect = new RECT (); int index = 0, count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETVISIBLECOUNT, 0, 0); while (index < count && hItem != 0) { int state = 0; if (OS.IsWinCE) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) { if (OS.TreeView_GetItemRect (handle, hItem, rect, false)) { OS.InvalidateRect (handle, rect, true); } } hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem); index++; } } } } void register () { super.register (); if (hwndParent != 0) display.addControl (hwndParent, this); if (hwndHeader != 0) display.addControl (hwndHeader, this); } void releaseItem (int /*long*/ hItem, TVITEM tvItem, boolean release) { if (hItem == hAnchor) hAnchor = 0; if (hItem == hInsert) hInsert = 0; tvItem.hItem = hItem; if (OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem) != 0) { if (tvItem.lParam != -1) { if (tvItem.lParam < lastID) lastID = (int)/*64*/tvItem.lParam; if (release) { TreeItem item = items [(int)/*64*/tvItem.lParam]; if (item != null) item.release (false); } items [(int)/*64*/tvItem.lParam] = null; } } } void releaseItems (int /*long*/ hItem, TVITEM tvItem) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); while (hItem != 0) { releaseItems (hItem, tvItem); releaseItem (hItem, tvItem, true); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } } void releaseHandle () { super.releaseHandle (); hwndParent = hwndHeader = 0; } void releaseChildren (boolean destroy) { if (items != null) { for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null && !item.isDisposed ()) { item.release (false); } } items = null; } if (columns != null) { for (int i=0; i<columns.length; i++) { TreeColumn column = columns [i]; if (column != null && !column.isDisposed ()) { column.release (false); } } columns = null; } super.releaseChildren (destroy); } void releaseWidget () { super.releaseWidget (); /* * Feature in Windows. For some reason, when TVM_GETIMAGELIST * or TVM_SETIMAGELIST is sent, the tree issues NM_CUSTOMDRAW * messages. This behavior is unwanted when the tree is being * disposed. The fix is to ignore NM_CUSTOMDRAW messages by * clearing the custom draw flag. * * NOTE: This only happens on Windows XP. */ customDraw = false; if (imageList != null) { OS.SendMessage (handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, 0); display.releaseImageList (imageList); } if (headerImageList != null) { if (hwndHeader != 0) { OS.SendMessage (hwndHeader, OS.HDM_SETIMAGELIST, 0, 0); } display.releaseImageList (headerImageList); } imageList = headerImageList = null; int /*long*/ hStateList = OS.SendMessage (handle, OS.TVM_GETIMAGELIST, OS.TVSIL_STATE, 0); OS.SendMessage (handle, OS.TVM_SETIMAGELIST, OS.TVSIL_STATE, 0); if (hStateList != 0) OS.ImageList_Destroy (hStateList); if (itemToolTipHandle != 0) OS.DestroyWindow (itemToolTipHandle); if (headerToolTipHandle != 0) OS.DestroyWindow (headerToolTipHandle); itemToolTipHandle = headerToolTipHandle = 0; if (display.isXMouseActive ()) { Shell shell = getShell (); if (shell.lockToolTipControl == this) { shell.lockToolTipControl = null; } } } /** * Removes all of the items from the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void removeAll () { checkWidget (); hFirstIndexOf = hLastIndexOf = 0; itemCount = -1; for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null && !item.isDisposed ()) { item.release (false); } } ignoreDeselect = ignoreSelect = true; boolean redraw = drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); shrink = ignoreShrink = true; int /*long*/ result = OS.SendMessage (handle, OS.TVM_DELETEITEM, 0, OS.TVI_ROOT); ignoreShrink = false; if (redraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); } ignoreDeselect = ignoreSelect = false; if (result == 0) error (SWT.ERROR_ITEM_NOT_REMOVED); if (imageList != null) { OS.SendMessage (handle, OS.TVM_SETIMAGELIST, 0, 0); display.releaseImageList (imageList); } imageList = null; if (hwndParent == 0 && !linesVisible) { if (!hooks (SWT.MeasureItem) && !hooks (SWT.EraseItem) && !hooks (SWT.PaintItem)) { customDraw = false; } } hAnchor = hInsert = hFirstIndexOf = hLastIndexOf = 0; itemCount = -1; items = new TreeItem [4]; scrollWidth = 0; setScrollWidth (); updateScrollBar (); } /** * Removes the listener from the collection of listeners who will * be notified when the user changes the receiver's selection. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see SelectionListener * @see #addSelectionListener */ public void removeSelectionListener (SelectionListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); eventTable.unhook (SWT.Selection, listener); eventTable.unhook (SWT.DefaultSelection, listener); } /** * Removes the listener from the collection of listeners who will * be notified when items in the receiver are expanded or collapsed. * * @param listener the listener which should no longer be notified * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the listener is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see TreeListener * @see #addTreeListener */ public void removeTreeListener(TreeListener listener) { checkWidget (); if (listener == null) error (SWT.ERROR_NULL_ARGUMENT); if (eventTable == null) return; eventTable.unhook (SWT.Expand, listener); eventTable.unhook (SWT.Collapse, listener); } /** * Display a mark indicating the point at which an item will be inserted. * The drop insert item has a visual hint to show where a dragged item * will be inserted when dropped on the tree. * * @param item the insert item. Null will clear the insertion mark. * @param before true places the insert mark above 'item'. false places * the insert mark below 'item'. * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setInsertMark (TreeItem item, boolean before) { checkWidget (); int /*long*/ hItem = 0; if (item != null) { if (item.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); hItem = item.handle; } hInsert = hItem; insertAfter = !before; OS.SendMessage (handle, OS.TVM_SETINSERTMARK, insertAfter ? 1 : 0, hInsert); } /** * Sets the number of root-level items contained in the receiver. * * @param count the number of items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public void setItemCount (int count) { checkWidget (); count = Math.max (0, count); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); setItemCount (count, OS.TVGN_ROOT, hItem); } void setItemCount (int count, int /*long*/ hParent, int /*long*/ hItem) { boolean redraw = false; if (OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0) == 0) { redraw = drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } int itemCount = 0; while (hItem != 0 && itemCount < count) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); itemCount++; } boolean expanded = false; TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; if (!redraw && (style & SWT.VIRTUAL) != 0) { if (OS.IsWinCE) { tvItem.hItem = hParent; tvItem.mask = OS.TVIF_STATE; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); expanded = (tvItem.state & OS.TVIS_EXPANDED) != 0; } else { /* * Bug in Windows. Despite the fact that TVM_GETITEMSTATE claims * to return only the bits specified by the stateMask, when called * with TVIS_EXPANDED, the entire state is returned. The fix is * to explicitly check for the TVIS_EXPANDED bit. */ int state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hParent, OS.TVIS_EXPANDED); expanded = (state & OS.TVIS_EXPANDED) != 0; } } while (hItem != 0) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); TreeItem item = tvItem.lParam != -1 ? items [(int)/*64*/tvItem.lParam] : null; if (item != null && !item.isDisposed ()) { item.dispose (); } else { releaseItem (tvItem.hItem, tvItem, false); destroyItem (null, tvItem.hItem); } } if ((style & SWT.VIRTUAL) != 0) { for (int i=itemCount; i<count; i++) { if (expanded) ignoreShrink = true; createItem (null, hParent, OS.TVI_LAST, 0); if (expanded) ignoreShrink = false; } } else { shrink = true; int extra = Math.max (4, (count + 3) / 4 * 4); TreeItem [] newItems = new TreeItem [items.length + extra]; System.arraycopy (items, 0, newItems, 0, items.length); items = newItems; for (int i=itemCount; i<count; i++) { new TreeItem (this, SWT.NONE, hParent, OS.TVI_LAST, 0); } } if (redraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); } } /** * Sets the height of the area which would be used to * display <em>one</em> of the items in the tree. * * @param itemHeight the height of one item * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ /*public*/ void setItemHeight (int itemHeight) { checkWidget (); if (itemHeight < -1) error (SWT.ERROR_INVALID_ARGUMENT); OS.SendMessage (handle, OS.TVM_SETITEMHEIGHT, itemHeight, 0); } /** * Marks the receiver's lines as visible if the argument is <code>true</code>, * and marks it invisible otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, marking * it visible may not actually cause it to be displayed. * </p> * * @param show the new visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public void setLinesVisible (boolean show) { checkWidget (); if (linesVisible == show) return; linesVisible = show; if (hwndParent == 0 && linesVisible) customDraw = true; OS.InvalidateRect (handle, null, true); } int /*long*/ scrolledHandle () { if (hwndHeader == 0) return handle; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); return count == 0 && scrollWidth == 0 ? handle : hwndParent; } void select (int /*long*/ hItem, TVITEM tvItem) { while (hItem != 0) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); select (hFirstItem, tvItem); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } } /** * Selects an item in the receiver. If the item was already * selected, it remains selected. * * @param item the item to be selected * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.4 */ public void select (TreeItem item) { checkWidget (); if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if ((style & SWT.SINGLE) != 0) { int /*long*/ hItem = item.handle; int state = 0; if (OS.IsWinCE) { TVITEM tvItem = new TVITEM (); tvItem.hItem = hItem; tvItem.mask = OS.TVIF_STATE; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) return; /* * Feature in Windows. When an item is selected with * TVM_SELECTITEM and TVGN_CARET, the tree expands and * scrolls to show the new selected item. Unfortunately, * there is no other way in Windows to set the focus * and select an item. The fix is to save the current * scroll bar positions, turn off redraw, select the item, * then scroll back to the original position and redraw * the entire tree. */ SCROLLINFO hInfo = null; int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_NOHSCROLL) == 0) { hInfo = new SCROLLINFO (); hInfo.cbSize = SCROLLINFO.sizeof; hInfo.fMask = OS.SIF_ALL; OS.GetScrollInfo (handle, OS.SB_HORZ, hInfo); } SCROLLINFO vInfo = new SCROLLINFO (); vInfo.cbSize = SCROLLINFO.sizeof; vInfo.fMask = OS.SIF_ALL; OS.GetScrollInfo (handle, OS.SB_VERT, vInfo); boolean redraw = drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) { OS.UpdateWindow (handle); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } setSelection (item); if (hInfo != null) { int /*long*/ hThumb = OS.MAKELPARAM (OS.SB_THUMBPOSITION, hInfo.nPos); OS.SendMessage (handle, OS.WM_HSCROLL, hThumb, 0); } int /*long*/ vThumb = OS.MAKELPARAM (OS.SB_THUMBPOSITION, vInfo.nPos); OS.SendMessage (handle, OS.WM_VSCROLL, vThumb, 0); if (redraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); if ((style & SWT.DOUBLE_BUFFERED) == 0) { int oldStyle = style; style |= SWT.DOUBLE_BUFFERED; OS.UpdateWindow (handle); style = oldStyle; } } return; } TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.state = OS.TVIS_SELECTED; tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } /** * Selects all of the items in the receiver. * <p> * If the receiver is single-select, do nothing. * </p> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void selectAll () { checkWidget (); if ((style & SWT.SINGLE) != 0) return; TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.state = OS.TVIS_SELECTED; tvItem.stateMask = OS.TVIS_SELECTED; int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); select (hItem, tvItem); } else { for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null) { tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); } Event sendEraseItemEvent (TreeItem item, NMTTCUSTOMDRAW nmcd, int column, RECT cellRect, int /*long*/ hFont) { int nSavedDC = OS.SaveDC (nmcd.hdc); RECT insetRect = toolTipInset (cellRect); OS.SetWindowOrgEx (nmcd.hdc, insetRect.left, insetRect.top, null); GCData data = new GCData (); data.device = display; data.foreground = OS.GetTextColor (nmcd.hdc); data.background = OS.GetBkColor (nmcd.hdc); data.hFont = hFont; GC gc = GC.win32_new (nmcd.hdc, data); Event event = new Event (); event.item = item; event.index = column; event.gc = gc; event.detail |= SWT.FOREGROUND; event.x = cellRect.left; event.y = cellRect.top; event.width = cellRect.right - cellRect.left; event.height = cellRect.bottom - cellRect.top; //gc.setClipping (event.x, event.y, event.width, event.height); sendEvent (SWT.EraseItem, event); event.gc = null; //int newTextClr = data.foreground; gc.dispose (); OS.RestoreDC (nmcd.hdc, nSavedDC); return event; } Event sendMeasureItemEvent (TreeItem item, int index, int /*long*/ hDC) { RECT itemRect = item.getBounds (index, true, true, false, false, false, hDC); int nSavedDC = OS.SaveDC (hDC); GCData data = new GCData (); data.device = display; data.hFont = item.fontHandle (index); GC gc = GC.win32_new (hDC, data); Event event = new Event (); event.item = item; event.gc = gc; event.index = index; event.x = itemRect.left; event.y = itemRect.top; event.width = itemRect.right - itemRect.left; event.height = itemRect.bottom - itemRect.top; sendEvent (SWT.MeasureItem, event); event.gc = null; gc.dispose (); OS.RestoreDC (hDC, nSavedDC); if (isDisposed () || item.isDisposed ()) return null; if (hwndHeader != 0) { int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (count == 0) { if (event.x + event.width > scrollWidth) { setScrollWidth (scrollWidth = event.x + event.width); } } } if (event.height > getItemHeight ()) setItemHeight (event.height); return event; } Event sendPaintItemEvent (TreeItem item, NMTTCUSTOMDRAW nmcd, int column, RECT itemRect, int /*long*/ hFont) { int nSavedDC = OS.SaveDC (nmcd.hdc); RECT insetRect = toolTipInset (itemRect); OS.SetWindowOrgEx (nmcd.hdc, insetRect.left, insetRect.top, null); GCData data = new GCData (); data.device = display; data.hFont = hFont; data.foreground = OS.GetTextColor (nmcd.hdc); data.background = OS.GetBkColor (nmcd.hdc); GC gc = GC.win32_new (nmcd.hdc, data); Event event = new Event (); event.item = item; event.index = column; event.gc = gc; event.detail |= SWT.FOREGROUND; event.x = itemRect.left; event.y = itemRect.top; event.width = itemRect.right - itemRect.left; event.height = itemRect.bottom - itemRect.top; //gc.setClipping (cellRect.left, cellRect.top, cellWidth, cellHeight); sendEvent (SWT.PaintItem, event); event.gc = null; gc.dispose (); OS.RestoreDC (nmcd.hdc, nSavedDC); return event; } void setBackgroundImage (int /*long*/ hBitmap) { super.setBackgroundImage (hBitmap); if (hBitmap != 0) { /* * Feature in Windows. If TVM_SETBKCOLOR is never * used to set the background color of a tree, the * background color of the lines and the plus/minus * will be drawn using the default background color, * not the HBRUSH returned from WM_CTLCOLOR. The fix * is to set the background color to the default (when * it is already the default) to make Windows use the * brush. */ if (OS.SendMessage (handle, OS.TVM_GETBKCOLOR, 0, 0) == -1) { OS.SendMessage (handle, OS.TVM_SETBKCOLOR, 0, -1); } _setBackgroundPixel (-1); } else { Control control = findBackgroundControl (); if (control == null) control = this; if (control.backgroundImage == null) { setBackgroundPixel (control.getBackgroundPixel ()); } } /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of the background image. The fix * is to clear TVS_FULLROWSELECT when a background * image is set. */ updateFullSelection (); } void setBackgroundPixel (int pixel) { Control control = findImageControl (); if (control != null) { setBackgroundImage (control.backgroundImage); return; } /* * Feature in Windows. When a tree is given a background color * using TVM_SETBKCOLOR and the tree is disabled, Windows draws * the tree using the background color rather than the disabled * colors. This is different from the table which draws grayed. * The fix is to set the default background color while the tree * is disabled and restore it when enabled. */ if (OS.IsWindowEnabled (handle)) _setBackgroundPixel (pixel); /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of the background image. The fix * is to restore TVS_FULLROWSELECT when a background * color is set. */ updateFullSelection (); } void setCursor () { /* * Bug in Windows. Under certain circumstances, when WM_SETCURSOR * is sent from SendMessage(), Windows GP's in the window proc for * the tree. The fix is to avoid calling the tree window proc and * set the cursor for the tree outside of WM_SETCURSOR. * * NOTE: This code assumes that the default cursor for the tree * is IDC_ARROW. */ Cursor cursor = findCursor (); int /*long*/ hCursor = cursor == null ? OS.LoadCursor (0, OS.IDC_ARROW) : cursor.handle; OS.SetCursor (hCursor); } /** * Sets the order that the items in the receiver should * be displayed in to the given argument which is described * in terms of the zero-relative ordering of when the items * were added. * * @param order the new order to display the items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item order is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item order is not the same length as the number of items</li> * </ul> * * @see Tree#getColumnOrder() * @see TreeColumn#getMoveable() * @see TreeColumn#setMoveable(boolean) * @see SWT#Move * * @since 3.2 */ public void setColumnOrder (int [] order) { checkWidget (); if (order == null) error (SWT.ERROR_NULL_ARGUMENT); int count = 0; if (hwndHeader != 0) { count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); } if (count == 0) { if (order.length != 0) error (SWT.ERROR_INVALID_ARGUMENT); return; } if (order.length != count) error (SWT.ERROR_INVALID_ARGUMENT); int [] oldOrder = new int [count]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, oldOrder); boolean reorder = false; boolean [] seen = new boolean [count]; for (int i=0; i<order.length; i++) { int index = order [i]; if (index < 0 || index >= count) error (SWT.ERROR_INVALID_RANGE); if (seen [index]) error (SWT.ERROR_INVALID_ARGUMENT); seen [index] = true; if (index != oldOrder [i]) reorder = true; } if (reorder) { RECT [] oldRects = new RECT [count]; for (int i=0; i<count; i++) { oldRects [i] = new RECT (); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, i, oldRects [i]); } OS.SendMessage (hwndHeader, OS.HDM_SETORDERARRAY, order.length, order); OS.InvalidateRect (handle, null, true); updateImageList (); TreeColumn [] newColumns = new TreeColumn [count]; System.arraycopy (columns, 0, newColumns, 0, count); RECT newRect = new RECT (); for (int i=0; i<count; i++) { TreeColumn column = newColumns [i]; if (!column.isDisposed ()) { OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, i, newRect); if (newRect.left != oldRects [i].left) { column.updateToolTip (i); column.sendEvent (SWT.Move); } } } } } void setCheckboxImageList () { if ((style & SWT.CHECK) == 0) return; int count = 5, flags = 0; if (OS.IsWinCE) { flags |= OS.ILC_COLOR; } else { if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { flags |= OS.ILC_COLOR32; } else { int /*long*/ hDC = OS.GetDC (handle); int bits = OS.GetDeviceCaps (hDC, OS.BITSPIXEL); int planes = OS.GetDeviceCaps (hDC, OS.PLANES); OS.ReleaseDC (handle, hDC); int depth = bits * planes; switch (depth) { case 4: flags |= OS.ILC_COLOR4; break; case 8: flags |= OS.ILC_COLOR8; break; case 16: flags |= OS.ILC_COLOR16; break; case 24: flags |= OS.ILC_COLOR24; break; case 32: flags |= OS.ILC_COLOR32; break; default: flags |= OS.ILC_COLOR; break; } flags |= OS.ILC_MASK; } } if ((style & SWT.RIGHT_TO_LEFT) != 0) flags |= OS.ILC_MIRROR; int height = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMHEIGHT, 0, 0), width = height; int /*long*/ hStateList = OS.ImageList_Create (width, height, flags, count, count); int /*long*/ hDC = OS.GetDC (handle); int /*long*/ memDC = OS.CreateCompatibleDC (hDC); int /*long*/ hBitmap = OS.CreateCompatibleBitmap (hDC, width * count, height); int /*long*/ hOldBitmap = OS.SelectObject (memDC, hBitmap); RECT rect = new RECT (); OS.SetRect (rect, 0, 0, width * count, height); /* * NOTE: DrawFrameControl() draws a black and white * mask when not drawing a push button. In order to * make the box surrounding the check mark transparent, * fill it with a color that is neither black or white. */ int clrBackground = 0; if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { Control control = findBackgroundControl (); if (control == null) control = this; clrBackground = control.getBackgroundPixel (); } else { clrBackground = 0x020000FF; if ((clrBackground & 0xFFFFFF) == OS.GetSysColor (OS.COLOR_WINDOW)) { clrBackground = 0x0200FF00; } } int /*long*/ hBrush = OS.CreateSolidBrush (clrBackground); OS.FillRect (memDC, rect, hBrush); OS.DeleteObject (hBrush); int /*long*/ oldFont = OS.SelectObject (hDC, defaultFont ()); TEXTMETRIC tm = OS.IsUnicode ? (TEXTMETRIC) new TEXTMETRICW () : new TEXTMETRICA (); OS.GetTextMetrics (hDC, tm); OS.SelectObject (hDC, oldFont); int itemWidth = Math.min (tm.tmHeight, width); int itemHeight = Math.min (tm.tmHeight, height); int left = (width - itemWidth) / 2, top = (height - itemHeight) / 2 + 1; OS.SetRect (rect, left + width, top, left + width + itemWidth, top + itemHeight); if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { int /*long*/ hTheme = display.hButtonTheme (); OS.DrawThemeBackground (hTheme, memDC, OS.BP_CHECKBOX, OS.CBS_UNCHECKEDNORMAL, rect, null); rect.left += width; rect.right += width; OS.DrawThemeBackground (hTheme, memDC, OS.BP_CHECKBOX, OS.CBS_CHECKEDNORMAL, rect, null); rect.left += width; rect.right += width; OS.DrawThemeBackground (hTheme, memDC, OS.BP_CHECKBOX, OS.CBS_UNCHECKEDNORMAL, rect, null); rect.left += width; rect.right += width; OS.DrawThemeBackground (hTheme, memDC, OS.BP_CHECKBOX, OS.CBS_MIXEDNORMAL, rect, null); } else { OS.DrawFrameControl (memDC, rect, OS.DFC_BUTTON, OS.DFCS_BUTTONCHECK | OS.DFCS_FLAT); rect.left += width; rect.right += width; OS.DrawFrameControl (memDC, rect, OS.DFC_BUTTON, OS.DFCS_BUTTONCHECK | OS.DFCS_CHECKED | OS.DFCS_FLAT); rect.left += width; rect.right += width; OS.DrawFrameControl (memDC, rect, OS.DFC_BUTTON, OS.DFCS_BUTTONCHECK | OS.DFCS_INACTIVE | OS.DFCS_FLAT); rect.left += width; rect.right += width; OS.DrawFrameControl (memDC, rect, OS.DFC_BUTTON, OS.DFCS_BUTTONCHECK | OS.DFCS_CHECKED | OS.DFCS_INACTIVE | OS.DFCS_FLAT); } OS.SelectObject (memDC, hOldBitmap); OS.DeleteDC (memDC); OS.ReleaseDC (handle, hDC); if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { OS.ImageList_Add (hStateList, hBitmap, 0); } else { OS.ImageList_AddMasked (hStateList, hBitmap, clrBackground); } OS.DeleteObject (hBitmap); int /*long*/ hOldStateList = OS.SendMessage (handle, OS.TVM_GETIMAGELIST, OS.TVSIL_STATE, 0); OS.SendMessage (handle, OS.TVM_SETIMAGELIST, OS.TVSIL_STATE, hStateList); if (hOldStateList != 0) OS.ImageList_Destroy (hOldStateList); } public void setFont (Font font) { checkWidget (); super.setFont (font); if ((style & SWT.CHECK) != 0) setCheckboxImageList (); } void setForegroundPixel (int pixel) { /* * Bug in Windows. When the tree is using the explorer * theme, it does not use COLOR_WINDOW_TEXT for the * foreground. When TVM_SETTEXTCOLOR is called with -1, * it resets the color to black, not COLOR_WINDOW_TEXT. * The fix is to explicitly set the color. */ if (explorerTheme) { if (pixel == -1) pixel = defaultForeground (); } OS.SendMessage (handle, OS.TVM_SETTEXTCOLOR, 0, pixel); } /** * Marks the receiver's header as visible if the argument is <code>true</code>, * and marks it invisible otherwise. * <p> * If one of the receiver's ancestors is not visible or some * other condition makes the receiver not visible, marking * it visible may not actually cause it to be displayed. * </p> * * @param show the new visibility state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public void setHeaderVisible (boolean show) { checkWidget (); if (hwndHeader == 0) { if (!show) return; createParent (); } int bits = OS.GetWindowLong (hwndHeader, OS.GWL_STYLE); if (show) { if ((bits & OS.HDS_HIDDEN) == 0) return; bits &= ~OS.HDS_HIDDEN; OS.SetWindowLong (hwndHeader, OS.GWL_STYLE, bits); OS.ShowWindow (hwndHeader, OS.SW_SHOW); } else { if ((bits & OS.HDS_HIDDEN) != 0) return; bits |= OS.HDS_HIDDEN; OS.SetWindowLong (hwndHeader, OS.GWL_STYLE, bits); OS.ShowWindow (hwndHeader, OS.SW_HIDE); } setScrollWidth (); updateHeaderToolTips (); updateScrollBar (); } public void setRedraw (boolean redraw) { checkWidget (); /* * Feature in Windows. When WM_SETREDRAW is used to * turn off redraw, the scroll bars are updated when * items are added and removed. The fix is to call * the default window proc to stop all drawing. * * Bug in Windows. For some reason, when WM_SETREDRAW * is used to turn redraw on for a tree and the tree * contains no items, the last item in the tree does * not redraw properly. If the tree has only one item, * that item is not drawn. If another window is dragged * on top of the item, parts of the item are redrawn * and erased at random. The fix is to ensure that this * case doesn't happen by inserting and deleting an item * when redraw is turned on and there are no items in * the tree. */ int /*long*/ hItem = 0; if (redraw) { if (drawCount == 1) { int count = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (count == 0) { TVINSERTSTRUCT tvInsert = new TVINSERTSTRUCT (); tvInsert.hInsertAfter = OS.TVI_FIRST; hItem = OS.SendMessage (handle, OS.TVM_INSERTITEM, 0, tvInsert); } OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); updateScrollBar (); } } super.setRedraw (redraw); if (!redraw) { if (drawCount == 1) OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } if (hItem != 0) { ignoreShrink = true; OS.SendMessage (handle, OS.TVM_DELETEITEM, 0, hItem); ignoreShrink = false; } } void setScrollWidth () { if (hwndHeader == 0 || hwndParent == 0) return; int width = 0; HDITEM hdItem = new HDITEM (); int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { hdItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, i, hdItem); width += hdItem.cxy; } setScrollWidth (Math.max (scrollWidth, width)); } void setScrollWidth (int width) { if (hwndHeader == 0 || hwndParent == 0) return; //TEMPORARY CODE //scrollWidth = width; int left = 0; RECT rect = new RECT (); SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_RANGE | OS.SIF_PAGE; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (count == 0 && width == 0) { OS.GetScrollInfo (hwndParent, OS.SB_HORZ, info); info.nPage = info.nMax + 1; OS.SetScrollInfo (hwndParent, OS.SB_HORZ, info, true); OS.GetScrollInfo (hwndParent, OS.SB_VERT, info); info.nPage = info.nMax + 1; OS.SetScrollInfo (hwndParent, OS.SB_VERT, info, true); } else { OS.GetClientRect (hwndParent, rect); OS.GetScrollInfo (hwndParent, OS.SB_HORZ, info); info.nMax = width; info.nPage = rect.right - rect.left + 1; OS.SetScrollInfo (hwndParent, OS.SB_HORZ, info, true); info.fMask = OS.SIF_POS; OS.GetScrollInfo (hwndParent, OS.SB_HORZ, info); left = info.nPos; } if (horizontalBar != null) { horizontalBar.setIncrement (INCREMENT); horizontalBar.setPageIncrement (info.nPage); } OS.GetClientRect (hwndParent, rect); int /*long*/ hHeap = OS.GetProcessHeap (); HDLAYOUT playout = new HDLAYOUT (); playout.prc = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, RECT.sizeof); playout.pwpos = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, WINDOWPOS.sizeof); OS.MoveMemory (playout.prc, rect, RECT.sizeof); OS.SendMessage (hwndHeader, OS.HDM_LAYOUT, 0, playout); WINDOWPOS pos = new WINDOWPOS (); OS.MoveMemory (pos, playout.pwpos, WINDOWPOS.sizeof); if (playout.prc != 0) OS.HeapFree (hHeap, 0, playout.prc); if (playout.pwpos != 0) OS.HeapFree (hHeap, 0, playout.pwpos); SetWindowPos (hwndHeader, OS.HWND_TOP, pos.x - left, pos.y, pos.cx + left, pos.cy, OS.SWP_NOACTIVATE); int bits = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); int b = (bits & OS.WS_EX_CLIENTEDGE) != 0 ? OS.GetSystemMetrics (OS.SM_CXEDGE) : 0; int w = pos.cx + (count == 0 && width == 0 ? 0 : OS.GetSystemMetrics (OS.SM_CXVSCROLL)); int h = rect.bottom - rect.top - pos.cy; boolean oldIgnore = ignoreResize; ignoreResize = true; SetWindowPos (handle, 0, pos.x - left - b, pos.y + pos.cy - b, w + left + b * 2, h + b * 2, OS.SWP_NOACTIVATE | OS.SWP_NOZORDER); ignoreResize = oldIgnore; } void setSelection (int /*long*/ hItem, TVITEM tvItem, TreeItem [] selection) { while (hItem != 0) { int index = 0; while (index < selection.length) { TreeItem item = selection [index]; if (item != null && item.handle == hItem) break; index++; } tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) != 0) { if (index == selection.length) { tvItem.state = 0; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } else { if (index != selection.length) { tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, hItem); setSelection (hFirstItem, tvItem, selection); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXT, hItem); } } /** * Sets the receiver's selection to the given item. * The current selection is cleared before the new item is selected. * <p> * If the item is not in the receiver, then it is ignored. * </p> * * @param item the item to select * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public void setSelection (TreeItem item) { checkWidget (); if (item == null) error (SWT.ERROR_NULL_ARGUMENT); setSelection (new TreeItem [] {item}); } /** * Sets the receiver's selection to be the given array of items. * The current selection is cleared before the new items are selected. * <p> * Items that are not in the receiver are ignored. * If the receiver is single-select and multiple items are specified, * then all items are ignored. * </p> * * @param items the array of items * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the array of items is null</li> * <li>ERROR_INVALID_ARGUMENT - if one of the items has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#deselectAll() */ public void setSelection (TreeItem [] items) { checkWidget (); if (items == null) error (SWT.ERROR_NULL_ARGUMENT); int length = items.length; if (length == 0 || ((style & SWT.SINGLE) != 0 && length > 1)) { deselectAll(); return; } /* Select/deselect the first item */ TreeItem item = items [0]; if (item != null) { if (item.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); int /*long*/ hOldItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); int /*long*/ hNewItem = hAnchor = item.handle; /* * Bug in Windows. When TVM_SELECTITEM is used to select and * scroll an item to be visible and the client area of the tree * is smaller that the size of one item, TVM_SELECTITEM makes * the next item in the tree visible by making it the top item * instead of making the desired item visible. The fix is to * detect the case when the client area is too small and make * the desired visible item be the top item in the tree. * * Note that TVM_SELECTITEM when called with TVGN_FIRSTVISIBLE * also requires the work around for scrolling. */ boolean fixScroll = checkScroll (hNewItem); if (fixScroll) { OS.SendMessage (handle, OS.WM_SETREDRAW, 1, 0); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } ignoreSelect = true; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hNewItem); ignoreSelect = false; if (OS.SendMessage (handle, OS.TVM_GETVISIBLECOUNT, 0, 0) == 0) { OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hNewItem); int /*long*/ hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hNewItem); if (hParent == 0) OS.SendMessage (handle, OS.WM_HSCROLL, OS.SB_TOP, 0); } if (fixScroll) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } /* * Feature in Windows. When the old and new focused item * are the same, Windows does not check to make sure that * the item is actually selected, not just focused. The * fix is to force the item to draw selected by setting * the state mask, and to ensure that it is visible. */ if (hOldItem == hNewItem) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.state = OS.TVIS_SELECTED; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); showItem (hNewItem); } } if ((style & SWT.SINGLE) != 0) return; /* Select/deselect the rest of the items */ TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); setSelection (hItem, tvItem, items); } else { for (int i=0; i<this.items.length; i++) { item = this.items [i]; if (item != null) { int index = 0; while (index < length) { if (items [index] == item) break; index++; } tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) != 0) { if (index == length) { tvItem.state = 0; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } else { if (index != length) { tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); } /** * Sets the column used by the sort indicator for the receiver. A null * value will clear the sort indicator. The current sort column is cleared * before the new column is set. * * @param column the column used by the sort indicator or <code>null</code> * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the column is disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public void setSortColumn (TreeColumn column) { checkWidget (); if (column != null && column.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if (sortColumn != null && !sortColumn.isDisposed ()) { sortColumn.setSortDirection (SWT.NONE); } sortColumn = column; if (sortColumn != null && sortDirection != SWT.NONE) { sortColumn.setSortDirection (sortDirection); } } /** * Sets the direction of the sort indicator for the receiver. The value * can be one of <code>UP</code>, <code>DOWN</code> or <code>NONE</code>. * * @param direction the direction of the sort indicator * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.2 */ public void setSortDirection (int direction) { checkWidget (); if ((direction & (SWT.UP | SWT.DOWN)) == 0 && direction != SWT.NONE) return; sortDirection = direction; if (sortColumn != null && !sortColumn.isDisposed ()) { sortColumn.setSortDirection (direction); } } /** * Sets the item which is currently at the top of the receiver. * This item can change when items are expanded, collapsed, scrolled * or new items are added or removed. * * @param item the item to be shown * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#getTopItem() * * @since 2.1 */ public void setTopItem (TreeItem item) { checkWidget (); if (item == null) SWT.error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); int /*long*/ hItem = item.handle; int /*long*/ hTopItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); if (hItem == hTopItem) return; boolean fixScroll = checkScroll (hItem), redraw = false; if (fixScroll) { OS.SendMessage (handle, OS.WM_SETREDRAW, 1, 0); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } else { redraw = drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hItem); int /*long*/ hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem); if (hParent == 0) OS.SendMessage (handle, OS.WM_HSCROLL, OS.SB_TOP, 0); if (fixScroll) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } else { if (redraw) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); } } updateScrollBar (); } void showItem (int /*long*/ hItem) { /* * Bug in Windows. When TVM_ENSUREVISIBLE is used to ensure * that an item is visible and the client area of the tree is * smaller that the size of one item, TVM_ENSUREVISIBLE makes * the next item in the tree visible by making it the top item * instead of making the desired item visible. The fix is to * detect the case when the client area is too small and make * the desired visible item be the top item in the tree. */ if (OS.SendMessage (handle, OS.TVM_GETVISIBLECOUNT, 0, 0) == 0) { boolean fixScroll = checkScroll (hItem); if (fixScroll) { OS.SendMessage (handle, OS.WM_SETREDRAW, 1, 0); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_FIRSTVISIBLE, hItem); /* This code is intentionally commented */ //int hParent = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem); //if (hParent == 0) OS.SendMessage (handle, OS.WM_HSCROLL, OS.SB_TOP, 0); OS.SendMessage (handle, OS.WM_HSCROLL, OS.SB_TOP, 0); if (fixScroll) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } } else { boolean scroll = true; RECT itemRect = new RECT (); if (OS.TreeView_GetItemRect (handle, hItem, itemRect, true)) { forceResize (); RECT rect = new RECT (); OS.GetClientRect (handle, rect); POINT pt = new POINT (); pt.x = itemRect.left; pt.y = itemRect.top; if (OS.PtInRect (rect, pt)) { pt.y = itemRect.bottom; if (OS.PtInRect (rect, pt)) scroll = false; } } if (scroll) { boolean fixScroll = checkScroll (hItem); if (fixScroll) { OS.SendMessage (handle, OS.WM_SETREDRAW, 1, 0); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } OS.SendMessage (handle, OS.TVM_ENSUREVISIBLE, 0, hItem); if (fixScroll) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.SendMessage (handle, OS.WM_SETREDRAW, 0, 0); } } } if (hwndParent != 0) { RECT itemRect = new RECT (); if (OS.TreeView_GetItemRect (handle, hItem, itemRect, true)) { forceResize (); RECT rect = new RECT (); OS.GetClientRect (hwndParent, rect); OS.MapWindowPoints (hwndParent, handle, rect, 2); POINT pt = new POINT (); pt.x = itemRect.left; pt.y = itemRect.top; if (!OS.PtInRect (rect, pt)) { pt.y = itemRect.bottom; if (!OS.PtInRect (rect, pt)) { SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_POS; info.nPos = Math.max (0, pt.x - Tree.INSET / 2); OS.SetScrollInfo (hwndParent, OS.SB_HORZ, info, true); setScrollWidth (); } } } } updateScrollBar (); } /** * Shows the column. If the column is already showing in the receiver, * this method simply returns. Otherwise, the columns are scrolled until * the column is visible. * * @param column the column to be shown * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.1 */ public void showColumn (TreeColumn column) { checkWidget (); if (column == null) error (SWT.ERROR_NULL_ARGUMENT); if (column.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); if (column.parent != this) return; int index = indexOf (column); if (index == -1) return; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (0 <= index && index < count) { if (hwndParent != 0) { forceResize (); RECT rect = new RECT (); OS.GetClientRect (hwndParent, rect); OS.MapWindowPoints (hwndParent, handle, rect, 2); RECT headerRect = new RECT (); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, index, headerRect); boolean scroll = headerRect.left < rect.left; if (!scroll) { int width = Math.min (rect.right - rect.left, headerRect.right - headerRect.left); scroll = headerRect.left + width > rect.right; } if (scroll) { SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_POS; info.nPos = Math.max (0, headerRect.left - Tree.INSET / 2); OS.SetScrollInfo (hwndParent, OS.SB_HORZ, info, true); setScrollWidth (); } } } } /** * Shows the item. If the item is already showing in the receiver, * this method simply returns. Otherwise, the items are scrolled * and expanded until the item is visible. * * @param item the item to be shown * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the item is null</li> * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#showSelection() */ public void showItem (TreeItem item) { checkWidget (); if (item == null) error (SWT.ERROR_NULL_ARGUMENT); if (item.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); showItem (item.handle); } /** * Shows the selection. If the selection is already showing in the receiver, * this method simply returns. Otherwise, the items are scrolled until * the selection is visible. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see Tree#showItem(TreeItem) */ public void showSelection () { checkWidget (); int /*long*/ hItem = 0; if ((style & SWT.SINGLE) != 0) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem == 0) return; int state = 0; if (OS.IsWinCE) { TVITEM tvItem = new TVITEM (); tvItem.hItem = hItem; tvItem.mask = OS.TVIF_STATE; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, hItem, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) == 0) return; } else { int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); TVITEM tvItem = null; if (OS.IsWinCE) { tvItem = new TVITEM (); tvItem.mask = OS.TVIF_STATE; } if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hRoot = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); hItem = getNextSelection (hRoot, tvItem); } else { //FIXME - this code expands first selected item it finds int index = 0; while (index <items.length) { TreeItem item = items [index]; if (item != null) { int state = 0; if (OS.IsWinCE) { tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); state = tvItem.state; } else { state = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETITEMSTATE, item.handle, OS.TVIS_SELECTED); } if ((state & OS.TVIS_SELECTED) != 0) { hItem = item.handle; break; } } index++; } } OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); } if (hItem != 0) showItem (hItem); } /*public*/ void sort () { checkWidget (); if ((style & SWT.VIRTUAL) != 0) return; sort (OS.TVI_ROOT, false); } void sort (int /*long*/ hParent, boolean all) { int itemCount = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (itemCount == 0 || itemCount == 1) return; hFirstIndexOf = hLastIndexOf = 0; itemCount = -1; if (sortDirection == SWT.UP || sortDirection == SWT.NONE) { OS.SendMessage (handle, OS.TVM_SORTCHILDREN, all ? 1 : 0, hParent); } else { Callback compareCallback = new Callback (this, "CompareFunc", 3); int /*long*/ lpfnCompare = compareCallback.getAddress (); TVSORTCB psort = new TVSORTCB (); psort.hParent = hParent; psort.lpfnCompare = lpfnCompare; psort.lParam = sortColumn == null ? 0 : indexOf (sortColumn); OS.SendMessage (handle, OS.TVM_SORTCHILDRENCB, all ? 1 : 0, psort); compareCallback.dispose (); } } void subclass () { super.subclass (); if (hwndHeader != 0) { OS.SetWindowLongPtr (hwndHeader, OS.GWLP_WNDPROC, display.windowProc); } } RECT toolTipInset (RECT rect) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { RECT insetRect = new RECT (); OS.SetRect (insetRect, rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1); return insetRect; } return rect; } RECT toolTipRect (RECT rect) { RECT toolRect = new RECT (); if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { OS.SetRect (toolRect, rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1); } else { OS.SetRect (toolRect, rect.left, rect.top, rect.right, rect.bottom); int dwStyle = OS.GetWindowLong (itemToolTipHandle, OS.GWL_STYLE); int dwExStyle = OS.GetWindowLong (itemToolTipHandle, OS.GWL_EXSTYLE); OS.AdjustWindowRectEx (toolRect, dwStyle, false, dwExStyle); } return toolRect; } String toolTipText (NMTTDISPINFO hdr) { int /*long*/ hwndToolTip = OS.SendMessage (handle, OS.TVM_GETTOOLTIPS, 0, 0); if (hwndToolTip == hdr.hwndFrom && toolTipText != null) return ""; //$NON-NLS-1$ if (headerToolTipHandle == hdr.hwndFrom) { int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { TreeColumn column = columns [i]; if (column.id == hdr.idFrom) return column.toolTipText; } return super.toolTipText (hdr); } if (itemToolTipHandle == hdr.hwndFrom) { if (toolTipText != null) return ""; int pos = OS.GetMessagePos (); POINT pt = new POINT(); OS.POINTSTOPOINT (pt, pos); OS.ScreenToClient (handle, pt); int [] index = new int [1]; TreeItem [] item = new TreeItem [1]; RECT [] cellRect = new RECT [1], itemRect = new RECT [1]; if (findCell (pt.x, pt.y, item, index, cellRect, itemRect)) { String text = null; if (index [0] == 0) { text = item [0].text; } else { String[] strings = item [0].strings; if (strings != null) text = strings [index [0]]; } //TEMPORARY CODE if (hooks (SWT.MeasureItem) || hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) { text = " "; } if (text != null) return text; } } return super.toolTipText (hdr); } int /*long*/ topHandle () { return hwndParent != 0 ? hwndParent : handle; } void updateFullSelection () { if ((style & SWT.FULL_SELECTION) != 0) { int oldBits = OS.GetWindowLong (handle, OS.GWL_STYLE), newBits = oldBits; if ((newBits & OS.TVS_FULLROWSELECT) != 0) { if (!OS.IsWindowEnabled (handle) || findImageControl () != null) { if (!explorerTheme) newBits &= ~OS.TVS_FULLROWSELECT; } } else { if (OS.IsWindowEnabled (handle) && findImageControl () == null) { if (!hooks (SWT.EraseItem) && !hooks (SWT.PaintItem)) { newBits |= OS.TVS_FULLROWSELECT; } } } if (newBits != oldBits) { OS.SetWindowLong (handle, OS.GWL_STYLE, newBits); OS.InvalidateRect (handle, null, true); } } } void updateHeaderToolTips () { if (headerToolTipHandle == 0) return; RECT rect = new RECT (); TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; lpti.uFlags = OS.TTF_SUBCLASS; lpti.hwnd = hwndHeader; lpti.lpszText = OS.LPSTR_TEXTCALLBACK; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { TreeColumn column = columns [i]; if (OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, i, rect) != 0) { lpti.uId = column.id = display.nextToolTipId++; lpti.left = rect.left; lpti.top = rect.top; lpti.right = rect.right; lpti.bottom = rect.bottom; OS.SendMessage (headerToolTipHandle, OS.TTM_ADDTOOL, 0, lpti); } } } void updateImageList () { if (imageList == null) return; if (hwndHeader == 0) return; int i = 0, index = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0); while (i < items.length) { TreeItem item = items [i]; if (item != null) { Image image = null; if (index == 0) { image = item.image; } else { Image [] images = item.images; if (images != null) image = images [index]; } if (image != null) break; } i++; } /* * Feature in Windows. When setting the same image list multiple * times, Windows does work making this operation slow. The fix * is to test for the same image list before setting the new one. */ int /*long*/ hImageList = i == items.length ? 0 : imageList.getHandle (); int /*long*/ hOldImageList = OS.SendMessage (handle, OS.TVM_GETIMAGELIST, OS.TVSIL_NORMAL, 0); if (hImageList != hOldImageList) { OS.SendMessage (handle, OS.TVM_SETIMAGELIST, OS.TVSIL_NORMAL, hImageList); } } void updateImages () { if (sortColumn != null && !sortColumn.isDisposed ()) { if (OS.COMCTL32_MAJOR < 6) { switch (sortDirection) { case SWT.UP: case SWT.DOWN: sortColumn.setImage (display.getSortImage (sortDirection), true, true); break; } } } } void updateScrollBar () { if (hwndParent != 0) { int columnCount = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); if (columnCount != 0 || scrollWidth != 0) { SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_ALL; int itemCount = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETCOUNT, 0, 0); if (itemCount == 0) { OS.GetScrollInfo (hwndParent, OS.SB_VERT, info); info.nPage = info.nMax + 1; OS.SetScrollInfo (hwndParent, OS.SB_VERT, info, true); } else { OS.GetScrollInfo (handle, OS.SB_VERT, info); if (info.nPage == 0) { SCROLLBARINFO psbi = new SCROLLBARINFO (); psbi.cbSize = SCROLLBARINFO.sizeof; OS.GetScrollBarInfo (handle, OS.OBJID_VSCROLL, psbi); if ((psbi.rgstate [0] & OS.STATE_SYSTEM_INVISIBLE) != 0) { info.nPage = info.nMax + 1; } } OS.SetScrollInfo (hwndParent, OS.SB_VERT, info, true); } } } } void unsubclass () { super.unsubclass (); if (hwndHeader != 0) { OS.SetWindowLongPtr (hwndHeader, OS.GWLP_WNDPROC, HeaderProc); } } int widgetStyle () { int bits = super.widgetStyle () | OS.TVS_SHOWSELALWAYS | OS.TVS_LINESATROOT | OS.TVS_HASBUTTONS | OS.TVS_NONEVENHEIGHT; if (EXPLORER_THEME && !OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { bits |= OS.TVS_TRACKSELECT; if ((style & SWT.FULL_SELECTION) != 0) bits |= OS.TVS_FULLROWSELECT; } else { if ((style & SWT.FULL_SELECTION) != 0) { bits |= OS.TVS_FULLROWSELECT; } else { bits |= OS.TVS_HASLINES; } } // bits |= OS.TVS_NOTOOLTIPS | OS.TVS_DISABLEDRAGDROP; return bits | OS.TVS_DISABLEDRAGDROP; } TCHAR windowClass () { return TreeClass; } int /*long*/ windowProc () { return TreeProc; } int /*long*/ windowProc (int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) { if (hwndHeader != 0 && hwnd == hwndHeader) { switch (msg) { /* This code is intentionally commented */ // case OS.WM_CONTEXTMENU: { // LRESULT result = wmContextMenu (hwnd, wParam, lParam); // if (result != null) return result.value; // break; // } case OS.WM_CAPTURECHANGED: { /* * Bug in Windows. When the capture changes during a * header drag, Windows does not redraw the header item * such that the header remains pressed. For example, * when focus is assigned to a push button, the mouse is * pressed (but not released), then the SPACE key is * pressed to activate the button, the capture changes, * the header not notified and NM_RELEASEDCAPTURE is not * sent. The fix is to redraw the header when the capture * changes to another control. * * This does not happen on XP. */ if (OS.COMCTL32_MAJOR < 6) { if (lParam != 0 && lParam != hwndHeader) { OS.InvalidateRect (hwndHeader, null, true); } } break; } case OS.WM_MOUSELEAVE: { /* * Bug in Windows. On XP, when a tooltip is hidden * due to a time out or mouse press, the tooltip * remains active although no longer visible and * won't show again until another tooltip becomes * active. The fix is to reset the tooltip bounds. */ if (OS.COMCTL32_MAJOR >= 6) updateHeaderToolTips (); updateHeaderToolTips (); break; } case OS.WM_NOTIFY: { NMHDR hdr = new NMHDR (); OS.MoveMemory (hdr, lParam, NMHDR.sizeof); switch (hdr.code) { case OS.TTN_SHOW: case OS.TTN_POP: case OS.TTN_GETDISPINFOA: case OS.TTN_GETDISPINFOW: return OS.SendMessage (handle, msg, wParam, lParam); } break; } case OS.WM_SETCURSOR: { if (wParam == hwnd) { int hitTest = (short) OS.LOWORD (lParam); if (hitTest == OS.HTCLIENT) { HDHITTESTINFO pinfo = new HDHITTESTINFO (); int pos = OS.GetMessagePos (); POINT pt = new POINT (); OS.POINTSTOPOINT (pt, pos); OS.ScreenToClient (hwnd, pt); pinfo.x = pt.x; pinfo.y = pt.y; int columnCount = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); int index = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_HITTEST, 0, pinfo); if (0 <= index && index < columnCount && !columns [index].resizable) { if ((pinfo.flags & (OS.HHT_ONDIVIDER | OS.HHT_ONDIVOPEN)) != 0) { OS.SetCursor (OS.LoadCursor (0, OS.IDC_ARROW)); return 1; } } } } break; } } return callWindowProc (hwnd, msg, wParam, lParam); } if (hwndParent != 0 && hwnd == hwndParent) { switch (msg) { case OS.WM_MOVE: { sendEvent (SWT.Move); return 0; } case OS.WM_SIZE: { setScrollWidth (); if (ignoreResize) return 0; setResizeChildren (false); int /*long*/ code = callWindowProc (hwnd, OS.WM_SIZE, wParam, lParam); sendEvent (SWT.Resize); if (isDisposed ()) return 0; if (layout != null) { markLayout (false, false); updateLayout (false, false); } setResizeChildren (true); updateScrollBar (); return code; } case OS.WM_NCPAINT: { LRESULT result = wmNCPaint (hwnd, wParam, lParam); if (result != null) return result.value; break; } case OS.WM_PRINT: { LRESULT result = wmPrint (hwnd, wParam, lParam); if (result != null) return result.value; break; } case OS.WM_COMMAND: case OS.WM_NOTIFY: case OS.WM_SYSCOLORCHANGE: { return OS.SendMessage (handle, msg, wParam, lParam); } case OS.WM_HSCROLL: { /* * Bug on WinCE. lParam should be NULL when the message is not sent * by a scroll bar control, but it contains the handle to the window. * When the message is sent by a scroll bar control, it correctly * contains the handle to the scroll bar. The fix is to check for * both. */ if (horizontalBar != null && (lParam == 0 || lParam == hwndParent)) { wmScroll (horizontalBar, true, hwndParent, OS.WM_HSCROLL, wParam, lParam); } setScrollWidth (); break; } case OS.WM_VSCROLL: { SCROLLINFO info = new SCROLLINFO (); info.cbSize = SCROLLINFO.sizeof; info.fMask = OS.SIF_ALL; OS.GetScrollInfo (hwndParent, OS.SB_VERT, info); /* * Update the nPos field to match the nTrackPos field * so that the tree scrolls when the scroll bar of the * parent is dragged. * * NOTE: For some reason, this code is only necessary * on Windows Vista. */ if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { if (OS.LOWORD (wParam) == OS.SB_THUMBTRACK) { info.nPos = info.nTrackPos; } } OS.SetScrollInfo (handle, OS.SB_VERT, info, true); int /*long*/ code = OS.SendMessage (handle, OS.WM_VSCROLL, wParam, lParam); OS.GetScrollInfo (handle, OS.SB_VERT, info); OS.SetScrollInfo (hwndParent, OS.SB_VERT, info, true); return code; } } return callWindowProc (hwnd, msg, wParam, lParam); } return super.windowProc (hwnd, msg, wParam, lParam); } LRESULT WM_CHAR (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_CHAR (wParam, lParam); if (result != null) return result; /* * Feature in Windows. The tree control beeps * in WM_CHAR when the search for the item that * matches the key stroke fails. This is the * standard tree behavior but is unexpected when * the key that was typed was ESC, CR or SPACE. * The fix is to avoid calling the tree window * proc in these cases. */ switch ((int)/*64*/wParam) { case ' ': { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) { hAnchor = hItem; OS.SendMessage (handle, OS.TVM_ENSUREVISIBLE, 0, hItem); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE | OS.TVIF_PARAM; tvItem.hItem = hItem; if ((style & SWT.CHECK) != 0) { tvItem.stateMask = OS.TVIS_STATEIMAGEMASK; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); int state = tvItem.state >> 12; if ((state & 0x1) != 0) { state++; } else { --state; } tvItem.state = state << 12; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); if (!OS.IsWinCE) { int /*long*/ id = hItem; if (OS.COMCTL32_MAJOR >= 6) { id = OS.SendMessage (handle, OS.TVM_MAPHTREEITEMTOACCID, hItem, 0); } OS.NotifyWinEvent (OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, (int)/*64*/id); } } tvItem.stateMask = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((style & SWT.MULTI) != 0 && OS.GetKeyState (OS.VK_CONTROL) < 0) { if ((tvItem.state & OS.TVIS_SELECTED) != 0) { tvItem.state &= ~OS.TVIS_SELECTED; } else { tvItem.state |= OS.TVIS_SELECTED; } } else { tvItem.state |= OS.TVIS_SELECTED; } OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); TreeItem item = _getItem (hItem, (int)/*64*/tvItem.lParam); Event event = new Event (); event.item = item; postEvent (SWT.Selection, event); if ((style & SWT.CHECK) != 0) { event = new Event (); event.item = item; event.detail = SWT.CHECK; postEvent (SWT.Selection, event); } } return LRESULT.ZERO; } case SWT.CR: { /* * Feature in Windows. Windows sends NM_RETURN from WM_KEYDOWN * instead of using WM_CHAR. This means that application code * that expects to consume the key press and therefore avoid a * SWT.DefaultSelection event from WM_CHAR will fail. The fix * is to implement SWT.DefaultSelection in WM_CHAR instead of * using NM_RETURN. */ Event event = new Event (); int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) event.item = _getItem (hItem); postEvent (SWT.DefaultSelection, event); return LRESULT.ZERO; } case SWT.ESC: return LRESULT.ZERO; } return result; } LRESULT WM_ERASEBKGND (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_ERASEBKGND (wParam, lParam); if ((style & SWT.DOUBLE_BUFFERED) != 0) return LRESULT.ONE; if (findImageControl () != null) return LRESULT.ONE; return result; } LRESULT WM_GETOBJECT (int /*long*/ wParam, int /*long*/ lParam) { /* * Ensure that there is an accessible object created for this * control because support for checked item and tree column * accessibility is temporarily implemented in the accessibility * package. */ if ((style & SWT.CHECK) != 0 || hwndParent != 0) { if (accessible == null) accessible = new_Accessible (this); } return super.WM_GETOBJECT (wParam, lParam); } LRESULT WM_KEYDOWN (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_KEYDOWN (wParam, lParam); if (result != null) return result; switch ((int)/*64*/wParam) { case OS.VK_SPACE: /* * Ensure that the window proc does not process VK_SPACE * so that it can be handled in WM_CHAR. This allows the * application to cancel an operation that is normally * performed in WM_KEYDOWN from WM_CHAR. */ return LRESULT.ZERO; case OS.VK_ADD: if (OS.GetKeyState (OS.VK_CONTROL) < 0) { if (hwndHeader != 0) { int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); TreeColumn [] newColumns = new TreeColumn [count]; System.arraycopy (columns, 0, newColumns, 0, count); for (int i=0; i<count; i++) { TreeColumn column = newColumns [i]; if (!column.isDisposed () && column.getResizable ()) { column.pack (); } } } } break; case OS.VK_UP: case OS.VK_DOWN: case OS.VK_PRIOR: case OS.VK_NEXT: case OS.VK_HOME: case OS.VK_END: { OS.SendMessage (handle, OS.WM_CHANGEUISTATE, OS.UIS_INITIALIZE, 0); if ((style & SWT.SINGLE) != 0) break; if (OS.GetKeyState (OS.VK_SHIFT) < 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) { if (hAnchor == 0) hAnchor = hItem; ignoreSelect = ignoreDeselect = true; int /*long*/ code = callWindowProc (handle, OS.WM_KEYDOWN, wParam, lParam); ignoreSelect = ignoreDeselect = false; int /*long*/ hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; int /*long*/ hDeselectItem = hItem; RECT rect1 = new RECT (); if (!OS.TreeView_GetItemRect (handle, hAnchor, rect1, false)) { hAnchor = hItem; OS.TreeView_GetItemRect (handle, hAnchor, rect1, false); } RECT rect2 = new RECT (); OS.TreeView_GetItemRect (handle, hDeselectItem, rect2, false); int flags = rect1.top < rect2.top ? OS.TVGN_PREVIOUSVISIBLE : OS.TVGN_NEXTVISIBLE; while (hDeselectItem != hAnchor) { tvItem.hItem = hDeselectItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); hDeselectItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, flags, hDeselectItem); } int /*long*/ hSelectItem = hAnchor; OS.TreeView_GetItemRect (handle, hNewItem, rect1, false); OS.TreeView_GetItemRect (handle, hSelectItem, rect2, false); tvItem.state = OS.TVIS_SELECTED; flags = rect1.top < rect2.top ? OS.TVGN_PREVIOUSVISIBLE : OS.TVGN_NEXTVISIBLE; while (hSelectItem != hNewItem) { tvItem.hItem = hSelectItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); hSelectItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, flags, hSelectItem); } tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); Event event = new Event (); event.item = _getItem (hNewItem, (int)/*64*/tvItem.lParam); postEvent (SWT.Selection, event); return new LRESULT (code); } } if (OS.GetKeyState (OS.VK_CONTROL) < 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hItem != 0) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); boolean oldSelected = (tvItem.state & OS.TVIS_SELECTED) != 0; int /*long*/ hNewItem = 0; switch ((int)/*64*/wParam) { case OS.VK_UP: hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PREVIOUSVISIBLE, hItem); break; case OS.VK_DOWN: hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hItem); break; case OS.VK_HOME: hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); break; case OS.VK_PRIOR: hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); if (hNewItem == hItem) { OS.SendMessage (handle, OS.WM_VSCROLL, OS.SB_PAGEUP, 0); hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); } break; case OS.VK_NEXT: RECT rect = new RECT (), clientRect = new RECT (); OS.GetClientRect (handle, clientRect); hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_FIRSTVISIBLE, 0); do { int /*long*/ hVisible = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hNewItem); if (hVisible == 0) break; if (!OS.TreeView_GetItemRect (handle, hVisible, rect, false)) break; if (rect.bottom > clientRect.bottom) break; if ((hNewItem = hVisible) == hItem) { OS.SendMessage (handle, OS.WM_VSCROLL, OS.SB_PAGEDOWN, 0); } } while (hNewItem != 0); break; case OS.VK_END: hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_LASTVISIBLE, 0); break; } if (hNewItem != 0) { OS.SendMessage (handle, OS.TVM_ENSUREVISIBLE, 0, hNewItem); tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); boolean newSelected = (tvItem.state & OS.TVIS_SELECTED) != 0; boolean redraw = !newSelected && drawCount == 0 && OS.IsWindowVisible (handle); if (redraw) { OS.UpdateWindow (handle); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } hSelect = hNewItem; ignoreSelect = true; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, hNewItem); ignoreSelect = false; hSelect = 0; if (oldSelected) { tvItem.state = OS.TVIS_SELECTED; tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } if (!newSelected) { tvItem.state = 0; tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } if (redraw) { RECT rect1 = new RECT (), rect2 = new RECT (); boolean fItemRect = (style & SWT.FULL_SELECTION) == 0; if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) fItemRect = false; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) fItemRect = false; OS.TreeView_GetItemRect (handle, hItem, rect1, fItemRect); OS.TreeView_GetItemRect (handle, hNewItem, rect2, fItemRect); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, rect1, true); OS.InvalidateRect (handle, rect2, true); OS.UpdateWindow (handle); } return LRESULT.ZERO; } } } int /*long*/ code = callWindowProc (handle, OS.WM_KEYDOWN, wParam, lParam); hAnchor = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); return new LRESULT (code); } } return result; } LRESULT WM_KILLFOCUS (int /*long*/ wParam, int /*long*/ lParam) { /* * Bug in Windows. When a tree item that has an image * with alpha is expanded or collapsed, the area where * the image is drawn is not erased before it is drawn. * This means that the image gets darker each time. * The fix is to redraw the selection. * * Feature in Windows. When multiple item have * the TVIS_SELECTED state, Windows redraws only * the focused item in the color used to show the * selection when the tree loses or gains focus. * The fix is to force Windows to redraw the * selection when focus is gained or lost. */ boolean redraw = (style & SWT.MULTI) != 0; if (!redraw) { if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) { if (imageList != null) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { redraw = true; } } } } if (redraw) redrawSelection (); return super.WM_KILLFOCUS (wParam, lParam); } LRESULT WM_LBUTTONDBLCLK (int /*long*/ wParam, int /*long*/ lParam) { TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = OS.GET_X_LPARAM (lParam); lpht.y = OS.GET_Y_LPARAM (lParam); OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem != 0) { if ((style & SWT.CHECK) != 0) { if ((lpht.flags & OS.TVHT_ONITEMSTATEICON) != 0) { Display display = this.display; display.captureChanged = false; sendMouseEvent (SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam); if (!sendMouseEvent (SWT.MouseDoubleClick, 1, handle, OS.WM_LBUTTONDBLCLK, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } OS.SetFocus (handle); TVITEM tvItem = new TVITEM (); tvItem.hItem = lpht.hItem; tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_STATEIMAGEMASK; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); int state = tvItem.state >> 12; if ((state & 0x1) != 0) { state++; } else { --state; } tvItem.state = state << 12; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); if (!OS.IsWinCE) { int /*long*/ id = tvItem.hItem; if (OS.COMCTL32_MAJOR >= 6) { id = OS.SendMessage (handle, OS.TVM_MAPHTREEITEMTOACCID, tvItem.hItem, 0); } OS.NotifyWinEvent (OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, (int)/*64*/id); } Event event = new Event (); event.item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); event.detail = SWT.CHECK; postEvent (SWT.Selection, event); return LRESULT.ZERO; } } } LRESULT result = super.WM_LBUTTONDBLCLK (wParam, lParam); if (result == LRESULT.ZERO) return result; if (lpht.hItem != 0) { if ((style & SWT.FULL_SELECTION) != 0 || (lpht.flags & OS.TVHT_ONITEM) != 0) { Event event = new Event (); event.item = _getItem (lpht.hItem); postEvent (SWT.DefaultSelection, event); } } return result; } LRESULT WM_LBUTTONDOWN (int /*long*/ wParam, int /*long*/ lParam) { /* * In a multi-select tree, if the user is collapsing a subtree that * contains selected items, clear the selection from these items and * issue a selection event. Only items that are selected and visible * are cleared. This code also runs in the case when the white space * below the last item is selected. */ TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = OS.GET_X_LPARAM (lParam); lpht.y = OS.GET_Y_LPARAM (lParam); OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem == 0 || (lpht.flags & OS.TVHT_ONITEMBUTTON) != 0) { Display display = this.display; display.captureChanged = false; if (!sendMouseEvent (SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } boolean fixSelection = false, deselected = false; int /*long*/ hOldSelection = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (lpht.hItem != 0 && (style & SWT.MULTI) != 0) { if (hOldSelection != 0) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.hItem = lpht.hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_EXPANDED) != 0) { fixSelection = true; tvItem.stateMask = OS.TVIS_SELECTED; int /*long*/ hNext = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, lpht.hItem); while (hNext != 0) { if (hNext == hAnchor) hAnchor = 0; tvItem.hItem = hNext; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) != 0) deselected = true; tvItem.state = 0; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); int /*long*/ hItem = hNext = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_NEXTVISIBLE, hNext); while (hItem != 0 && hItem != lpht.hItem) { hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_PARENT, hItem); } if (hItem == 0) break; } } } } dragStarted = gestureCompleted = false; if (fixSelection) ignoreDeselect = ignoreSelect = lockSelection = true; int /*long*/ code = callWindowProc (handle, OS.WM_LBUTTONDOWN, wParam, lParam); if (fixSelection) ignoreDeselect = ignoreSelect = lockSelection = false; int /*long*/ hNewSelection = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if (hOldSelection != hNewSelection) hAnchor = hNewSelection; if (dragStarted) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } } if (deselected) { Event event = new Event (); event.item = _getItem (lpht.hItem); postEvent (SWT.Selection, event); } return new LRESULT (code); } /* Look for check/uncheck */ if ((style & SWT.CHECK) != 0) { if ((lpht.flags & OS.TVHT_ONITEMSTATEICON) != 0) { Display display = this.display; display.captureChanged = false; if (!sendMouseEvent (SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } OS.SetFocus (handle); TVITEM tvItem = new TVITEM (); tvItem.hItem = lpht.hItem; tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_STATEIMAGEMASK; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); int state = tvItem.state >> 12; if ((state & 0x1) != 0) { state++; } else { --state; } tvItem.state = state << 12; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); if (!OS.IsWinCE) { int /*long*/ id = tvItem.hItem; if (OS.COMCTL32_MAJOR >= 6) { id = OS.SendMessage (handle, OS.TVM_MAPHTREEITEMTOACCID, tvItem.hItem, 0); } OS.NotifyWinEvent (OS.EVENT_OBJECT_FOCUS, handle, OS.OBJID_CLIENT, (int)/*64*/id); } Event event = new Event (); event.item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); event.detail = SWT.CHECK; postEvent (SWT.Selection, event); return LRESULT.ZERO; } } /* Process the mouse when an item is not selected */ if ((style & SWT.FULL_SELECTION) == 0) { if ((lpht.flags & OS.TVHT_ONITEM) == 0) { Display display = this.display; display.captureChanged = false; if (!sendMouseEvent (SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } int /*long*/ code = callWindowProc (handle, OS.WM_LBUTTONDOWN, wParam, lParam); if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return new LRESULT (code); } } /* Get the selected state of the item under the mouse */ TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; boolean hittestSelected = false, focused = false; if ((style & SWT.MULTI) != 0) { tvItem.hItem = lpht.hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); hittestSelected = (tvItem.state & OS.TVIS_SELECTED) != 0; focused = OS.GetFocus () == handle; } /* Get the selected state of the last selected item */ boolean redraw = false; int /*long*/ hOldItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); if ((style & SWT.MULTI) != 0) { tvItem.hItem = hOldItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); /* Check for CONTROL or drag selection */ if (hittestSelected || (wParam & OS.MK_CONTROL) != 0) { /* * Feature in Windows. When the tree is not drawing focus * and the user selects a tree item using while the CONTROL * key is down, the tree window proc sends WM_UPDATEUISTATE * to the top level window, causing controls within the shell * to redraw. When drag detect is enabled, the tree window * proc runs a modal loop that allows WM_PAINT messages to be * delivered during WM_LBUTTONDOWN. When WM_SETREDRAW is used * to disable drawing for the tree and a WM_PAINT happens for * a parent of the tree (or a sibling that overlaps), the parent * will draw on top of the tree. If WM_SETREDRAW is turned back * on without redrawing the entire tree, pixel corruption occurs. * This case only seems to happen when the tree has been given * focus from WM_MOUSEACTIVATE of the shell. The fix is to * detect that WM_UPDATEUISTATE will be sent and avoid using * WM_SETREDRAW to disable drawing. * * NOTE: Any redraw of a parent (or sibling) will be dispatched * during the modal drag detect loop. This code only fixes the * case where the tree causes a redraw from WM_UPDATEUISTATE. * In SWT, the InvalidateRect() that causes the pixel corruption * is found in Composite.WM_UPDATEUISTATE(). */ int uiState = (int)/*64*/OS.SendMessage (handle, OS.WM_QUERYUISTATE, 0, 0); if ((uiState & OS.UISF_HIDEFOCUS) == 0) { redraw = focused && drawCount == 0 && OS.IsWindowVisible (handle); } if (redraw) { OS.UpdateWindow (handle); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } } else { deselectAll (); } } /* Do the selection */ Display display = this.display; display.captureChanged = false; if (!sendMouseEvent (SWT.MouseDown, 1, handle, OS.WM_LBUTTONDOWN, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } hSelect = lpht.hItem; dragStarted = gestureCompleted = false; ignoreDeselect = ignoreSelect = true; int /*long*/ code = callWindowProc (handle, OS.WM_LBUTTONDOWN, wParam, lParam); int /*long*/ hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); /* * Feature in Windows. When the tree has the style * TVS_FULLROWSELECT, the background color for the * entire row is filled when an item is painted, * drawing on top of any custom drawing. The fix * is to emulate TVS_FULLROWSELECT. */ if ((style & SWT.FULL_SELECTION) != 0) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { if (lpht.hItem != 0) { if (hOldItem == 0 || (hNewItem == hOldItem && lpht.hItem != hOldItem)) { OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, lpht.hItem); hNewItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CARET, 0); } if (!dragStarted && (state & DRAG_DETECT) != 0 && hooks (SWT.DragDetect)) { dragStarted = dragDetect (handle, lpht.x, lpht.y, false, null, null); } } } } ignoreDeselect = ignoreSelect = false; hSelect = 0; if (dragStarted) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } } /* * Feature in Windows. When the old and new focused item * are the same, Windows does not check to make sure that * the item is actually selected, not just focused. The * fix is to force the item to draw selected by setting * the state mask. This is only necessary when the tree * is single select. */ if ((style & SWT.SINGLE) != 0) { if (hOldItem == hNewItem) { tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.state = OS.TVIS_SELECTED; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.hItem = hNewItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } /* Reselect the last item that was unselected */ if ((style & SWT.MULTI) != 0) { /* Check for CONTROL and reselect the last item */ if (hittestSelected || (wParam & OS.MK_CONTROL) != 0) { if (hOldItem == hNewItem && hOldItem == lpht.hItem) { if ((wParam & OS.MK_CONTROL) != 0) { tvItem.state ^= OS.TVIS_SELECTED; if (dragStarted) tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } else { if ((tvItem.state & OS.TVIS_SELECTED) != 0) { tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } if ((wParam & OS.MK_CONTROL) != 0 && !dragStarted) { if (hittestSelected) { tvItem.state = 0; tvItem.hItem = lpht.hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } if (redraw) { RECT rect1 = new RECT (), rect2 = new RECT (); boolean fItemRect = (style & SWT.FULL_SELECTION) == 0; if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) fItemRect = false; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) fItemRect = false; OS.TreeView_GetItemRect (handle, hOldItem, rect1, fItemRect); OS.TreeView_GetItemRect (handle, hNewItem, rect2, fItemRect); OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, rect1, true); OS.InvalidateRect (handle, rect2, true); OS.UpdateWindow (handle); } } /* Check for SHIFT or normal select and deselect/reselect items */ if ((wParam & OS.MK_CONTROL) == 0) { if (!hittestSelected || !dragStarted) { tvItem.state = 0; int /*long*/ oldProc = OS.GetWindowLongPtr (handle, OS.GWLP_WNDPROC); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, TreeProc); if ((style & SWT.VIRTUAL) != 0) { int /*long*/ hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_ROOT, 0); deselect (hItem, tvItem, hNewItem); } else { for (int i=0; i<items.length; i++) { TreeItem item = items [i]; if (item != null && item.handle != hNewItem) { tvItem.hItem = item.handle; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } tvItem.hItem = hNewItem; tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); OS.SetWindowLongPtr (handle, OS.GWLP_WNDPROC, oldProc); if ((wParam & OS.MK_SHIFT) != 0) { RECT rect1 = new RECT (); if (hAnchor == 0) hAnchor = hNewItem; if (OS.TreeView_GetItemRect (handle, hAnchor, rect1, false)) { RECT rect2 = new RECT (); if (OS.TreeView_GetItemRect (handle, hNewItem, rect2, false)) { int flags = rect1.top < rect2.top ? OS.TVGN_NEXTVISIBLE : OS.TVGN_PREVIOUSVISIBLE; tvItem.state = OS.TVIS_SELECTED; int /*long*/ hItem = tvItem.hItem = hAnchor; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); while (hItem != hNewItem) { tvItem.hItem = hItem; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); hItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, flags, hItem); } } } } } } } if ((wParam & OS.MK_SHIFT) == 0) hAnchor = hNewItem; /* Issue notification */ if (!gestureCompleted) { tvItem.hItem = hNewItem; tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); Event event = new Event (); event.item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); postEvent (SWT.Selection, event); } gestureCompleted = false; /* * Feature in Windows. Inside WM_LBUTTONDOWN and WM_RBUTTONDOWN, * the widget starts a modal loop to determine if the user wants * to begin a drag/drop operation or marquee select. Unfortunately, * this modal loop eats the corresponding mouse up. The fix is to * detect the cases when the modal loop has eaten the mouse up and * issue a fake mouse up. */ if (dragStarted) { sendDragEvent (1, OS.GET_X_LPARAM (lParam), OS.GET_Y_LPARAM (lParam)); } else { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_DISABLEDRAGDROP) == 0) { sendMouseEvent (SWT.MouseUp, 1, handle, OS.WM_LBUTTONUP, wParam, lParam); } } dragStarted = false; return new LRESULT (code); } LRESULT WM_MOUSEMOVE (int /*long*/ wParam, int /*long*/ lParam) { Display display = this.display; LRESULT result = super.WM_MOUSEMOVE (wParam, lParam); if (result != null) return result; if (itemToolTipHandle != 0) { /* * Bug in Windows. On some machines that do not have XBUTTONs, * the MK_XBUTTON1 and OS.MK_XBUTTON2 bits are sometimes set, * causing mouse capture to become stuck. The fix is to test * for the extra buttons only when they exist. */ int mask = OS.MK_LBUTTON | OS.MK_MBUTTON | OS.MK_RBUTTON; if (display.xMouse) mask |= OS.MK_XBUTTON1 | OS.MK_XBUTTON2; if ((wParam & mask) == 0) { int x = OS.GET_X_LPARAM (lParam); int y = OS.GET_Y_LPARAM (lParam); int [] index = new int [1]; TreeItem [] item = new TreeItem [1]; RECT [] cellRect = new RECT [1], itemRect = new RECT [1]; if (findCell (x, y, item, index, cellRect, itemRect)) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; lpti.hwnd = handle; lpti.uId = handle; lpti.uFlags = OS.TTF_SUBCLASS | OS.TTF_TRANSPARENT; lpti.left = cellRect [0].left; lpti.top = cellRect [0].top; lpti.right = cellRect [0].right; lpti.bottom = cellRect [0].bottom; OS.SendMessage (itemToolTipHandle, OS.TTM_NEWTOOLRECT, 0, lpti); } } } return result; } LRESULT WM_MOVE (int /*long*/ wParam, int /*long*/ lParam) { if (ignoreResize) return null; return super.WM_MOVE (wParam, lParam); } LRESULT WM_RBUTTONDOWN (int /*long*/ wParam, int /*long*/ lParam) { /* * Feature in Windows. The receiver uses WM_RBUTTONDOWN * to initiate a drag/drop operation depending on how the * user moves the mouse. If the user clicks the right button, * without moving the mouse, the tree consumes the corresponding * WM_RBUTTONUP. The fix is to avoid calling the window proc for * the tree. */ Display display = this.display; display.captureChanged = false; if (!sendMouseEvent (SWT.MouseDown, 3, handle, OS.WM_RBUTTONDOWN, wParam, lParam)) { if (!display.captureChanged && !isDisposed ()) { if (OS.GetCapture () != handle) OS.SetCapture (handle); } return LRESULT.ZERO; } /* * This code is intentionally commented. */ // if (OS.GetCapture () != handle) OS.SetCapture (handle); setFocus (); /* * Feature in Windows. When the user selects a tree item * with the right mouse button, the item remains selected * only as long as the user does not release or move the * mouse. As soon as this happens, the selection snaps * back to the previous selection. This behavior can be * observed in the Explorer but is not instantly apparent * because the Explorer explicitly sets the selection when * the user chooses a menu item. If the user cancels the * menu, the selection snaps back. The fix is to avoid * calling the window proc and do the selection ourselves. * This behavior is consistent with the table. */ TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = OS.GET_X_LPARAM (lParam); lpht.y = OS.GET_Y_LPARAM (lParam); OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem != 0) { int flags = OS.TVHT_ONITEMICON | OS.TVHT_ONITEMLABEL; if ((style & SWT.FULL_SELECTION) != 0 || (lpht.flags & flags) != 0) { if ((wParam & (OS.MK_CONTROL | OS.MK_SHIFT)) == 0) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.hItem = lpht.hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); if ((tvItem.state & OS.TVIS_SELECTED) == 0) { ignoreSelect = true; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, 0); ignoreSelect = false; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, lpht.hItem); } } } } return LRESULT.ZERO; } LRESULT WM_PAINT (int /*long*/ wParam, int /*long*/ lParam) { if (shrink && !ignoreShrink) { /* Resize the item array to fit the last item */ int count = items.length - 1; while (count >= 0) { if (items [count] != null) break; --count; } count++; if (items.length > 4 && items.length - count > 3) { int length = Math.max (4, (count + 3) / 4 * 4); TreeItem [] newItems = new TreeItem [length]; System.arraycopy (items, 0, newItems, 0, count); items = newItems; } shrink = false; } if ((style & SWT.DOUBLE_BUFFERED) != 0 || findImageControl () != null) { boolean doubleBuffer = true; if (EXPLORER_THEME) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { int exStyle = (int)/*64*/OS.SendMessage (handle, OS.TVM_GETEXTENDEDSTYLE, 0, 0); if ((exStyle & OS.TVS_EX_DOUBLEBUFFER) != 0) doubleBuffer = false; } } if (doubleBuffer) { GC gc = null; int /*long*/ paintDC = 0; PAINTSTRUCT ps = new PAINTSTRUCT (); boolean hooksPaint = hooks (SWT.Paint); if (hooksPaint) { GCData data = new GCData (); data.ps = ps; data.hwnd = handle; gc = GC.win32_new (this, data); paintDC = gc.handle; } else { paintDC = OS.BeginPaint (handle, ps); } int width = ps.right - ps.left; int height = ps.bottom - ps.top; if (width != 0 && height != 0) { int /*long*/ hDC = OS.CreateCompatibleDC (paintDC); POINT lpPoint1 = new POINT (), lpPoint2 = new POINT (); OS.SetWindowOrgEx (hDC, ps.left, ps.top, lpPoint1); OS.SetBrushOrgEx (hDC, ps.left, ps.top, lpPoint2); int /*long*/ hBitmap = OS.CreateCompatibleBitmap (paintDC, width, height); int /*long*/ hOldBitmap = OS.SelectObject (hDC, hBitmap); RECT rect = new RECT (); OS.SetRect (rect, ps.left, ps.top, ps.right, ps.bottom); drawBackground (hDC, rect); callWindowProc (handle, OS.WM_PAINT, hDC, 0); OS.SetWindowOrgEx (hDC, lpPoint1.x, lpPoint1.y, null); OS.SetBrushOrgEx (hDC, lpPoint2.x, lpPoint2.y, null); OS.BitBlt (paintDC, ps.left, ps.top, width, height, hDC, 0, 0, OS.SRCCOPY); OS.SelectObject (hDC, hOldBitmap); OS.DeleteObject (hBitmap); OS.DeleteObject (hDC); if (hooksPaint) { Event event = new Event (); event.gc = gc; event.x = ps.left; event.y = ps.top; event.width = ps.right - ps.left; event.height = ps.bottom - ps.top; sendEvent (SWT.Paint, event); // widget could be disposed at this point event.gc = null; } } if (hooksPaint) { gc.dispose (); } else { OS.EndPaint (handle, ps); } return LRESULT.ZERO; } } return super.WM_PAINT (wParam, lParam); } LRESULT WM_PRINTCLIENT (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_PRINTCLIENT (wParam, lParam); if (result != null) return result; /* * Feature in Windows. For some reason, when WM_PRINT is used * to capture an image of a hierarchy that contains a tree with * columns, the clipping that is used to stop the first column * from drawing on top of subsequent columns stops the first * column and the tree lines from drawing. This does not happen * during WM_PAINT. The fix is to draw without clipping and * then draw the rest of the columns on top. Since the drawing * is happening in WM_PRINTCLIENT, the redrawing is not visible. */ printClient = true; int /*long*/ code = callWindowProc (handle, OS.WM_PRINTCLIENT, wParam, lParam); printClient = false; return new LRESULT (code); } LRESULT WM_SETFOCUS (int /*long*/ wParam, int /*long*/ lParam) { /* * Bug in Windows. When a tree item that has an image * with alpha is expanded or collapsed, the area where * the image is drawn is not erased before it is drawn. * This means that the image gets darker each time. * The fix is to redraw the selection. * * Feature in Windows. When multiple item have * the TVIS_SELECTED state, Windows redraws only * the focused item in the color used to show the * selection when the tree loses or gains focus. * The fix is to force Windows to redraw the * selection when focus is gained or lost. */ boolean redraw = (style & SWT.MULTI) != 0; if (!redraw) { if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) { if (imageList != null) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { redraw = true; } } } } if (redraw) redrawSelection (); return super.WM_SETFOCUS (wParam, lParam); } LRESULT WM_SETFONT (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_SETFONT (wParam, lParam); if (result != null) return result; if (hwndHeader != 0) { /* * Bug in Windows. When a header has a sort indicator * triangle, Windows resizes the indicator based on the * size of the n-1th font. The fix is to always make * the n-1th font be the default. This makes the sort * indicator always be the default size. */ OS.SendMessage (hwndHeader, OS.WM_SETFONT, 0, lParam); OS.SendMessage (hwndHeader, OS.WM_SETFONT, wParam, lParam); } if (itemToolTipHandle != 0) { OS.SendMessage (itemToolTipHandle, OS.WM_SETFONT, wParam, lParam); } if (headerToolTipHandle != 0) { OS.SendMessage (headerToolTipHandle, OS.WM_SETFONT, wParam, lParam); } return result; } LRESULT WM_SETREDRAW (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_SETREDRAW (wParam, lParam); if (result != null) return result; /* * Bug in Windows. Under certain circumstances, when * WM_SETREDRAW is used to turn off drawing and then * TVM_GETITEMRECT is sent to get the bounds of an item * that is not inside the client area, Windows segment * faults. The fix is to call the default window proc * rather than the default tree proc. * * NOTE: This problem is intermittent and happens on * Windows Vista running under the theme manager. */ if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { int /*long*/ code = OS.DefWindowProc (handle, OS.WM_SETREDRAW, wParam, lParam); return code == 0 ? LRESULT.ZERO : new LRESULT (code); } return result; } LRESULT WM_SIZE (int /*long*/ wParam, int /*long*/ lParam) { /* * Bug in Windows. When TVS_NOHSCROLL is set when the * size of the tree is zero, the scroll bar is shown the * next time the tree resizes. The fix is to hide the * scroll bar every time the tree is resized. */ int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_NOHSCROLL) != 0) { if (!OS.IsWinCE) OS.ShowScrollBar (handle, OS.SB_HORZ, false); } /* * Bug in Windows. On Vista, when the Explorer theme * is used with a full selection tree, when the tree * is resized to be smaller, the rounded right edge * of the selected items is not drawn. The fix is the * redraw the entire tree. */ if (EXPLORER_THEME) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { if ((style & SWT.FULL_SELECTION) != 0) { OS.InvalidateRect (handle, null, false); } } } if (ignoreResize) return null; return super.WM_SIZE (wParam, lParam); } LRESULT WM_SYSCOLORCHANGE (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_SYSCOLORCHANGE (wParam, lParam); if (result != null) return result; /* * Bug in Windows. When the tree is using the explorer * theme, it does not use COLOR_WINDOW_TEXT for the * default foreground color. The fix is to explicitly * set the foreground. */ if (explorerTheme) { if (foreground == -1) setForegroundPixel (-1); } if ((style & SWT.CHECK) != 0) setCheckboxImageList (); return result; } LRESULT wmColorChild (int /*long*/ wParam, int /*long*/ lParam) { if (findImageControl () != null) { if (OS.COMCTL32_MAJOR < 6) { return super.wmColorChild (wParam, lParam); } return new LRESULT (OS.GetStockObject (OS.NULL_BRUSH)); } /* * Feature in Windows. Tree controls send WM_CTLCOLOREDIT * to allow application code to change the default colors. * This is undocumented and conflicts with TVM_SETTEXTCOLOR * and TVM_SETBKCOLOR, the documented way to do this. The * fix is to ignore WM_CTLCOLOREDIT messages from trees. */ return null; } LRESULT wmNotify (NMHDR hdr, int /*long*/ wParam, int /*long*/ lParam) { if (hdr.hwndFrom == itemToolTipHandle) { LRESULT result = wmNotifyToolTip (hdr, wParam, lParam); if (result != null) return result; } if (hdr.hwndFrom == hwndHeader) { LRESULT result = wmNotifyHeader (hdr, wParam, lParam); if (result != null) return result; } return super.wmNotify (hdr, wParam, lParam); } LRESULT wmNotifyChild (NMHDR hdr, int /*long*/ wParam, int /*long*/ lParam) { switch (hdr.code) { case OS.TVN_GETDISPINFOA: case OS.TVN_GETDISPINFOW: { NMTVDISPINFO lptvdi = new NMTVDISPINFO (); OS.MoveMemory (lptvdi, lParam, NMTVDISPINFO.sizeof); if ((style & SWT.VIRTUAL) != 0) { /* * Feature in Windows. When a new tree item is inserted * using TVM_INSERTITEM, a TVN_GETDISPINFO is sent before * TVM_INSERTITEM returns and before the item is added to * the items array. The fix is to check for null. * * NOTE: This only happens on XP with the version 6.00 of * COMCTL32.DLL. */ boolean checkVisible = true; /* * When an item is being deleted from a virtual tree, do not * allow the application to provide data for a new item that * becomes visible until the item has been removed from the * items array. Because arbitrary application code can run * during the callback, the items array might be accessed * in an inconsistent state. Rather than answering the data * right away, queue a redraw for later. */ if (!ignoreShrink) { if (items != null && lptvdi.lParam != -1) { if (items [(int)/*64*/lptvdi.lParam] != null && items [(int)/*64*/lptvdi.lParam].cached) { checkVisible = false; } } } if (checkVisible) { if (drawCount != 0 || !OS.IsWindowVisible (handle)) break; RECT itemRect = new RECT (); if (!OS.TreeView_GetItemRect (handle, lptvdi.hItem, itemRect, false)) { break; } RECT rect = new RECT (); OS.GetClientRect (handle, rect); if (!OS.IntersectRect (rect, rect, itemRect)) break; if (ignoreShrink) { OS.InvalidateRect (handle, rect, true); break; } } } if (items == null) break; /* * Bug in Windows. If the lParam field of TVITEM * is changed during custom draw using TVM_SETITEM, * the lItemlParam field of the NMTVCUSTOMDRAW struct * is not updated until the next custom draw. The * fix is to query the field from the item instead * of using the struct. */ int id = (int)/*64*/lptvdi.lParam; if ((style & SWT.VIRTUAL) != 0) { if (id == -1) { TVITEM tvItem = new TVITEM (); tvItem.mask = OS.TVIF_HANDLE | OS.TVIF_PARAM; tvItem.hItem = lptvdi.hItem; OS.SendMessage (handle, OS.TVM_GETITEM, 0, tvItem); id = (int)/*64*/tvItem.lParam; } } TreeItem item = _getItem (lptvdi.hItem, id); /* * Feature in Windows. When a new tree item is inserted * using TVM_INSERTITEM, a TVN_GETDISPINFO is sent before * TVM_INSERTITEM returns and before the item is added to * the items array. The fix is to check for null. * * NOTE: This only happens on XP with the version 6.00 of * COMCTL32.DLL. * * Feature in Windows. When TVM_DELETEITEM is called with * TVI_ROOT to remove all items from a tree, under certain * circumstances, the tree sends TVN_GETDISPINFO for items * that are about to be disposed. The fix is to check for * disposed items. */ if (item == null) break; if (item.isDisposed ()) break; if (!item.cached) { if ((style & SWT.VIRTUAL) != 0) { if (!checkData (item, false)) break; } if (painted) item.cached = true; } int index = 0; if (hwndHeader != 0) { index = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, 0, 0); } if ((lptvdi.mask & OS.TVIF_TEXT) != 0) { String string = null; if (index == 0) { string = item.text; } else { String [] strings = item.strings; if (strings != null) string = strings [index]; } if (string != null) { TCHAR buffer = new TCHAR (getCodePage (), string, false); int byteCount = Math.min (buffer.length (), lptvdi.cchTextMax - 1) * TCHAR.sizeof; OS.MoveMemory (lptvdi.pszText, buffer, byteCount); OS.MoveMemory (lptvdi.pszText + byteCount, new byte [TCHAR.sizeof], TCHAR.sizeof); lptvdi.cchTextMax = Math.min (lptvdi.cchTextMax, string.length () + 1); } } if ((lptvdi.mask & (OS.TVIF_IMAGE | OS.TVIF_SELECTEDIMAGE)) != 0) { Image image = null; if (index == 0) { image = item.image; } else { Image [] images = item.images; if (images != null) image = images [index]; } lptvdi.iImage = lptvdi.iSelectedImage = OS.I_IMAGENONE; if (image != null) { lptvdi.iImage = lptvdi.iSelectedImage = imageIndex (image, index); } if (explorerTheme && OS.IsWindowEnabled (handle)) { if (findImageControl () != null) { lptvdi.iImage = lptvdi.iSelectedImage = OS.I_IMAGENONE; } } } OS.MoveMemory (lParam, lptvdi, NMTVDISPINFO.sizeof); break; } case OS.NM_CUSTOMDRAW: { if (hdr.hwndFrom == hwndHeader) break; if (hooks (SWT.MeasureItem)) { if (hwndHeader == 0) createParent (); } else { if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) { createItemToolTips (); } } if (!customDraw && findImageControl () == null) { if (OS.COMCTL32_MAJOR >= 6 && OS.IsAppThemed ()) { if (sortColumn == null || sortDirection == SWT.NONE) { break; } } } NMTVCUSTOMDRAW nmcd = new NMTVCUSTOMDRAW (); OS.MoveMemory (nmcd, lParam, NMTVCUSTOMDRAW.sizeof); switch (nmcd.dwDrawStage) { case OS.CDDS_PREPAINT: return CDDS_PREPAINT (nmcd, wParam, lParam); case OS.CDDS_ITEMPREPAINT: return CDDS_ITEMPREPAINT (nmcd, wParam, lParam); case OS.CDDS_ITEMPOSTPAINT: return CDDS_ITEMPOSTPAINT (nmcd, wParam, lParam); case OS.CDDS_POSTPAINT: return CDDS_POSTPAINT (nmcd, wParam, lParam); } break; } case OS.NM_DBLCLK: { /* * When the user double clicks on a tree item * or a line beside the item, the window proc * for the tree collapses or expand the branch. * When application code associates an action * with double clicking, then the tree expand * is unexpected and unwanted. The fix is to * avoid the operation by testing to see whether * the mouse was inside a tree item. */ if (hooks (SWT.DefaultSelection)) { POINT pt = new POINT (); int pos = OS.GetMessagePos (); OS.POINTSTOPOINT (pt, pos); OS.ScreenToClient (handle, pt); TVHITTESTINFO lpht = new TVHITTESTINFO (); lpht.x = pt.x; lpht.y = pt.y; OS.SendMessage (handle, OS.TVM_HITTEST, 0, lpht); if (lpht.hItem != 0 && (lpht.flags & OS.TVHT_ONITEM) != 0) { return LRESULT.ONE; } } break; } /* * Bug in Windows. On Vista, when TVM_SELECTITEM is called * with TVGN_CARET in order to set the selection, for some * reason, Windows deselects the previous two items that * were selected. The fix is to stop the selection from * changing on all but the item that is supposed to be * selected. */ case OS.TVN_ITEMCHANGINGA: case OS.TVN_ITEMCHANGINGW: { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { if ((style & SWT.MULTI) != 0) { if (hSelect != 0) { NMTVITEMCHANGE pnm = new NMTVITEMCHANGE (); OS.MoveMemory (pnm, lParam, NMTVITEMCHANGE.sizeof); if (hSelect == pnm.hItem) break; return LRESULT.ONE; } } } break; } case OS.TVN_SELCHANGINGA: case OS.TVN_SELCHANGINGW: { if ((style & SWT.MULTI) != 0) { if (lockSelection) { /* Save the old selection state for both items */ NMTREEVIEW treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); TVITEM tvItem = treeView.itemOld; oldSelected = (tvItem.state & OS.TVIS_SELECTED) != 0; tvItem = treeView.itemNew; newSelected = (tvItem.state & OS.TVIS_SELECTED) != 0; } } if (!ignoreSelect && !ignoreDeselect) { hAnchor = 0; if ((style & SWT.MULTI) != 0) deselectAll (); } break; } case OS.TVN_SELCHANGEDA: case OS.TVN_SELCHANGEDW: { NMTREEVIEW treeView = null; if ((style & SWT.MULTI) != 0) { if (lockSelection) { /* Restore the old selection state of both items */ if (oldSelected) { if (treeView == null) { treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); } TVITEM tvItem = treeView.itemOld; tvItem.mask = OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.state = OS.TVIS_SELECTED; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } if (!newSelected && ignoreSelect) { if (treeView == null) { treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); } TVITEM tvItem = treeView.itemNew; tvItem.mask = OS.TVIF_STATE; tvItem.stateMask = OS.TVIS_SELECTED; tvItem.state = 0; OS.SendMessage (handle, OS.TVM_SETITEM, 0, tvItem); } } } if (!ignoreSelect) { if (treeView == null) { treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); } TVITEM tvItem = treeView.itemNew; hAnchor = tvItem.hItem; Event event = new Event (); event.item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); postEvent (SWT.Selection, event); } updateScrollBar (); break; } case OS.TVN_ITEMEXPANDINGA: case OS.TVN_ITEMEXPANDINGW: { boolean runExpanded = false; if ((style & SWT.VIRTUAL) != 0) style &= ~SWT.DOUBLE_BUFFERED; if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) style &= ~SWT.DOUBLE_BUFFERED; if (findImageControl () != null && drawCount == 0 && OS.IsWindowVisible (handle)) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 0, 0); } /* * Bug in Windows. When TVM_SETINSERTMARK is used to set * an insert mark for a tree and an item is expanded or * collapsed near the insert mark, the tree does not redraw * the insert mark properly. The fix is to hide and show * the insert mark whenever an item is expanded or collapsed. */ if (hInsert != 0) { OS.SendMessage (handle, OS.TVM_SETINSERTMARK, 0, 0); } if (!ignoreExpand) { NMTREEVIEW treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); TVITEM tvItem = treeView.itemNew; /* * Feature in Windows. In some cases, TVM_ITEMEXPANDING * is sent from within TVM_DELETEITEM for the tree item * being destroyed. By the time the message is sent, * the item has already been removed from the list of * items. The fix is to check for null. */ if (items == null) break; TreeItem item = _getItem (tvItem.hItem, (int)/*64*/tvItem.lParam); if (item == null) break; Event event = new Event (); event.item = item; switch (treeView.action) { case OS.TVE_EXPAND: /* * Bug in Windows. When the numeric keypad asterisk * key is used to expand every item in the tree, Windows * sends TVN_ITEMEXPANDING to items in the tree that * have already been expanded. The fix is to detect * that the item is already expanded and ignore the * notification. */ if ((tvItem.state & OS.TVIS_EXPANDED) == 0) { sendEvent (SWT.Expand, event); if (isDisposed ()) return LRESULT.ZERO; } break; case OS.TVE_COLLAPSE: sendEvent (SWT.Collapse, event); if (isDisposed ()) return LRESULT.ZERO; break; } /* * Bug in Windows. When all of the items are deleted during * TVN_ITEMEXPANDING, Windows does not send TVN_ITEMEXPANDED. * The fix is to detect this case and run the TVN_ITEMEXPANDED * code in this method. */ int /*long*/ hFirstItem = OS.SendMessage (handle, OS.TVM_GETNEXTITEM, OS.TVGN_CHILD, tvItem.hItem); runExpanded = hFirstItem == 0; } if (!runExpanded) break; //FALL THROUGH } case OS.TVN_ITEMEXPANDEDA: case OS.TVN_ITEMEXPANDEDW: { if ((style & SWT.VIRTUAL) != 0) style |= SWT.DOUBLE_BUFFERED; if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) style |= SWT.DOUBLE_BUFFERED; if (findImageControl () != null && drawCount == 0 /*&& OS.IsWindowVisible (handle)*/) { OS.DefWindowProc (handle, OS.WM_SETREDRAW, 1, 0); OS.InvalidateRect (handle, null, true); } /* * Bug in Windows. When TVM_SETINSERTMARK is used to set * an insert mark for a tree and an item is expanded or * collapsed near the insert mark, the tree does not redraw * the insert mark properly. The fix is to hide and show * the insert mark whenever an item is expanded or collapsed. */ if (hInsert != 0) { OS.SendMessage (handle, OS.TVM_SETINSERTMARK, insertAfter ? 1 : 0, hInsert); } /* * Bug in Windows. When a tree item that has an image * with alpha is expanded or collapsed, the area where * the image is drawn is not erased before it is drawn. * This means that the image gets darker each time. * The fix is to redraw the item. */ if (!OS.IsWinCE && OS.COMCTL32_MAJOR >= 6) { if (imageList != null) { NMTREEVIEW treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); TVITEM tvItem = treeView.itemNew; if (tvItem.hItem != 0) { int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); if ((bits & OS.TVS_FULLROWSELECT) == 0) { RECT rect = new RECT (); if (OS.TreeView_GetItemRect (handle, tvItem.hItem, rect, false)) { OS.InvalidateRect (handle, rect, true); } } } } } updateScrollBar (); break; } case OS.TVN_BEGINDRAGA: case OS.TVN_BEGINDRAGW: case OS.TVN_BEGINRDRAGA: case OS.TVN_BEGINRDRAGW: { NMTREEVIEW treeView = new NMTREEVIEW (); OS.MoveMemory (treeView, lParam, NMTREEVIEW.sizeof); TVITEM tvItem = treeView.itemNew; if (tvItem.hItem != 0 && (tvItem.state & OS.TVIS_SELECTED) == 0) { hSelect = tvItem.hItem; ignoreSelect = ignoreDeselect = true; OS.SendMessage (handle, OS.TVM_SELECTITEM, OS.TVGN_CARET, tvItem.hItem); ignoreSelect = ignoreDeselect = false; hSelect = 0; } dragStarted = true; break; } case OS.NM_RECOGNIZEGESTURE: { /* * Feature in Pocket PC. The tree and table controls detect the tap * and hold gesture by default. They send a GN_CONTEXTMENU message to show * the popup menu. This default behaviour is unwanted on Pocket PC 2002 * when no menu has been set, as it still draws a red circle. The fix * is to disable this default behaviour when no menu is set by returning * TRUE when receiving the Pocket PC 2002 specific NM_RECOGNIZEGESTURE * message. */ if (OS.IsPPC) { boolean hasMenu = menu != null && !menu.isDisposed (); if (!hasMenu && !hooks (SWT.MenuDetect)) return LRESULT.ONE; } break; } case OS.GN_CONTEXTMENU: { if (OS.IsPPC) { boolean hasMenu = menu != null && !menu.isDisposed (); if (hasMenu || hooks (SWT.MenuDetect)) { NMRGINFO nmrg = new NMRGINFO (); OS.MoveMemory (nmrg, lParam, NMRGINFO.sizeof); showMenu (nmrg.x, nmrg.y); gestureCompleted = true; return LRESULT.ONE; } } break; } } return super.wmNotifyChild (hdr, wParam, lParam); } LRESULT wmNotifyHeader (NMHDR hdr, int /*long*/ wParam, int /*long*/ lParam) { /* * Feature in Windows. On NT, the automatically created * header control is created as a UNICODE window, not an * ANSI window despite the fact that the parent is created * as an ANSI window. This means that it sends UNICODE * notification messages to the parent window on NT for * no good reason. The data and size in the NMHEADER and * HDITEM structs is identical between the platforms so no * different message is actually necessary. Despite this, * Windows sends different messages. The fix is to look * for both messages, despite the platform. This works * because only one will be sent on either platform, never * both. */ switch (hdr.code) { case OS.HDN_BEGINTRACKW: case OS.HDN_BEGINTRACKA: case OS.HDN_DIVIDERDBLCLICKW: case OS.HDN_DIVIDERDBLCLICKA: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); TreeColumn column = columns [phdn.iItem]; if (column != null && !column.getResizable ()) { return LRESULT.ONE; } ignoreColumnMove = true; switch (hdr.code) { case OS.HDN_DIVIDERDBLCLICKW: case OS.HDN_DIVIDERDBLCLICKA: if (column != null) column.pack (); } break; } case OS.NM_RELEASEDCAPTURE: { if (!ignoreColumnMove) { int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); for (int i=0; i<count; i++) { TreeColumn column = columns [i]; column.updateToolTip (i); } updateImageList (); } ignoreColumnMove = false; break; } case OS.HDN_BEGINDRAG: { if (ignoreColumnMove) return LRESULT.ONE; NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); if (phdn.iItem != -1) { TreeColumn column = columns [phdn.iItem]; if (column != null && !column.getMoveable ()) { ignoreColumnMove = true; return LRESULT.ONE; } } break; } case OS.HDN_ENDDRAG: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); if (phdn.iItem != -1 && phdn.pitem != 0) { HDITEM pitem = new HDITEM (); OS.MoveMemory (pitem, phdn.pitem, HDITEM.sizeof); if ((pitem.mask & OS.HDI_ORDER) != 0 && pitem.iOrder != -1) { int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); int [] order = new int [count]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, order); int index = 0; while (index < order.length) { if (order [index] == phdn.iItem) break; index++; } if (index == order.length) index = 0; if (index == pitem.iOrder) break; int start = Math.min (index, pitem.iOrder); int end = Math.max (index, pitem.iOrder); RECT rect = new RECT (), headerRect = new RECT (); OS.GetClientRect (handle, rect); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, order [start], headerRect); rect.left = Math.max (rect.left, headerRect.left); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, order [end], headerRect); rect.right = Math.min (rect.right, headerRect.right); OS.InvalidateRect (handle, rect, true); ignoreColumnMove = false; for (int i=start; i<=end; i++) { TreeColumn column = columns [order [i]]; if (!column.isDisposed ()) { column.postEvent (SWT.Move); } } } } break; } case OS.HDN_ITEMCHANGINGW: case OS.HDN_ITEMCHANGINGA: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); if (phdn.pitem != 0) { HDITEM newItem = new HDITEM (); OS.MoveMemory (newItem, phdn.pitem, HDITEM.sizeof); if ((newItem.mask & OS.HDI_WIDTH) != 0) { RECT rect = new RECT (); OS.GetClientRect (handle, rect); HDITEM oldItem = new HDITEM (); oldItem.mask = OS.HDI_WIDTH; OS.SendMessage (hwndHeader, OS.HDM_GETITEM, phdn.iItem, oldItem); int deltaX = newItem.cxy - oldItem.cxy; RECT headerRect = new RECT (); OS.SendMessage (hwndHeader, OS.HDM_GETITEMRECT, phdn.iItem, headerRect); int gridWidth = linesVisible ? GRID_WIDTH : 0; rect.left = headerRect.right - gridWidth; int newX = rect.left + deltaX; rect.right = Math.max (rect.right, rect.left + Math.abs (deltaX)); if (explorerTheme || (findImageControl () != null || hooks (SWT.EraseItem) || hooks (SWT.PaintItem))) { OS.InvalidateRect (handle, rect, true); OS.OffsetRect (rect, deltaX, 0); OS.InvalidateRect (handle, rect, true); } else { int flags = OS.SW_INVALIDATE | OS.SW_ERASE; OS.ScrollWindowEx (handle, deltaX, 0, rect, null, 0, null, flags); } if (OS.SendMessage (hwndHeader, OS.HDM_ORDERTOINDEX, phdn.iItem, 0) != 0) { rect.left = headerRect.left; rect.right = newX; OS.InvalidateRect (handle, rect, true); } setScrollWidth (); } } break; } case OS.HDN_ITEMCHANGEDW: case OS.HDN_ITEMCHANGEDA: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); if (phdn.pitem != 0) { HDITEM pitem = new HDITEM (); OS.MoveMemory (pitem, phdn.pitem, HDITEM.sizeof); if ((pitem.mask & OS.HDI_WIDTH) != 0) { if (ignoreColumnMove) { if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0)) { int flags = OS.RDW_UPDATENOW | OS.RDW_ALLCHILDREN; OS.RedrawWindow (handle, null, 0, flags); } else { if ((style & SWT.DOUBLE_BUFFERED) == 0) { int oldStyle = style; style |= SWT.DOUBLE_BUFFERED; OS.UpdateWindow (handle); style = oldStyle; } } } TreeColumn column = columns [phdn.iItem]; if (column != null) { column.updateToolTip (phdn.iItem); column.sendEvent (SWT.Resize); if (isDisposed ()) return LRESULT.ZERO; int count = (int)/*64*/OS.SendMessage (hwndHeader, OS.HDM_GETITEMCOUNT, 0, 0); TreeColumn [] newColumns = new TreeColumn [count]; System.arraycopy (columns, 0, newColumns, 0, count); int [] order = new int [count]; OS.SendMessage (hwndHeader, OS.HDM_GETORDERARRAY, count, order); boolean moved = false; for (int i=0; i<count; i++) { TreeColumn nextColumn = newColumns [order [i]]; if (moved && !nextColumn.isDisposed ()) { nextColumn.updateToolTip (order [i]); nextColumn.sendEvent (SWT.Move); } if (nextColumn == column) moved = true; } } } setScrollWidth (); } break; } case OS.HDN_ITEMCLICKW: case OS.HDN_ITEMCLICKA: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); TreeColumn column = columns [phdn.iItem]; if (column != null) { column.postEvent (SWT.Selection); } break; } case OS.HDN_ITEMDBLCLICKW: case OS.HDN_ITEMDBLCLICKA: { NMHEADER phdn = new NMHEADER (); OS.MoveMemory (phdn, lParam, NMHEADER.sizeof); TreeColumn column = columns [phdn.iItem]; if (column != null) { column.postEvent (SWT.DefaultSelection); } break; } } return null; } LRESULT wmNotifyToolTip (NMHDR hdr, int /*long*/ wParam, int /*long*/ lParam) { if (OS.IsWinCE) return null; switch (hdr.code) { case OS.NM_CUSTOMDRAW: { NMTTCUSTOMDRAW nmcd = new NMTTCUSTOMDRAW (); OS.MoveMemory (nmcd, lParam, NMTTCUSTOMDRAW.sizeof); return wmNotifyToolTip (nmcd, lParam); } case OS.TTN_POP: { if (display.isXMouseActive ()) { Shell shell = getShell (); shell.lockToolTipControl = null; } break; } case OS.TTN_SHOW: { if (display.isXMouseActive ()) { Shell shell = getShell (); shell.lockToolTipControl = this; } int pos = OS.GetMessagePos (); POINT pt = new POINT(); OS.POINTSTOPOINT (pt, pos); OS.ScreenToClient (handle, pt); int [] index = new int [1]; TreeItem [] item = new TreeItem [1]; RECT [] cellRect = new RECT [1], itemRect = new RECT [1]; if (findCell (pt.x, pt.y, item, index, cellRect, itemRect)) { RECT toolRect = toolTipRect (itemRect [0]); OS.MapWindowPoints (handle, 0, toolRect, 2); int width = toolRect.right - toolRect.left; int height = toolRect.bottom - toolRect.top; int flags = OS.SWP_NOACTIVATE | OS.SWP_NOZORDER | OS.SWP_NOSIZE; if (hooks (SWT.MeasureItem) || hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) { flags &= ~OS.SWP_NOSIZE; } SetWindowPos (itemToolTipHandle, 0, toolRect.left, toolRect.top, width, height, flags); return LRESULT.ONE; } break; } } return null; } LRESULT wmNotifyToolTip (NMTTCUSTOMDRAW nmcd, int /*long*/ lParam) { if (OS.IsWinCE) return null; switch (nmcd.dwDrawStage) { case OS.CDDS_PREPAINT: { if (hooks (SWT.EraseItem) || hooks (SWT.PaintItem)) { //TEMPORARY CODE // nmcd.uDrawFlags |= OS.DT_CALCRECT; // OS.MoveMemory (lParam, nmcd, NMTTCUSTOMDRAW.sizeof); return new LRESULT (OS.CDRF_NOTIFYPOSTPAINT | OS.CDRF_NEWFONT); } break; } case OS.CDDS_POSTPAINT: { if (OS.SendMessage (itemToolTipHandle, OS.TTM_GETCURRENTTOOL, 0, 0) != 0) { TOOLINFO lpti = new TOOLINFO (); lpti.cbSize = TOOLINFO.sizeof; if (OS.SendMessage (itemToolTipHandle, OS.TTM_GETCURRENTTOOL, 0, lpti) != 0) { int [] index = new int [1]; TreeItem [] item = new TreeItem [1]; RECT [] cellRect = new RECT [1], itemRect = new RECT [1]; int pos = OS.GetMessagePos (); POINT pt = new POINT(); OS.POINTSTOPOINT (pt, pos); OS.ScreenToClient (handle, pt); if (findCell (pt.x, pt.y, item, index, cellRect, itemRect)) { int /*long*/ hDC = OS.GetDC (handle); int /*long*/ hFont = item [0].fontHandle (index [0]); if (hFont == -1) hFont = OS.SendMessage (handle, OS.WM_GETFONT, 0, 0); int /*long*/ oldFont = OS.SelectObject (hDC, hFont); LRESULT result = null; boolean drawForeground = true; cellRect [0] = item [0].getBounds (index [0], true, true, false, false, false, hDC); if (hooks (SWT.EraseItem)) { Event event = sendEraseItemEvent (item [0], nmcd, index [0], cellRect [0], hFont); if (isDisposed () || item [0].isDisposed ()) break; if (event.doit) { drawForeground = (event.detail & SWT.FOREGROUND) != 0; } else { drawForeground = false; } } if (drawForeground) { int nSavedDC = OS.SaveDC (nmcd.hdc); int gridWidth = getLinesVisible () ? Table.GRID_WIDTH : 0; RECT insetRect = toolTipInset (cellRect [0]); OS.SetWindowOrgEx (nmcd.hdc, insetRect.left, insetRect.top, null); GCData data = new GCData (); data.device = display; data.foreground = OS.GetTextColor (nmcd.hdc); data.background = OS.GetBkColor (nmcd.hdc); data.hFont = hFont; GC gc = GC.win32_new (nmcd.hdc, data); int x = cellRect [0].left + INSET; if (index [0] != 0) x -= gridWidth; Image image = item [0].getImage (index [0]); if (image != null || index [0] == 0) { Point size = getImageSize (); RECT imageRect = item [0].getBounds (index [0], false, true, false, false, false, hDC); if (imageList == null) size.x = imageRect.right - imageRect.left; if (image != null) { Rectangle rect = image.getBounds (); gc.drawImage (image, rect.x, rect.y, rect.width, rect.height, x, imageRect.top, size.x, size.y); x += INSET + (index [0] == 0 ? 1 : 0); } x += size.x; } else { x += INSET; } String string = item [0].getText (index [0]); if (string != null) { int flags = OS.DT_NOPREFIX | OS.DT_SINGLELINE | OS.DT_VCENTER; TreeColumn column = columns != null ? columns [index [0]] : null; if (column != null) { if ((column.style & SWT.CENTER) != 0) flags |= OS.DT_CENTER; if ((column.style & SWT.RIGHT) != 0) flags |= OS.DT_RIGHT; } TCHAR buffer = new TCHAR (getCodePage (), string, false); RECT textRect = new RECT (); OS.SetRect (textRect, x, cellRect [0].top, cellRect [0].right, cellRect [0].bottom); OS.DrawText (nmcd.hdc, buffer, buffer.length (), textRect, flags); } gc.dispose (); OS.RestoreDC (nmcd.hdc, nSavedDC); } if (hooks (SWT.PaintItem)) { itemRect [0] = item [0].getBounds (index [0], true, true, false, false, false, hDC); sendPaintItemEvent (item [0], nmcd, index[0], itemRect [0], hFont); } OS.SelectObject (hDC, oldFont); OS.ReleaseDC (handle, hDC); if (result != null) return result; } break; } } break; } } return null; } }
[ "375833274@qq.com" ]
375833274@qq.com
5b2435168c1fbcf9643da6d778226b78735f1154
5c5aea1318dd81422e244b839511191b353c60b7
/src/JJTGrammar2State.java
9f8d5ec23108ce63b46eff45ccebee37fd672f20
[]
no_license
Koriano/pedalgo
023668ae22574b8797303223d986ef9fe851ba94
e5f94edf1be1d06bd596e6bcf4cc96ea79d33c10
refs/heads/master
2023-02-11T10:40:56.404271
2020-12-18T09:43:54
2020-12-18T09:43:54
329,883,803
0
0
null
null
null
null
UTF-8
Java
false
false
3,327
java
/* Generated By:JavaCC: Do not edit this line. JJTGrammar2State.java Version 4.1d1 */ public class JJTGrammar2State { private java.util.List nodes; private java.util.List marks; private int sp; // number of nodes on stack private int mk; // current mark private boolean node_created; public JJTGrammar2State() { nodes = new java.util.ArrayList(); marks = new java.util.ArrayList(); sp = 0; mk = 0; } /* Determines whether the current node was actually closed and pushed. This should only be called in the final user action of a node scope. */ public boolean nodeCreated() { return node_created; } /* Call this to reinitialize the node stack. It is called automatically by the parser's ReInit() method. */ public void reset() { nodes.clear(); marks.clear(); sp = 0; mk = 0; } /* Returns the root node of the AST. It only makes sense to call this after a successful parse. */ public Node rootNode() { return (Node)nodes.get(0); } /* Pushes a node on to the stack. */ public void pushNode(Node n) { nodes.add(n); ++sp; } /* Returns the node on the top of the stack, and remove it from the stack. */ public Node popNode() { if (--sp < mk) { mk = ((Integer)marks.remove(marks.size()-1)).intValue(); } return (Node)nodes.remove(nodes.size()-1); } /* Returns the node currently on the top of the stack. */ public Node peekNode() { return (Node)nodes.get(nodes.size()-1); } /* Returns the number of children on the stack in the current node scope. */ public int nodeArity() { return sp - mk; } public void clearNodeScope(Node n) { while (sp > mk) { popNode(); } mk = ((Integer)marks.remove(marks.size()-1)).intValue(); } public void openNodeScope(Node n) { marks.add(new Integer(mk)); mk = sp; n.jjtOpen(); } /* A definite node is constructed from a specified number of children. That number of nodes are popped from the stack and made the children of the definite node. Then the definite node is pushed on to the stack. */ public void closeNodeScope(Node n, int num) { mk = ((Integer)marks.remove(marks.size()-1)).intValue(); while (num-- > 0) { Node c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, num); } n.jjtClose(); pushNode(n); node_created = true; } /* A conditional node is constructed if its condition is true. All the nodes that have been pushed since the node was opened are made children of the conditional node, which is then pushed on to the stack. If the condition is false the node is not constructed and they are left on the stack. */ public void closeNodeScope(Node n, boolean condition) { if (condition) { int a = nodeArity(); mk = ((Integer)marks.remove(marks.size()-1)).intValue(); while (a-- > 0) { Node c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, a); } n.jjtClose(); pushNode(n); node_created = true; } else { mk = ((Integer)marks.remove(marks.size()-1)).intValue(); node_created = false; } } } /* JavaCC - OriginalChecksum=90bfd0983d45acdda6c708ad0fb9ee0e (do not edit this line) */
[ "hamonalexandre29@gmail.com" ]
hamonalexandre29@gmail.com
3efbc4c468e4406769a38b27cebb75110ee95ef7
3cc4d7e1eafd91c994e998773875ab220fc6144b
/app/src/main/java/com/zhangzd/video/MainActivity.java
30878ec10c95b53cd8c57a7346757424955feec7
[]
no_license
amibition521/VideoPlayer
60581730fa1094b3a9f8675410bb38265cbbd8e3
e402db752dc34721bfccfb6226b2d1b57a7c081e
refs/heads/master
2022-02-24T09:16:10.699812
2019-09-24T08:17:30
2019-09-24T08:17:30
208,955,475
0
0
null
2019-09-22T03:09:31
2019-09-17T03:56:53
C
UTF-8
Java
false
false
3,003
java
package com.zhangzd.video; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.TextView; import com.yanzhenjie.permission.Action; import com.yanzhenjie.permission.AndPermission; import com.yanzhenjie.permission.runtime.Permission; import java.util.List; public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{ static { System.loadLibrary("native-lib"); } SurfaceHolder mSurfaceHolder; // final String src = "/storage/emulated/0/DCIM/Camera/e7a9c442d1cda4462fc03459d71d8b7c.mp4"; final String src = "/storage/emulated/0/tencent/QQfile_recv/disco.mp3"; // final String src = "https://ips.ifeng.com/video19.ifeng.com/video09/2018/12/07/p5749945-102-009-184237.mp4"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SurfaceView surfaceView = findViewById(R.id.surface_view); mSurfaceHolder = surfaceView.getHolder(); mSurfaceHolder.addCallback(this); final TextView textView = findViewById(R.id.tv2); textView.setMovementMethod(ScrollingMovementMethod.getInstance()); final TextView textView1 = findViewById(R.id.tv1); textView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AndPermission.with(MainActivity.this) .runtime() .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE,Permission.RECORD_AUDIO) .onGranted(new Action<List<String>>() { @Override public void onAction(List<String> data) { // avioreading(src); playAudio(src); } }) .onDenied(new Action<List<String>>() { @Override public void onAction(List<String> data) { } }).start(); } }); } public native int avcodecinfo(); public native int avioreading(String src); public native int sysloginit(); public native int play(Object surface, String src); public native int playAudio(String url); public native int stopAudio(); @Override public void surfaceCreated(SurfaceHolder holder) { mSurfaceHolder = holder; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }
[ "zhangzd@ifeng.com" ]
zhangzd@ifeng.com
d33136097061cc1b3d6b4d9b12e2413cadf68092
a73df0dc7ae50ee6cf1e14611ef6db20a6eef10e
/app/src/main/java/com/shidonghui/mymagic/request/LiveDetailsRequest.java
a0cba314bd1ca3f1d05974a62b025b613604ec86
[]
no_license
ZHANGKUN0917/MyMagic
a4143aad380e029d20f2d798d2217936777df38e
60966ba16eb47f11924e661481573d005c9f5efa
refs/heads/master
2020-06-17T00:32:44.189831
2019-07-08T10:15:12
2019-07-08T10:15:12
195,732,731
0
0
null
null
null
null
UTF-8
Java
false
false
250
java
package com.shidonghui.mymagic.request; /** * @author ZhangKun * @create 2019/6/19 * @Describe */ public class LiveDetailsRequest { private String liveId; public LiveDetailsRequest(String liveId) { this.liveId = liveId; } }
[ "zhangkun917@163.com" ]
zhangkun917@163.com
86b28135c1cba4ac1e93aed43b09e841378f2e70
d7d7b0c25a923a699ffa579e1bab546435443302
/NGServer/Invoker/src/main/java/org/Invoker/rpc/protocol/SpringMVC.java
e9283ef02cccd7e8ca5ed8498e0bcb751aefe2e9
[]
no_license
github188/test-3
9cd2417319161a014df8b54aa68579843ade8885
92c8b20ba19185fca1e0293fe7208102b338a9ca
refs/heads/master
2020-03-15T09:36:37.329325
2017-12-18T02:40:21
2017-12-18T02:40:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,460
java
package org.Invoker.rpc.protocol; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc public class SpringMVC extends WebMvcConfigurerAdapter { // private nari.Logger.Logger logger = LoggerManager.getLogger(this.getClass()); /** * 非必须 */ @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable("mvcServlet"); } //配置html等的方法 @Override public void configureViewResolvers(ViewResolverRegistry registry){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/"); viewResolver.setSuffix(".html"); viewResolver.setViewClass(InternalResourceView.class); registry.viewResolver(viewResolver); } @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addWebRequestInterceptor(new WebRequestInterceptor() { // // @Override // public void preHandle(WebRequest arg0) throws Exception { // logger.info("1"); // } // // @Override // public void postHandle(WebRequest arg0, ModelMap arg1) throws Exception { // logger.info("2"); // } // // @Override // public void afterCompletion(WebRequest arg0, Exception arg1) throws Exception { // logger.info("3"); // } // }); } /** * 如果项目的一些资源文件放在/WEB-INF/resources/下面 * 在浏览器访问的地址就是类似:http://host:port/projectName/WEB-INF/resources/xxx.css * 但是加了如下定义之后就可以这样访问: * http://host:port/projectName/resources/xxx.css * 非必须 */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { // registry.addResourceHandler("/resources").addResourceLocations("classpath:/resources/"); } }
[ "645236219@qq.com" ]
645236219@qq.com
c78598ccddc3fc5a1409be2138a75d94829f279a
07c473a7754057e99e6c81b00172b9a1a43c0e96
/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/cpp/CcInfoApi.java
54238d0d8279967a25e3a65c1140bc2b4e1c30bd
[ "Apache-2.0" ]
permissive
chenshuo/bazel
ffd3f37331db1ce5979f43aa3d27b96a6efcd1a2
c2ba4a08a788097297da81b58e2fb9ffdb22a581
refs/heads/master
2020-04-29T20:13:31.491356
2019-03-18T21:51:45
2019-03-18T21:53:24
176,378,348
3
0
Apache-2.0
2019-03-18T22:18:32
2019-03-18T22:18:32
null
UTF-8
Java
false
false
3,950
java
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.cpp; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.skylarkbuildapi.ProviderApi; import com.google.devtools.build.lib.skylarkbuildapi.StructApi; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.ParamType; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkConstructor; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory; import com.google.devtools.build.lib.syntax.Environment; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.Runtime.NoneType; /** Wrapper for every C++ compilation and linking provider. */ @SkylarkModule( name = "CcInfo", category = SkylarkModuleCategory.PROVIDER, doc = "A provider containing information for C++ compilation and linking.") public interface CcInfoApi extends StructApi { String NAME = "CcInfo"; @SkylarkCallable( name = "compilation_context", doc = "Returns the <code>CompilationContext</code>", structField = true) CcCompilationContextApi getCcCompilationContext(); @SkylarkCallable( name = "linking_context", doc = "Returns the <code>LinkingContext</code>", structField = true) CcLinkingContextApi getCcLinkingContext(); /** The provider implementing this can construct the CcInfo provider. */ @SkylarkModule( name = "CcProvider", doc = "A provider for compilation and linking of C++. This " + "is also a marking provider telling C++ rules that they can depend on the rule " + "with this provider. If it is not intended for the rule to be depended on by C++, " + "the rule should wrap the CcInfo in some other provider.") interface Provider extends ProviderApi { @SkylarkCallable( name = NAME, doc = "The <code>CcInfo</code> constructor.", useLocation = true, useEnvironment = true, parameters = { @Param( name = "compilation_context", doc = "The <code>CompilationContext</code>.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = CcCompilationContextApi.class), @ParamType(type = NoneType.class) }), @Param( name = "linking_context", doc = "The <code>LinkingContext</code>.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = CcLinkingContextApi.class), @ParamType(type = NoneType.class) }) }, selfCall = true) @SkylarkConstructor(objectType = CcInfoApi.class, receiverNameForDoc = NAME) CcInfoApi createInfo( Object ccCompilationContext, Object ccLinkingInfo, Location location, Environment environment) throws EvalException; } }
[ "copybara-piper@google.com" ]
copybara-piper@google.com
dacb27fe9b406ab57ade864242ce30532cef1149
885f5580c7de1a9807152e7a602e5c6417a15471
/SyscortRazorpayNewCards/src/test/java/com/syscort/pages/EcomTestPage.java
69e20c0f0acba87645c707609a298a5e21764414
[]
no_license
rajvpatil5/Eclipse-New-Version
7bf12468d6c0915e5574385de9b82d5286349517
4544e804c2f890054614b659ea40bb7fe91c9082
refs/heads/main
2023-05-15T03:26:36.451400
2021-06-10T09:23:33
2021-06-10T09:23:33
361,465,579
0
0
null
null
null
null
UTF-8
Java
false
false
1,214
java
package com.syscort.pages; import org.openqa.selenium.By; public class EcomTestPage { public static By textEmail = By.xpath("//input[@name='email']"); public static By textPhone = By.xpath("//input[@name='phone']"); public static By textAmount = By.xpath("//*[@id='form-section']/form/div[1]/div[3]/div/div[2]/div[1]/input"); public static By submitBtn = By.xpath("//button[@type='submit']"); // Card Modal public static By checkoutFrame = By.xpath("//iframe[@class='razorpay-checkout-frame']"); public static By cardBtn = By.xpath("//button[@method='card']"); public static By cardNumber = By.xpath("//input[@id='card_number']"); public static By cardExpiry = By.xpath("//input[@id='card_expiry']"); public static By cardName = By.xpath("//input[@id='card_name']"); public static By cardCvv = By.xpath("//input[@id='card_cvv']"); public static By payBtn = By.xpath("//span[@id='footer-cta']"); public static By ipin = By.xpath("//input[@id='txtipin']"); public static By SubmitPayBtn = By.xpath("//input[@id='btnverify']"); public static By errorMessage = By.xpath("//div[@id='fd-t']"); public static By paymentID = By.xpath(" //*[@id='status-section-container']/div[3]/div[5]/div/div[1]"); }
[ "rajvpatil5@gmail.com" ]
rajvpatil5@gmail.com
431543436722e9d5ace0303494fda960930c9b8c
27511a2f9b0abe76e3fcef6d70e66647dd15da96
/src/com/instagram/ui/widget/bannertoast/b.java
dbe342da34ba74294254d891f1637fdacd9493ad
[]
no_license
biaolv/com.instagram.android
7edde43d5a909ae2563cf104acfc6891f2a39ebe
3fcd3db2c3823a6d29a31ec0f6abcf5ceca995de
refs/heads/master
2022-05-09T15:05:05.412227
2016-07-21T03:48:36
2016-07-21T03:48:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package com.instagram.ui.widget.bannertoast; import com.facebook.j.n; final class b implements Runnable { b(BannerToast paramBannerToast, n paramn) {} public final void run() { a.b(0.0D); } } /* Location: * Qualified Name: com.instagram.ui.widget.bannertoast.b * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
7ac7423ed2decdcbeb0a481e48492e7a573b7ec4
17c5a088d4dbfdf986631bacc62ff417949ed78b
/CRM/src/main/java/workbench/entity/ContactsRemark.java
76a133a9db80b4fea82391569c30ccad810c72cf
[]
no_license
judy19981229/IdeaProjects
72e7755f2bf5891abc37f574e576317ce17fb1d4
d3df2db8675cd583126a7b1377f8a65314dd1d0b
refs/heads/master
2023-04-15T12:50:56.593891
2021-04-27T02:14:50
2021-04-27T02:14:50
356,805,074
0
0
null
null
null
null
UTF-8
Java
false
false
1,294
java
package workbench.entity; public class ContactsRemark { private String id; private String noteContent; private String createTime; private String createBy; private String editTime; private String editBy; private String editFlag; private String contactsId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNoteContent() { return noteContent; } public void setNoteContent(String noteContent) { this.noteContent = noteContent; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getEditTime() { return editTime; } public void setEditTime(String editTime) { this.editTime = editTime; } public String getEditBy() { return editBy; } public void setEditBy(String editBy) { this.editBy = editBy; } public String getEditFlag() { return editFlag; } public void setEditFlag(String editFlag) { this.editFlag = editFlag; } public String getContactsId() { return contactsId; } public void setContactsId(String contactsId) { this.contactsId = contactsId; } }
[ "1264284228@qq.com" ]
1264284228@qq.com
3fde825ecc4b4f465b4d8f4faf4fde76ccf5df3a
d394411d9dd74e03a597c2e7f8076c382913b418
/src/main/java/ra/net/NetServerApplication.java
407bb05df5301df30972c40f1e28027ddc839a92
[ "MIT" ]
permissive
EastLu/RA
2d75d734d24ca06b0cc533a964566d145cb09d6f
44c0b3967dd7077dbd005d076117c68b86e6bf11
refs/heads/main
2023-06-20T23:09:02.745214
2021-07-27T07:44:54
2021-07-27T07:44:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,696
java
package ra.net; import java.io.IOException; import java.net.ServerSocket; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.naming.NamingException; import ra.net.nio.DataNetService; import ra.net.nio.PackageHandleOutput; import ra.net.processor.CommandProcessorListener; import ra.net.processor.CommandProcessorProvider; import ra.net.processor.DataNetCommandProvider; import ra.net.processor.NetCommandProvider; import ra.net.request.Request; import ra.util.annotation.Configuration; import ra.util.annotation.ServerApplication; /** * {@link NetService}, {@link DataNetService} manager. * * @author Ray Li */ public class NetServerApplication implements NetServiceProvider { private static NetServerApplication instance; private static final String NET = "Net"; private ServerSocket serverSocket; private Map<String, Serviceable<?>> servicePool; private Map<String, User> userList; private MessageSender sender; private ExecutorService threadPool; private ServerConfiguration configuration; /** Initialize. */ public NetServerApplication() { servicePool = new HashMap<>(); userList = new ConcurrentHashMap<>(); sender = new MessageSender(); sender.setNetServiceProvider(this); } /** * User offline. * * @param index Socket index */ public void removeUser(int index) { User user = userList.get("" + index); if (user != null) { user.close(); userList.remove("" + index); } } /** * Put the user into user pool. * * @param index index * @param listener listener */ public void putUser(int index, User listener) { userList.put("" + index, listener); } /** * Put {@link NetService}. * * @param index service index * @param service service * @throws NamingException The key already exists */ public void putNetService(int index, NetService service) throws NamingException { this.putService(NET + index, service); } /** * Put DataNetService. * * @param index service index * @param service service * @throws NamingException NamingException */ public void putDataNetService(int index, DataNetService service) throws NamingException { this.putService(NET + index, service); } /** * Put Serviceable. * * @param index index * @param service service * @throws NamingException NamingException */ public void putService(int index, Serviceable<?> service) throws NamingException { this.putService(NET + index, service); } /** * Put Serviceable. * * @param key key * @param service service * @throws NamingException NamingException */ public void putService(String key, Serviceable<?> service) throws NamingException { if (servicePool.containsKey(key)) { throw new NamingException("Naming repeat, key = " + key); } servicePool.put(key, service); } @Override public Serviceable<?> getService(int index) { return servicePool.get(NET + index); } /** * Returns service. * * @param key key * @return service */ public Serviceable<?> getService(String key) { return servicePool.get(key); } /** * Returns service. * * @param index specify index * @return NetService */ public NetService getNetService(int index) { return (NetService) servicePool.get(NET + index); } /** * Returns service. * * @param index specify index * @return DataNetService */ public DataNetService getDataNetService(int index) { return (DataNetService) servicePool.get(NET + index); } /** * Returns user. * * @param index specify index * @return User */ public User getUser(int index) { return userList.get("" + index); } @Override public Map<String, User> getUsers() { return userList; } /** * Returns message sender. * * @return MessageSender */ public MessageSender getMessageSender() { return sender; } /** * Returns server configuration. * * @return ServerConfiguration */ public ServerConfiguration getConfiguration() { return configuration; } /** * Get current application. * * @return NetServerApplication */ public static NetServerApplication getApplication() { return instance; } /** * Run server. * * @param source source * @param args args */ @SuppressWarnings("resource") public static void run(Class<?> source, String... args) { if (!source.isAnnotationPresent(ServerApplication.class)) { throw new RuntimeException("Source '" + source + "' is not annotation @ServerApplication."); } NetServerApplication application = new NetServerApplication(); ServerConfiguration configuration = null; String path = null; if (source.isAnnotationPresent(Configuration.class)) { Configuration configurationAnnotation = source.getAnnotation(Configuration.class); path = configurationAnnotation.value(); } else { throw new RuntimeException("Source '" + source + "' is not annotation @Configuration."); } try { configuration = new ServerConfiguration(path); } catch (IOException e) { e.printStackTrace(); } application.configuration = configuration; int poolSize = application.configuration.getPropertyAsInt("server.netservice.max-threads", 200); int port = application.configuration.getPropertyAsInt("server.port", 20000); ServerApplication annotation = source.getAnnotation(ServerApplication.class); Class<? extends CommandProcessorProvider<? extends Request>> commandProviderClass = annotation.serviceMode(); ServerSocket serverSocket = null; System.out.printf( "port=%d, poolsize=%d, commandProvider=%s\n", port, poolSize, commandProviderClass.getName()); try { serverSocket = new ServerSocket(port, poolSize); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException( "ServerSocket not initialize, port = " + port + ",poolSize=" + poolSize + ".", e); } CommandProcessorProvider<? extends Request> providerObject = null; try { providerObject = commandProviderClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "The provider class '" + commandProviderClass + "' constructor is a mismatch."); } if (NetCommandProvider.class.isAssignableFrom(commandProviderClass)) { application.runNetService(serverSocket, port, poolSize, (NetCommandProvider) providerObject); } else if (DataNetCommandProvider.class.isAssignableFrom(commandProviderClass)) { application.runNetDataService( serverSocket, port, poolSize, (DataNetCommandProvider) providerObject); } else { throw new RuntimeException( "The provider class '" + commandProviderClass + "' invalid, please use or inherit NetServiceCommandProvider, " + "DataNetServiceCommandProvider."); } instance = application; } /** * NetServerApplication initialize. * * @param serverSocket serverSocket * @param port port * @param poolSize request pool size * @param providerClass command provider */ private void runNetService( ServerSocket serverSocket, int port, int poolSize, NetCommandProvider commandProvider) { this.serverSocket = serverSocket; threadPool = Executors.newFixedThreadPool(poolSize); NetService.Builder builder = new NetService.Builder(); NetService service = null; builder .setSendExecutor(threadPool) .setSocketSoTimeout(Duration.ofSeconds(20)) .setServerSocket(serverSocket); for (int i = 1; i <= poolSize; i++) { builder.setIndex(i); service = builder.build(); service.setCommandProcessorProvider( new NetCommandProvider() { @Override public CommandProcessorListener<NetService.NetRequest> createCommand() { return commandProvider.createCommand(); } @Override public void offline(int index) { commandProvider.offline(index); removeUser(index); } }); try { putNetService(i, service); } catch (NamingException e) { e.printStackTrace(); } service.start(); } } /** * NetServerApplication initialize. * * @param serverSocket serverSocket * @param port port * @param poolSize request pool size * @param providerClass command provider */ private void runNetDataService( ServerSocket serverSocket, int port, int poolSize, DataNetCommandProvider commandProvider) { this.serverSocket = serverSocket; threadPool = Executors.newFixedThreadPool(poolSize); DataNetService.Builder builder = new DataNetService.Builder() .setSendExecutor(threadPool) .setServerSocket(serverSocket) .setCommandProcessorProvider( new DataNetCommandProvider() { @Override public CommandProcessorListener<DataNetService.DataNetRequest> createCommand() { return commandProvider.createCommand(); } @Override public void offline(int index) { commandProvider.offline(index); removeUser(index); } }) .setSocketSoTimeout(Duration.ofSeconds(60)) .setTransferListener(new PackageHandleOutput()); DataNetService service = null; for (int i = 1; i <= poolSize; i++) { builder.setIndex(i); service = builder.build(); try { putDataNetService(i, service); } catch (NamingException e) { e.printStackTrace(); } service.start(); } } /** Finish application. */ public void close() { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } threadPool.shutdownNow(); servicePool .values() .stream() .filter(service -> AutoCloseable.class.isInstance(service)) .map(AutoCloseable.class::cast) .forEach( service -> { try { service.close(); } catch (Exception e) { e.printStackTrace(); } }); userList.values().forEach(user -> user.close()); } }
[ "ray00000sina@gmail.com" ]
ray00000sina@gmail.com
76c7b25b863bffa06176387c24571eb24e5781fe
41df3f1bffbcc52a02588eeaa13b920e2aa0245e
/cloud-ribbon/src/main/java/com/cloud/config/quanJu/RibbonClientDefaultConfigrationTestConfig.java
0753b05d4bfa8bf4e65b0aabef1e891ca357d45c
[]
no_license
18895317466/cloudDemo
fe50ab49af77a14e3d224ebbe94caf908623d485
7cce32afbd271ab0895fd64a9ffa71d969c7d4b4
refs/heads/master
2020-05-16T16:54:49.163212
2019-04-29T10:01:57
2019-04-29T10:01:57
183,177,797
0
0
null
null
null
null
UTF-8
Java
false
false
1,033
java
package com.cloud.config.quanJu; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.*; import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by ouyang on 2019/4/29. */ @RibbonClients(defaultConfiguration = DefaultRibbonConfig.class) public class RibbonClientDefaultConfigrationTestConfig { public static class BazServiceList extends ConfigurationBasedServerList{ public BazServiceList(IClientConfig config){ super.initWithNiwsConfig(config); } } } @Configuration class DefaultRibbonConfig{ @Bean public IRule ribbonRule(){ return new BestAvailableRule(); } @Bean public IPing ribbonPing(){ return new PingUrl(); } @Bean public ServerListSubsetFilter serverListSubsetFilter(){ ServerListSubsetFilter filter= new ServerListSubsetFilter(); return filter; } }
[ "370480765@qq.com" ]
370480765@qq.com
a15ea92b473f96722da365c549d29c5ad2573cf1
0e894d0257811bf883e0d46fcfbb5d08f100637e
/src/main/java/com/enginemobi/bssuite/domain/Promotion.java
464ad576294b64661a3e8a93a5f1ddc145271a4b
[ "Apache-2.0" ]
permissive
pkcool/bssuite
ded01f8c015bdc23209bb97ee97be7ebbebad5a7
6771fed3c2e2bb2b318f5cc8e6edafd1b787a063
refs/heads/develop-0.3.x
2021-01-10T06:20:51.001239
2015-12-08T03:05:22
2015-12-08T03:05:22
44,002,076
6
7
null
2015-11-06T11:13:35
2015-10-10T08:32:55
Java
UTF-8
Java
false
false
3,859
java
package com.enginemobi.bssuite.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import java.time.LocalDate; import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Promotion. */ @Entity @Table(name = "promotion") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "promotion") public class Promotion implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Column(name = "code", nullable = false) private String code; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "start_date") private LocalDate startDate; @Column(name = "end_date") private LocalDate endDate; @Column(name = "cost") private Double cost; @Column(name = "income") private Double income; @Column(name = "expense") private Double expense; @Column(name = "date_created") private LocalDate dateCreated; @ManyToOne @JoinColumn(name = "store_id") private Store store; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } 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 LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public Double getCost() { return cost; } public void setCost(Double cost) { this.cost = cost; } public Double getIncome() { return income; } public void setIncome(Double income) { this.income = income; } public Double getExpense() { return expense; } public void setExpense(Double expense) { this.expense = expense; } public LocalDate getDateCreated() { return dateCreated; } public void setDateCreated(LocalDate dateCreated) { this.dateCreated = dateCreated; } public Store getStore() { return store; } public void setStore(Store store) { this.store = store; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Promotion promotion = (Promotion) o; return Objects.equals(id, promotion.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Promotion{" + "id=" + id + ", code='" + code + "'" + ", name='" + name + "'" + ", description='" + description + "'" + ", startDate='" + startDate + "'" + ", endDate='" + endDate + "'" + ", cost='" + cost + "'" + ", income='" + income + "'" + ", expense='" + expense + "'" + ", dateCreated='" + dateCreated + "'" + '}'; } }
[ "smaxllimit@gmail.com" ]
smaxllimit@gmail.com
95b4dce096b3b4297de954dec9d7c4c1dd3b5ebd
368c663f8d031f576e3add37dde8e9052dc628d8
/java/GBOL/trunk/src/org/gmod/gbol/simpleObject/generated/AbstractPhenotypeCVTerm.java
6ab8ef67fd45e97cab3dc89d791cff834f422197
[]
no_license
mahmoudimus/obo-edit
494a588830758ddbd7cf43d2e70550ddd542cb1b
61c146958fd7d0ba7f78cda77f56d45849897b3e
refs/heads/master
2022-01-31T22:59:21.316185
2014-03-20T17:05:47
2014-03-20T17:05:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,304
java
package org.gmod.gbol.simpleObject.generated; import org.gmod.gbol.simpleObject.*; /** * PhenotypeCVTerm generated by hbm2java */ public abstract class AbstractPhenotypeCVTerm extends AbstractSimpleObject implements java.io.Serializable { private Integer phenotypeCVTermId; private CVTerm cvterm; private Phenotype phenotype; private int rank; public AbstractPhenotypeCVTerm() { } public AbstractPhenotypeCVTerm(CVTerm cvterm, Phenotype phenotype, int rank) { this.cvterm = cvterm; this.phenotype = phenotype; this.rank = rank; } public Integer getPhenotypeCVTermId() { return this.phenotypeCVTermId; } public void setPhenotypeCVTermId(Integer phenotypeCVTermId) { this.phenotypeCVTermId = phenotypeCVTermId; } public CVTerm getCvterm() { return this.cvterm; } public void setCvterm(CVTerm cvterm) { this.cvterm = cvterm; } public Phenotype getPhenotype() { return this.phenotype; } public void setPhenotype(Phenotype phenotype) { this.phenotype = phenotype; } public int getRank() { return this.rank; } public void setRank(int rank) { this.rank = rank; } public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof AbstractPhenotypeCVTerm) ) return false; AbstractPhenotypeCVTerm castOther = ( AbstractPhenotypeCVTerm ) other; return ( (this.getCvterm()==castOther.getCvterm()) || ( this.getCvterm()!=null && castOther.getCvterm()!=null && this.getCvterm().equals(castOther.getCvterm()) ) ) && ( (this.getPhenotype()==castOther.getPhenotype()) || ( this.getPhenotype()!=null && castOther.getPhenotype()!=null && this.getPhenotype().equals(castOther.getPhenotype()) ) ) && (this.getRank()==castOther.getRank()); } public int hashCode() { int result = 17; result = 37 * result + ( getCvterm() == null ? 0 : this.getCvterm().hashCode() ); result = 37 * result + ( getPhenotype() == null ? 0 : this.getPhenotype().hashCode() ); result = 37 * result + this.getRank(); return result; } }
[ "yostinso@users.noreply.github.com" ]
yostinso@users.noreply.github.com
d9fc8d75d9b6722cd232c146736d6feb8e77741e
e6e16791661f6883e043721c243bc32f2a13c88d
/src/main/java/cn/diffpi/kit/video/BuilderUtil.java
c2e121f5c1515df39fe77d0174b6a6c0e49f18cd
[]
no_license
SuperHeYilin/hi-video-resty
5be7db63c964c8024d9b998ff776075dfada68ab
eddfa90b3045ab96a2aed4cd9944bbc6ea6df272
refs/heads/master
2022-09-03T10:49:25.995353
2020-04-21T09:11:25
2020-04-21T09:11:25
141,672,804
0
0
null
2022-09-01T22:48:01
2018-07-20T06:30:30
Java
UTF-8
Java
false
false
548
java
package cn.diffpi.kit.video; /** * 打开文件的工具类 */ public class BuilderUtil { private BuilderUtil() { } public static ProcessBuilder getInstance() { return BuilderSingleton.INSTANCE.getInstance(); } private static enum BuilderSingleton { INSTANCE; private ProcessBuilder processBuilder; private BuilderSingleton() { processBuilder = new ProcessBuilder(); } public ProcessBuilder getInstance() { return processBuilder; } } }
[ "240957830@qq.com" ]
240957830@qq.com
f0d0eca28ad7ad70db19272cb9a6526439f3e8a7
bfa4af4d96cb65540bc68796ac677fb5d8d4749b
/Sager/ons-sager-read/src/test/java/br/org/ons/sager/read/web/rest/InstalacaoEventInsHandlerTest.java
4b9f5d9fd3c8e3562e98413ee0fd3b9793025e33
[]
no_license
MbqIIB/Project-Java-Microservices
4e538d3ac808a4da2bd4c6358da5efd22cce916b
77ada2cda0d16d5d737630f22c1b522ea72c0a40
refs/heads/master
2021-01-22T15:16:11.100497
2017-02-09T21:05:01
2017-02-09T21:05:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,831
java
package br.org.ons.sager.read.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.time.LocalTime; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.ArrayList; import java.util.Date; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.jayway.jsonpath.JsonPath; import br.org.ons.geracao.cadastro.Agente; import br.org.ons.geracao.cadastro.EquipamentoInterligacaoInternacional; import br.org.ons.geracao.cadastro.Instalacao; import br.org.ons.geracao.cadastro.InterligacaoInternacional; import br.org.ons.geracao.cadastro.TipoInstalacao; import br.org.ons.geracao.cadastro.TipoUsina; import br.org.ons.geracao.cadastro.UnidadeGeradora; import br.org.ons.geracao.cadastro.Usina; import br.org.ons.geracao.evento.Comentario; import br.org.ons.geracao.evento.ComentarioSituacao; import br.org.ons.geracao.evento.Disponibilidade; import br.org.ons.geracao.evento.EventoMudancaEstadoOperativo; import br.org.ons.geracao.evento.OrigemComentario; import br.org.ons.geracao.evento.StatusEvento; import br.org.ons.geracao.evento.TipoComentario; import br.org.ons.geracao.evento.TipoDisponibilidade; import br.org.ons.geracao.evento.franquia.Franquia; import br.org.ons.geracao.evento.taxa.Taxa; import br.org.ons.geracao.evento.taxa.TipoTaxa; import br.org.ons.geracao.modelagem.Periodo; import br.org.ons.geracao.evento.ComentarioSituacao.StatusObjeto; import br.org.ons.geracao.evento.ComentarioSituacao.TipoObjeto; import br.org.ons.platform.common.EventMessage; import br.org.ons.platform.common.EventMetadata; import br.org.ons.sager.instalacao.event.DisponibilidadesCalculadasEvent; import br.org.ons.sager.instalacao.event.EquipamentoCadastradoEvent; import br.org.ons.sager.instalacao.event.InstalacaoCadastradaEvent; import br.org.ons.sager.read.OnsSagerReadApp; import br.org.ons.sager.read.domain.Equipamento; import br.org.ons.sager.read.domain.Evento; import br.org.ons.sager.read.domain.Interligacoes; import br.org.ons.sager.read.domain.QInterligacoes; import br.org.ons.sager.read.domain.QUsinas; import br.org.ons.sager.read.domain.Usinas; import br.org.ons.sager.read.repository.EventoRepository; import br.org.ons.sager.read.repository.InterligacoesRepository; import br.org.ons.sager.read.repository.UsinasRepository; import br.org.ons.sager.read.service.EventoService; import br.org.ons.sager.read.service.InstalacaoEventHandler; /** * EventHandler que recebe eventos publicados no barramento * e atualiza o repositório de dados de leitura */ @RunWith(SpringRunner.class) @SpringBootTest(classes = OnsSagerReadApp.class) public class InstalacaoEventInsHandlerTest { @Inject private UsinasRepository usinasRepository; @Inject private InterligacoesRepository interligacoesRepository; private InstalacaoEventHandler eventHandler; @PostConstruct public void setup() { eventHandler = new InstalacaoEventHandler(usinasRepository,interligacoesRepository); } @Before public void initTest() { usinasRepository.deleteAll(); interligacoesRepository.deleteAll(); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("cnos", "")); Date data = new Date("2016/11/28 03:00:00"); BigDecimal bg = new BigDecimal(12); Periodo periodoValidade = new Periodo(); periodoValidade.setDataFim(data); periodoValidade.setDataInicio(data); Franquia franquia = new Franquia(); franquia.setCodigo("cod01"); franquia.setIdEquipamento("idEquip01"); franquia.setPeriodoValidade(periodoValidade); franquia.setQtMinutosServicoParaUso(12); franquia.setValorDisponivel(10); franquia.setValorLimite(13); franquia.setVersao("01"); List<Franquia> franquias = new ArrayList<>(); franquias.add(franquia); Equipamento equipamento = new Equipamento(); equipamento.setId("id01"); equipamento.setNome("nom01"); equipamento.setParticipacao(bg); equipamento.setValorPotencia(bg); Usinas usina1 = new Usinas(); usina1.setId("idUsina01"); usina1.setNome("NomeUsina01"); usina1.setTipo_id("tipoUsina"); List<Equipamento> equipamentos = new ArrayList<>(); equipamentos.add(equipamento); Interligacoes inters = new Interligacoes(); inters.setEquipamentos(equipamentos); inters.setId("idInter01"); inters.setIdagente("idAgente01"); usinasRepository.save(usina1); interligacoesRepository.save(inters); } @Test public void cadastrarEquipamentoTipoUnidadeGeradora() throws Exception { Date data = new Date("2016/11/28 03:00:00"); Periodo periodoValidade = new Periodo(); periodoValidade.setDataFim(data); periodoValidade.setDataInicio(data); Franquia franquia = new Franquia(); franquia.setCodigo("cod01"); franquia.setIdEquipamento("idEquip01"); franquia.setPeriodoValidade(periodoValidade); franquia.setQtMinutosServicoParaUso(12); franquia.setValorDisponivel(10); franquia.setValorLimite(13); franquia.setVersao("01"); List<Franquia> franquias = new ArrayList<>(); franquias.add(franquia); UnidadeGeradora equipamento = new UnidadeGeradora(); equipamento.setDataDesativacao(data); equipamento.setDataEventoEOC(data); equipamento.setDataImplantacao(data); equipamento.setDataRenovacaoProrrogacaoConcessao(data); equipamento.setId("id02"); equipamento.setIdInstalacao("idInstalacao01"); equipamento.setNome("nome01"); equipamento.setTipoInstalacao(TipoInstalacao.USINA); equipamento.setVersao("01"); equipamento.setFranquias(franquias); EquipamentoCadastradoEvent event = new EquipamentoCadastradoEvent(); event.setEquipamento(equipamento); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idUsina01"); EventMessage<EquipamentoCadastradoEvent> eventMessage = new EventMessage<>(); eventMessage.setEvent(event); eventMessage.setMetadata(metadata); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); } @Test public void cadastrarEquipamentoSemUnidadeGeradoraNoRepository() throws Exception { usinasRepository.deleteAll(); Date data = new Date("2016/11/28 03:00:00"); Periodo periodoValidade = new Periodo(); periodoValidade.setDataFim(data); periodoValidade.setDataInicio(data); Franquia franquia = new Franquia(); franquia.setCodigo("cod01"); franquia.setIdEquipamento("idEquip01"); franquia.setPeriodoValidade(periodoValidade); franquia.setQtMinutosServicoParaUso(12); franquia.setValorDisponivel(10); franquia.setValorLimite(13); franquia.setVersao("01"); List<Franquia> franquias = new ArrayList<>(); franquias.add(franquia); UnidadeGeradora equipamento = new UnidadeGeradora(); equipamento.setDataDesativacao(data); equipamento.setDataEventoEOC(data); equipamento.setDataImplantacao(data); equipamento.setDataRenovacaoProrrogacaoConcessao(data); equipamento.setId("id02"); equipamento.setIdInstalacao("idInstalacao01"); equipamento.setNome("nome01"); equipamento.setTipoInstalacao(TipoInstalacao.USINA); equipamento.setVersao("01"); equipamento.setFranquias(franquias); EquipamentoCadastradoEvent event = new EquipamentoCadastradoEvent(); event.setEquipamento(equipamento); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idUsina01"); EventMessage<EquipamentoCadastradoEvent> eventMessage = new EventMessage<>(); eventMessage.setEvent(event); eventMessage.setMetadata(metadata); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); } @Test public void cadastrarEquipamentoTipoEquipamentoInterligacaoInternacional() throws Exception { Date data = new Date("2016/11/28 03:00:00"); Periodo periodoValidade = new Periodo(); periodoValidade.setDataFim(data); periodoValidade.setDataInicio(data); Franquia franquia = new Franquia(); franquia.setCodigo("cod01"); franquia.setIdEquipamento("idEquip01"); franquia.setPeriodoValidade(periodoValidade); franquia.setQtMinutosServicoParaUso(12); franquia.setValorDisponivel(10); franquia.setValorLimite(13); franquia.setVersao("01"); List<Franquia> franquias = new ArrayList<>(); franquias.add(franquia); EquipamentoInterligacaoInternacional equipamento = new EquipamentoInterligacaoInternacional(); equipamento.setDataDesativacao(data); equipamento.setDataEventoEOC(data); equipamento.setDataImplantacao(data); equipamento.setDataRenovacaoProrrogacaoConcessao(data); equipamento.setId("id02"); equipamento.setIdInstalacao("idInstalacao01"); equipamento.setNome("nome01"); equipamento.setTipoInstalacao(TipoInstalacao.INTERLIGACAO_INTERNACIONAL); equipamento.setVersao("01"); equipamento.setFranquias(franquias); EquipamentoCadastradoEvent event = new EquipamentoCadastradoEvent(); event.setEquipamento(equipamento); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idInter01"); EventMessage<EquipamentoCadastradoEvent> eventMessage = new EventMessage<>(); eventMessage.setEvent(event); eventMessage.setMetadata(metadata); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); } @Test public void cadastrarEquipamentoTipoEquipamentoInterligacaoInternacionalSemRepositorio() throws Exception { interligacoesRepository.deleteAll(); Date data = new Date("2016/11/28 03:00:00"); Periodo periodoValidade = new Periodo(); periodoValidade.setDataFim(data); periodoValidade.setDataInicio(data); Franquia franquia = new Franquia(); franquia.setCodigo("cod01"); franquia.setIdEquipamento("idEquip01"); franquia.setPeriodoValidade(periodoValidade); franquia.setQtMinutosServicoParaUso(12); franquia.setValorDisponivel(10); franquia.setValorLimite(13); franquia.setVersao("01"); List<Franquia> franquias = new ArrayList<>(); franquias.add(franquia); EquipamentoInterligacaoInternacional equipamento = new EquipamentoInterligacaoInternacional(); equipamento.setDataDesativacao(data); equipamento.setDataEventoEOC(data); equipamento.setDataImplantacao(data); equipamento.setDataRenovacaoProrrogacaoConcessao(data); equipamento.setId("id02"); equipamento.setIdInstalacao("idInstalacao01"); equipamento.setNome("nome01"); equipamento.setTipoInstalacao(TipoInstalacao.INTERLIGACAO_INTERNACIONAL); equipamento.setVersao("01"); equipamento.setFranquias(franquias); EquipamentoCadastradoEvent event = new EquipamentoCadastradoEvent(); event.setEquipamento(equipamento); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idInter01"); EventMessage<EquipamentoCadastradoEvent> eventMessage = new EventMessage<>(); eventMessage.setEvent(event); eventMessage.setMetadata(metadata); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); eventHandler.handleEquipamentoCadastradoEvent(eventMessage); } @Test public void cadastrarEventoTipoUsina() throws Exception { BigDecimal bg = new BigDecimal(12); Date data = new Date("2016/11/28 03:00:00"); ComentarioSituacao comentario1 = new ComentarioSituacao(); comentario1.setDataInsercao(data); comentario1.setDescricao("Descricao"); comentario1.setOrigem(OrigemComentario.ONS); comentario1.setTipo(TipoComentario.COMENTARIO); comentario1.setDataFim(data); comentario1.setNomeObjeto("nome01"); comentario1.setStatusObjeto(StatusObjeto.FORA_OPERACAO_COMERCIAL); comentario1.setTipoObjeto(TipoObjeto.USINA); List<Comentario> comentarios = new ArrayList<>(); comentarios.add(comentario1); Taxa taxa = new Taxa(); taxa.setCodigo("cod01"); taxa.setId("id01"); taxa.setTipo(TipoTaxa.ACUMULADA); taxa.setValor(bg); taxa.setDenominador(bg); taxa.setComentarios(comentarios); List<Taxa> taxasAjustadas = new ArrayList<>(); taxasAjustadas.add(taxa); UnidadeGeradora unidade = new UnidadeGeradora(); unidade.setId("idUni01"); unidade.setNome("nomeUni01"); List<UnidadeGeradora> unidadesGeradoras = new ArrayList<>(); unidadesGeradoras.add(unidade); Agente agenteProprietario = new Agente(); agenteProprietario.setId("id01"); agenteProprietario.setNomeCurto("nomeCurtoAgente01"); agenteProprietario.setSigla("SIGLA"); Usina instalacao = new Usina(); instalacao.setId("id01"); instalacao.setDataOutorgaImplantacao(data); instalacao.setNomeCurto("nomeCurto01"); instalacao.setTaxasAjustadas(taxasAjustadas); instalacao.setUnidadesGeradoras(unidadesGeradoras); instalacao.setTipo(TipoUsina.UHE); instalacao.setAgenteProprietario(agenteProprietario); InstalacaoCadastradaEvent event = new InstalacaoCadastradaEvent(); event.setInstalacao(instalacao); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idInter01"); Long i = 12L; metadata.setMinorVersion(i); EventMessage<InstalacaoCadastradaEvent> eventMessage = new EventMessage<>(); InstalacaoCadastradaEvent e; eventMessage.setEvent(event); eventHandler.handleInstalacaoCadastradaEvent(eventMessage); eventHandler.handleInstalacaoCadastradaEvent(eventMessage); } @Test public void cadastrarEventoTipoInterligacaoInternacional() throws Exception { BigDecimal bg = new BigDecimal(12); Date data = new Date("2016/11/28 03:00:00"); ComentarioSituacao comentario1 = new ComentarioSituacao(); comentario1.setDataInsercao(data); comentario1.setDescricao("Descricao"); comentario1.setOrigem(OrigemComentario.ONS); comentario1.setTipo(TipoComentario.COMENTARIO); comentario1.setDataFim(data); comentario1.setNomeObjeto("nome01"); comentario1.setStatusObjeto(StatusObjeto.FORA_OPERACAO_COMERCIAL); comentario1.setTipoObjeto(TipoObjeto.USINA); List<Comentario> comentarios = new ArrayList<>(); comentarios.add(comentario1); Taxa taxa = new Taxa(); taxa.setCodigo("cod01"); taxa.setId("id01"); taxa.setTipo(TipoTaxa.ACUMULADA); taxa.setValor(bg); taxa.setDenominador(bg); taxa.setComentarios(comentarios); List<Taxa> taxasAjustadas = new ArrayList<>(); taxasAjustadas.add(taxa); UnidadeGeradora unidade = new UnidadeGeradora(); unidade.setId("idUni01"); unidade.setNome("nomeUni01"); List<UnidadeGeradora> unidadesGeradoras = new ArrayList<>(); unidadesGeradoras.add(unidade); Agente agenteProprietario = new Agente(); agenteProprietario.setId("id01"); agenteProprietario.setNomeCurto("nomeCurtoAgente01"); agenteProprietario.setSigla("SIGLA"); EquipamentoInterligacaoInternacional equipamento = new EquipamentoInterligacaoInternacional(); equipamento.setId("idEquip01"); equipamento.setNome("nomeEquip01"); InterligacaoInternacional instalacao = new InterligacaoInternacional(); instalacao.setId("id01"); instalacao.setDataOutorgaImplantacao(data); instalacao.setNomeCurto("nomeCurto01"); instalacao.setTaxasAjustadas(taxasAjustadas); instalacao.setAgenteResponsavel(agenteProprietario); instalacao.setEquipamento(equipamento); InstalacaoCadastradaEvent event = new InstalacaoCadastradaEvent(); event.setInstalacao(instalacao); EventMetadata metadata= new EventMetadata(); metadata.setAggregateId("idInter01"); Long i = 12L; metadata.setMinorVersion(i); EventMessage<InstalacaoCadastradaEvent> eventMessage = new EventMessage<>(); InstalacaoCadastradaEvent e; eventMessage.setEvent(event); eventHandler.handleInstalacaoCadastradaEvent(eventMessage); eventHandler.handleInstalacaoCadastradaEvent(eventMessage); } }
[ "leandro.santana@scalait.com" ]
leandro.santana@scalait.com
780c01ef23e7158e3aea115a31fa77230beb37e3
e28ca94227ed7dd6b905878233aec7cce98a99df
/Max-Increase-to-Keep-City-Skyline/src/Solution.java
a4c73197f8ee022a3816d7096c0938e35d41441b
[]
no_license
xiao-peng1006/Coding-Chanllenge
a0f80b70439902da98191d91f2d2b023070c3dde
419ddfa497b744da4c985407c601f44ac149a03d
refs/heads/master
2020-04-27T09:59:47.396322
2019-12-16T19:02:05
2019-12-16T19:02:05
174,236,289
0
0
null
null
null
null
UTF-8
Java
false
false
1,352
java
import java.util.Arrays; class Solution { /** * Leetcode 807. Max Increase to Keep City Skyline * @param grid * @return */ int[][] grid; public int maxIncreaseKeepingSkyline(int[][] grid) { this.grid = grid; int res = 0; for (int i = 0; i < grid.length; i++) { int rowMax = getMaxRow(i); for (int j = 0; j < grid[0].length; j++) { int colMax = getMaxCol(j); if (grid[i][j] == rowMax || grid[i][j] == colMax) continue; res += Math.min(rowMax, colMax) - grid[i][j]; } } return res; } private int getMaxRow(int row) { int rowMax = grid[row][0]; for (int i = 1; i < grid[row].length; i++) { rowMax = Math.max(rowMax, grid[row][i]); } return rowMax; } private int getMaxCol(int col) { int colMax = grid[0][col]; for (int i = 1; i < grid.length; i++) { colMax = Math.max(colMax, grid[i][col]); } return colMax; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println("Expected: 35, Output: " + solution.maxIncreaseKeepingSkyline(new int[][]{{3, 0, 8, 4}, {2, 4, 5, 7}, {9, 2, 6, 3}, {0, 3, 1, 0}})); } }
[ "xiao.peng1006@gmail.com" ]
xiao.peng1006@gmail.com
7734d32f4cf0ef99dc610d8dc5e590ede50065f8
8cd199f4dd1bd71e22b0ae35431149b9c3d4991d
/carpentersblocks/data/Slope.java
976abb17cffd200ca8ba6fe8d4a0d02895ce6a46
[]
no_license
rysson/carpentersblocks
116a6ad7048c0334b6a1d631c593640e8d9461c6
916bcb045375e09ba641c79885a0aa82074c32fa
refs/heads/master
2021-01-18T05:10:31.919288
2013-12-27T13:17:03
2013-12-27T13:17:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,136
java
package carpentersblocks.data; import static net.minecraftforge.common.ForgeDirection.DOWN; import static net.minecraftforge.common.ForgeDirection.EAST; import static net.minecraftforge.common.ForgeDirection.NORTH; import static net.minecraftforge.common.ForgeDirection.SOUTH; import static net.minecraftforge.common.ForgeDirection.UP; import static net.minecraftforge.common.ForgeDirection.WEST; import java.util.ArrayList; import java.util.List; import net.minecraftforge.common.ForgeDirection; public class Slope { /** * 16-bit data components: * * [0000000000000000] * slopeID */ /* * Slope IDs. * * IDs 0 - 11 are set arbitrarily when * block is placed in world. * * IDs 12 - 45 are mixed to retain compatibility * with older versions. */ public final static byte ID_WEDGE_SE = 0; public final static byte ID_WEDGE_NW = 1; public final static byte ID_WEDGE_NE = 2; public final static byte ID_WEDGE_SW = 3; public final static byte ID_WEDGE_NEG_N = 4; public final static byte ID_WEDGE_NEG_S = 5; public final static byte ID_WEDGE_NEG_W = 6; public final static byte ID_WEDGE_NEG_E = 7; public final static byte ID_WEDGE_POS_N = 8; public final static byte ID_WEDGE_POS_S = 9; public final static byte ID_WEDGE_POS_W = 10; public final static byte ID_WEDGE_POS_E = 11; public final static byte ID_WEDGE_INT_NEG_SE = 19; public final static byte ID_WEDGE_INT_NEG_NW = 15; public final static byte ID_WEDGE_INT_NEG_NE = 13; public final static byte ID_WEDGE_INT_NEG_SW = 17; public final static byte ID_WEDGE_INT_POS_SE = 18; public final static byte ID_WEDGE_INT_POS_NW = 14; public final static byte ID_WEDGE_INT_POS_NE = 12; public final static byte ID_WEDGE_INT_POS_SW = 16; public final static byte ID_WEDGE_EXT_NEG_SE = 23; public final static byte ID_WEDGE_EXT_NEG_NW = 27; public final static byte ID_WEDGE_EXT_NEG_NE = 25; public final static byte ID_WEDGE_EXT_NEG_SW = 21; public final static byte ID_WEDGE_EXT_POS_SE = 22; public final static byte ID_WEDGE_EXT_POS_NW = 26; public final static byte ID_WEDGE_EXT_POS_NE = 24; public final static byte ID_WEDGE_EXT_POS_SW = 20; public final static byte ID_OBL_INT_NEG_SE = 35; public final static byte ID_OBL_INT_NEG_NW = 31; public final static byte ID_OBL_INT_NEG_NE = 29; public final static byte ID_OBL_INT_NEG_SW = 33; public final static byte ID_OBL_INT_POS_SE = 34; public final static byte ID_OBL_INT_POS_NW = 30; public final static byte ID_OBL_INT_POS_NE = 28; public final static byte ID_OBL_INT_POS_SW = 32; public final static byte ID_OBL_EXT_NEG_SE = 39; public final static byte ID_OBL_EXT_NEG_NW = 43; public final static byte ID_OBL_EXT_NEG_NE = 41; public final static byte ID_OBL_EXT_NEG_SW = 37; public final static byte ID_OBL_EXT_POS_SE = 38; public final static byte ID_OBL_EXT_POS_NW = 42; public final static byte ID_OBL_EXT_POS_NE = 40; public final static byte ID_OBL_EXT_POS_SW = 36; public final static byte ID_PYR_HALF_NEG = 45; public final static byte ID_PYR_HALF_POS = 44; public final static byte ID_PRISM_1P_N = 46; public final static byte ID_PRISM_1P_S = 47; public final static byte ID_PRISM_1P_W = 48; public final static byte ID_PRISM_1P_E = 49; public final static byte ID_PRISM_2P_NS = 50; public final static byte ID_PRISM_2P_WE = 51; public final static byte ID_PRISM_2P_SE = 52; public final static byte ID_PRISM_2P_NW = 53; public final static byte ID_PRISM_2P_NE = 54; public final static byte ID_PRISM_2P_SW = 55; public final static byte ID_PRISM_3P_WEN = 56; public final static byte ID_PRISM_3P_WES = 57; public final static byte ID_PRISM_3P_NSW = 58; public final static byte ID_PRISM_3P_NSE = 59; public final static byte ID_PRISM_4P = 60; public final static byte ID_PRISM_SLOPE_N = 61; public final static byte ID_PRISM_SLOPE_S = 62; public final static byte ID_PRISM_SLOPE_W = 63; public final static byte ID_PRISM_SLOPE_E = 64; public enum Type { WEDGE_XZ, WEDGE_Y, WEDGE_INT, WEDGE_EXT, OBLIQUE_INT, OBLIQUE_EXT, PYRAMID, PRISM_1P, PRISM_2P, PRISM_3P, PRISM_4P, PRISM_SLOPE } public enum Face { NONE, FULL, WEDGE, TRIANGLE } /* * These represent the primary corner of the face shape. */ public final static byte XYNN = 4; public final static byte XYNP = 5; public final static byte XYPN = 6; public final static byte XYPP = 7; /** Array containing registered slopes. */ public static final Slope[] slopesList = new Slope[65]; /** ID of the slope. */ public final int slopeID; /** Slope type. */ public final Type type; /** * Holds slope face shape. * * [DOWN, UP, NORTH, SOUTH, WEST, EAST] */ private final Face[] face; /** * If faceShape indicates side is WEDGE, * this will indicate which corner of face * is the "corner." * * This is used for side render checks. * * Stores MIN/MAX of wedge corner. * Stored as [X/Y], [Z/Y], or [X/Z]. * * [DOWN, UP, NORTH, SOUTH, WEST, EAST] */ private final int[] faceBias; /** * Is the slope facing up. * A quick reference since it's called often. */ public final boolean isPositive; /** * For most slopes, this aids in auto-transformation code. * For prism slopes, this aids in rendering the slopes. */ public final List<ForgeDirection> facings; public Slope(int slopeID, Type slopeType, ForgeDirection[] facings, Face[] faceShape, int[] faceBias) { this.slopeID = slopeID; slopesList[slopeID] = this; type = slopeType; face = faceShape; this.faceBias = faceBias; this.facings = new ArrayList<ForgeDirection>(); for (ForgeDirection face : facings) { this.facings.add(face); } isPositive = this.facings.contains(UP); } public static final Slope WEDGE_NW = new Slope(ID_WEDGE_NW, Type.WEDGE_XZ, new ForgeDirection[] { NORTH, WEST }, new Face[] { Face.WEDGE, Face.WEDGE, Face.NONE, Face.FULL, Face.NONE, Face.FULL }, new int[] { XYPP, XYPP, 0, 0, 0, 0 }); public static final Slope WEDGE_NE = new Slope(ID_WEDGE_NE, Type.WEDGE_XZ, new ForgeDirection[] { NORTH, EAST }, new Face[] { Face.WEDGE, Face.WEDGE, Face.NONE, Face.FULL, Face.FULL, Face.NONE }, new int[] { XYNP, XYNP, 0, 0, 0, 0 }); public static final Slope WEDGE_SW = new Slope(ID_WEDGE_SW, Type.WEDGE_XZ, new ForgeDirection[] { SOUTH, WEST }, new Face[] { Face.WEDGE, Face.WEDGE, Face.FULL, Face.NONE, Face.NONE, Face.FULL }, new int[] { XYPN, XYPN, 0, 0, 0, 0 }); public static final Slope WEDGE_SE = new Slope(ID_WEDGE_SE, Type.WEDGE_XZ, new ForgeDirection[] { SOUTH, EAST }, new Face[] { Face.WEDGE, Face.WEDGE, Face.FULL, Face.NONE, Face.FULL, Face.NONE }, new int[] { XYNN, XYNN, 0, 0, 0, 0 }); public static final Slope WEDGE_NEG_N = new Slope(ID_WEDGE_NEG_N, Type.WEDGE_Y, new ForgeDirection[] { DOWN, NORTH }, new Face[] { Face.NONE, Face.FULL, Face.NONE, Face.FULL, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYPP, XYPP }); public static final Slope WEDGE_NEG_S = new Slope(ID_WEDGE_NEG_S, Type.WEDGE_Y, new ForgeDirection[] { DOWN, SOUTH }, new Face[] { Face.NONE, Face.FULL, Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYNP, XYNP }); public static final Slope WEDGE_NEG_W = new Slope(ID_WEDGE_NEG_W, Type.WEDGE_Y, new ForgeDirection[] { DOWN, WEST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.WEDGE, Face.NONE, Face.FULL }, new int[] { 0, 0, XYPP, XYPP, 0, 0 }); public static final Slope WEDGE_NEG_E = new Slope(ID_WEDGE_NEG_E, Type.WEDGE_Y, new ForgeDirection[] { DOWN, EAST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL, Face.NONE }, new int[] { 0, 0, XYNP, XYNP, 0, 0 }); public static final Slope WEDGE_POS_N = new Slope(ID_WEDGE_POS_N, Type.WEDGE_Y, new ForgeDirection[] { UP, NORTH }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.FULL, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYPN, XYPN }); public static final Slope WEDGE_POS_S = new Slope(ID_WEDGE_POS_S, Type.WEDGE_Y, new ForgeDirection[] { UP, SOUTH }, new Face[] { Face.FULL, Face.NONE, Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYNN, XYNN }); public static final Slope WEDGE_POS_W = new Slope(ID_WEDGE_POS_W, Type.WEDGE_Y, new ForgeDirection[] { UP, WEST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE, Face.FULL }, new int[] { 0, 0, XYPN, XYPN, 0, 0 }); public static final Slope WEDGE_POS_E = new Slope(ID_WEDGE_POS_E, Type.WEDGE_Y, new ForgeDirection[] { UP, EAST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE, Face.FULL, Face.NONE }, new int[] { 0, 0, XYNN, XYNN, 0, 0 }); public static final Slope WEDGE_INT_NEG_NW = new Slope(ID_WEDGE_INT_NEG_NW, Type.WEDGE_INT, new ForgeDirection[] { DOWN, NORTH, WEST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL }, new int[] { 0, 0, XYPP, 0, XYPP, 0 }); public static final Slope WEDGE_INT_NEG_NE = new Slope(ID_WEDGE_INT_NEG_NE, Type.WEDGE_INT, new ForgeDirection[] { DOWN, NORTH, EAST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE }, new int[] { 0, 0, XYNP, 0, 0, XYPP }); public static final Slope WEDGE_INT_NEG_SW = new Slope(ID_WEDGE_INT_NEG_SW, Type.WEDGE_INT, new ForgeDirection[] { DOWN, SOUTH, WEST }, new Face[] { Face.NONE, Face.FULL, Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL }, new int[] { 0, 0, 0, XYPP, XYNP, 0 }); public static final Slope WEDGE_INT_NEG_SE = new Slope(ID_WEDGE_INT_NEG_SE, Type.WEDGE_INT, new ForgeDirection[] { DOWN, SOUTH, EAST }, new Face[] { Face.NONE, Face.FULL, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE }, new int[] { 0, 0, 0, XYNP, 0, XYNP }); public static final Slope WEDGE_INT_POS_NW = new Slope(ID_WEDGE_INT_POS_NW, Type.WEDGE_INT, new ForgeDirection[] { UP, NORTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL }, new int[] { 0, 0, XYPN, 0, XYPN, 0 }); public static final Slope WEDGE_INT_POS_NE = new Slope(ID_WEDGE_INT_POS_NE, Type.WEDGE_INT, new ForgeDirection[] { UP, NORTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE }, new int[] { 0, 0, XYNN, 0, 0, XYPN }); public static final Slope WEDGE_INT_POS_SW = new Slope(ID_WEDGE_INT_POS_SW, Type.WEDGE_INT, new ForgeDirection[] { UP, SOUTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL }, new int[] { 0, 0, 0, XYPN, XYNN, 0 }); public static final Slope WEDGE_INT_POS_SE = new Slope(ID_WEDGE_INT_POS_SE, Type.WEDGE_INT, new ForgeDirection[] { UP, SOUTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE }, new int[] { 0, 0, 0, XYNN, 0, XYNN }); public static final Slope WEDGE_EXT_NEG_NW = new Slope(ID_WEDGE_EXT_NEG_NW, Type.WEDGE_EXT, new ForgeDirection[] { DOWN, NORTH, WEST }, new Face[] { Face.NONE, Face.FULL, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE }, new int[] { 0, 0, 0, XYPP, 0, XYPP }); public static final Slope WEDGE_EXT_NEG_NE = new Slope(ID_WEDGE_EXT_NEG_NE, Type.WEDGE_EXT, new ForgeDirection[] { DOWN, NORTH, EAST }, new Face[] { Face.NONE, Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE }, new int[] { 0, 0, 0, XYNP, XYPP, 0 }); public static final Slope WEDGE_EXT_NEG_SW = new Slope(ID_WEDGE_EXT_NEG_SW, Type.WEDGE_EXT, new ForgeDirection[] { DOWN, SOUTH, WEST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE }, new int[] { 0, 0, XYPP, 0, 0, XYNP }); public static final Slope WEDGE_EXT_NEG_SE = new Slope(ID_WEDGE_EXT_NEG_SE, Type.WEDGE_EXT, new ForgeDirection[] { DOWN, SOUTH, EAST }, new Face[] { Face.NONE, Face.FULL, Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE }, new int[] { 0, 0, XYNP, 0, XYNP, 0 }); public static final Slope WEDGE_EXT_POS_NW = new Slope(ID_WEDGE_EXT_POS_NW, Type.WEDGE_EXT, new ForgeDirection[] { UP, NORTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE }, new int[] { 0, 0, 0, XYPN, 0, XYPN }); public static final Slope WEDGE_EXT_POS_NE = new Slope(ID_WEDGE_EXT_POS_NE, Type.WEDGE_EXT, new ForgeDirection[] { UP, NORTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE }, new int[] { 0, 0, 0, XYNN, XYPN, 0 }); public static final Slope WEDGE_EXT_POS_SW = new Slope(ID_WEDGE_EXT_POS_SW, Type.WEDGE_EXT, new ForgeDirection[] { UP, SOUTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE }, new int[] { 0, 0, XYPN, 0, 0, XYNN }); public static final Slope WEDGE_EXT_POS_SE = new Slope(ID_WEDGE_EXT_POS_SE, Type.WEDGE_EXT, new ForgeDirection[] { UP, SOUTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE }, new int[] { 0, 0, XYNN, 0, XYNN, 0 }); public static final Slope OBL_INT_NEG_NW = new Slope(ID_OBL_INT_NEG_NW, Type.OBLIQUE_INT, new ForgeDirection[] { DOWN, NORTH, WEST }, new Face[] { Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL }, new int[] { XYPP, 0, XYPP, 0, XYPP, 0 }); public static final Slope OBL_INT_NEG_NE = new Slope(ID_OBL_INT_NEG_NE, Type.OBLIQUE_INT, new ForgeDirection[] { DOWN, NORTH, EAST }, new Face[] { Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE }, new int[] { XYNP, 0, XYNP, 0, 0, XYPP }); public static final Slope OBL_INT_NEG_SW = new Slope(ID_OBL_INT_NEG_SW, Type.OBLIQUE_INT, new ForgeDirection[] { DOWN, SOUTH, WEST }, new Face[] { Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL }, new int[] { XYPN, 0, 0, XYPP, XYNP, 0 }); public static final Slope OBL_INT_NEG_SE = new Slope(ID_OBL_INT_NEG_SE, Type.OBLIQUE_INT, new ForgeDirection[] { DOWN, SOUTH, EAST }, new Face[] { Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE }, new int[] { XYNN, 0, 0, XYNP, 0, XYNP }); public static final Slope OBL_INT_POS_NW = new Slope(ID_OBL_INT_POS_NW, Type.OBLIQUE_INT, new ForgeDirection[] { UP, NORTH, WEST }, new Face[] { Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL }, new int[] { 0, XYPP, XYPN, 0, XYPN, 0 }); public static final Slope OBL_INT_POS_NE = new Slope(ID_OBL_INT_POS_NE, Type.OBLIQUE_INT, new ForgeDirection[] { UP, NORTH, EAST }, new Face[] { Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL, Face.FULL, Face.WEDGE }, new int[] { 0, XYNP, XYNN, 0, 0, XYPN }); public static final Slope OBL_INT_POS_SW = new Slope(ID_OBL_INT_POS_SW, Type.OBLIQUE_INT, new ForgeDirection[] { UP, SOUTH, WEST }, new Face[] { Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE, Face.WEDGE, Face.FULL }, new int[] { 0, XYPN, 0, XYPN, XYNN, 0 }); public static final Slope OBL_INT_POS_SE = new Slope(ID_OBL_INT_POS_SE, Type.OBLIQUE_INT, new ForgeDirection[] { UP, SOUTH, EAST }, new Face[] { Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE, Face.FULL, Face.WEDGE }, new int[] { 0, XYNN, 0, XYNN, 0, XYNN }); public static final Slope OBL_EXT_NEG_NW = new Slope(ID_OBL_EXT_NEG_NW, Type.OBLIQUE_EXT, new ForgeDirection[] { DOWN, NORTH, WEST }, new Face[] { Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE }, new int[] { 0, XYPP, 0, XYPP, 0, XYPP }); public static final Slope OBL_EXT_NEG_NE = new Slope(ID_OBL_EXT_NEG_NE, Type.OBLIQUE_EXT, new ForgeDirection[] { DOWN, NORTH, EAST }, new Face[] { Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE }, new int[] { 0, XYNP, 0, XYNP, XYPP, 0 }); public static final Slope OBL_EXT_NEG_SW = new Slope(ID_OBL_EXT_NEG_SW, Type.OBLIQUE_EXT, new ForgeDirection[] { DOWN, SOUTH, WEST }, new Face[] { Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE }, new int[] { 0, XYPN, XYPP, 0, 0, XYNP }); public static final Slope OBL_EXT_NEG_SE = new Slope(ID_OBL_EXT_NEG_SE, Type.OBLIQUE_EXT, new ForgeDirection[] { DOWN, SOUTH, EAST }, new Face[] { Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE }, new int[] { 0, XYNN, XYNP, 0, XYNP, 0 }); public static final Slope OBL_EXT_POS_NW = new Slope(ID_OBL_EXT_POS_NW, Type.OBLIQUE_EXT, new ForgeDirection[] { UP, NORTH, WEST }, new Face[] { Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE }, new int[] { XYPP, 0, 0, XYPN, 0, XYPN }); public static final Slope OBL_EXT_POS_NE = new Slope(ID_OBL_EXT_POS_NE, Type.OBLIQUE_EXT, new ForgeDirection[] { UP, NORTH, EAST }, new Face[] { Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE, Face.WEDGE, Face.NONE }, new int[] { XYNP, 0, 0, XYNN, XYPN, 0 }); public static final Slope OBL_EXT_POS_SW = new Slope(ID_OBL_EXT_POS_SW, Type.OBLIQUE_EXT, new ForgeDirection[] { UP, SOUTH, WEST }, new Face[] { Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE, Face.NONE, Face.WEDGE }, new int[] { XYPN, 0, XYPN, 0, 0, XYNN }); public static final Slope OBL_EXT_POS_SE = new Slope(ID_OBL_EXT_POS_SE, Type.OBLIQUE_EXT, new ForgeDirection[] { UP, SOUTH, EAST }, new Face[] { Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE, Face.WEDGE, Face.NONE }, new int[] { XYNN, 0, XYNN, 0, XYNN, 0 }); public static final Slope PYR_HALF_NEG = new Slope(ID_PYR_HALF_NEG, Type.PYRAMID, new ForgeDirection[] { DOWN, NORTH, SOUTH, WEST, EAST }, new Face[] { Face.NONE, Face.FULL, Face.NONE, Face.NONE, Face.NONE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PYR_HALF_POS = new Slope(ID_PYR_HALF_POS, Type.PYRAMID, new ForgeDirection[] { UP, NORTH, SOUTH, WEST, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.NONE, Face.NONE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_1P_N = new Slope(ID_PRISM_1P_N, Type.PRISM_1P, new ForgeDirection[] { UP, NORTH }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.NONE, Face.NONE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_1P_S = new Slope(ID_PRISM_1P_S, Type.PRISM_1P, new ForgeDirection[] { UP, SOUTH }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.TRIANGLE, Face.NONE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_1P_W = new Slope(ID_PRISM_1P_W, Type.PRISM_1P, new ForgeDirection[] { UP, WEST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.NONE, Face.TRIANGLE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_1P_E = new Slope(ID_PRISM_1P_E, Type.PRISM_1P, new ForgeDirection[] { UP, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.NONE, Face.NONE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_NS = new Slope(ID_PRISM_2P_NS, Type.PRISM_2P, new ForgeDirection[] { UP, NORTH, SOUTH }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.NONE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_WE = new Slope(ID_PRISM_2P_WE, Type.PRISM_2P, new ForgeDirection[] { UP, WEST, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.NONE, Face.TRIANGLE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_SE = new Slope(ID_PRISM_2P_SE, Type.PRISM_2P, new ForgeDirection[] { UP, SOUTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.TRIANGLE, Face.NONE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_NW = new Slope(ID_PRISM_2P_NW, Type.PRISM_2P, new ForgeDirection[] { UP, NORTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.NONE, Face.TRIANGLE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_NE = new Slope(ID_PRISM_2P_NE, Type.PRISM_2P, new ForgeDirection[] { UP, NORTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.NONE, Face.NONE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_2P_SW = new Slope(ID_PRISM_2P_SW, Type.PRISM_2P, new ForgeDirection[] { UP, SOUTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_3P_WEN = new Slope(ID_PRISM_3P_WEN, Type.PRISM_3P, new ForgeDirection[] { UP, NORTH, WEST, EAST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.NONE, Face.TRIANGLE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_3P_WES = new Slope(ID_PRISM_3P_WES, Type.PRISM_3P, new ForgeDirection[] { UP, SOUTH, WEST, EAST }, new Face[] { Face.FULL, Face.NONE, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_3P_NSW = new Slope(ID_PRISM_3P_NSW, Type.PRISM_3P, new ForgeDirection[] { UP, NORTH, SOUTH, WEST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.TRIANGLE, Face.NONE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_3P_NSE = new Slope(ID_PRISM_3P_NSE, Type.PRISM_3P, new ForgeDirection[] { UP, NORTH, SOUTH, EAST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.NONE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_4P = new Slope(ID_PRISM_4P, Type.PRISM_4P, new ForgeDirection[] { UP, NORTH, SOUTH, WEST, EAST }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.TRIANGLE, Face.TRIANGLE, Face.TRIANGLE }, new int[] { 0, 0, 0, 0, 0, 0 }); public static final Slope PRISM_SLOPE_N = new Slope(ID_PRISM_SLOPE_N, Type.PRISM_SLOPE, new ForgeDirection[] { UP, NORTH }, new Face[] { Face.FULL, Face.NONE, Face.TRIANGLE, Face.FULL, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYPN, XYPN }); public static final Slope PRISM_SLOPE_S = new Slope(ID_PRISM_SLOPE_S, Type.PRISM_SLOPE, new ForgeDirection[] { UP, SOUTH }, new Face[] { Face.FULL, Face.NONE, Face.FULL, Face.TRIANGLE, Face.WEDGE, Face.WEDGE }, new int[] { 0, 0, 0, 0, XYNN, XYNN }); public static final Slope PRISM_SLOPE_W = new Slope(ID_PRISM_SLOPE_W, Type.PRISM_SLOPE, new ForgeDirection[] { UP, WEST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE, Face.TRIANGLE, Face.FULL }, new int[] { 0, 0, XYPN, XYPN, 0, 0 }); public static final Slope PRISM_SLOPE_E = new Slope(ID_PRISM_SLOPE_E, Type.PRISM_SLOPE, new ForgeDirection[] { UP, EAST }, new Face[] { Face.FULL, Face.NONE, Face.WEDGE, Face.WEDGE, Face.FULL, Face.TRIANGLE }, new int[] { 0, 0, XYNN, XYNN, 0, 0 }); public Type getPrimaryType() { switch (type) { case WEDGE_XZ: case WEDGE_Y: case WEDGE_INT: case WEDGE_EXT: case OBLIQUE_INT: case OBLIQUE_EXT: return Type.WEDGE_XZ; case PYRAMID: return Type.PYRAMID; case PRISM_1P: case PRISM_2P: case PRISM_3P: case PRISM_4P: case PRISM_SLOPE: return Type.PRISM_SLOPE; default: return Type.WEDGE_Y; } } public Face getFace(ForgeDirection side) { return face[side.ordinal()]; } public boolean isFaceFull(ForgeDirection side) { return face[side.ordinal()] == Face.FULL; } public boolean hasSide(ForgeDirection side) { return face[side.ordinal()] != Face.NONE; } public int faceBias(ForgeDirection side) { return faceBias[side.ordinal()]; } }
[ "kmartshopper@gmail.com" ]
kmartshopper@gmail.com
2cd82d28184a35fa485f7053c644218258deb7c1
aecffb5cc456d31f938774a02de30c062fee726b
/sources/com/sec/android/app/clockpackage/stopwatch/model/ListItem.java
9748f990f943e18b214054d796ba9f1838236a35
[]
no_license
Austin-Chow/SamsungClock10.0.04.3
6d48abd288f3b182a6520315ef526163a94b0278
5523378f7fea1bf462248fddf52a7828ff2de0a9
refs/heads/master
2020-06-29T12:44:41.353764
2019-08-04T20:47:14
2019-08-04T20:47:14
200,538,351
0
0
null
null
null
null
UTF-8
Java
false
false
2,689
java
package com.sec.android.app.clockpackage.stopwatch.model; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; public class ListItem implements Parcelable { public static final Creator<ListItem> CREATOR = new C07071(); private long mElapsedTime; private String mIndex; private String mMilliSecond; private String mMilliSecondDiff; private String mTime; private String mTimeDescription; private String mTimeDiff; private String mTimeDiffDescription; /* renamed from: com.sec.android.app.clockpackage.stopwatch.model.ListItem$1 */ static class C07071 implements Creator<ListItem> { C07071() { } public ListItem createFromParcel(Parcel source) { return new ListItem(source.readString(), source.readLong(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString()); } public ListItem[] newArray(int size) { return new ListItem[size]; } } public ListItem(String index, long elapsedTime, String time, String millisecond, String timeDiff, String millisecondDiff, String timeDescription, String timeDiffDescription) { this.mIndex = index; this.mElapsedTime = elapsedTime; this.mTime = time; this.mMilliSecond = millisecond; this.mTimeDiff = timeDiff; this.mMilliSecondDiff = millisecondDiff; this.mTimeDescription = timeDescription; this.mTimeDiffDescription = timeDiffDescription; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.mIndex); dest.writeLong(this.mElapsedTime); dest.writeString(this.mTime); dest.writeString(this.mMilliSecond); dest.writeString(this.mTimeDiff); dest.writeString(this.mMilliSecondDiff); dest.writeString(this.mTimeDescription); dest.writeString(this.mTimeDiffDescription); } public String getIndex() { return this.mIndex; } public String getTime() { return this.mTime; } public long getElapsedTime() { return this.mElapsedTime; } public String getMillisecond() { return this.mMilliSecond; } public String getTimeDiff() { return this.mTimeDiff; } public String getMillisecondDiff() { return this.mMilliSecondDiff; } public String getTimeDescription() { return this.mTimeDescription; } public String getTimeDiffDescription() { return this.mTimeDiffDescription; } }
[ "myemail" ]
myemail
8daa98917d2fb4122817614a082b771cc8995997
4e1787629588da82a11e6cb4845c57923f527e5d
/coherence-spring-core/src/main/java/com/oracle/coherence/spring/messaging/CoherencePublisherScanRegistrar.java
e9ca5f89c1ded6caa909a26db9556bdec1d0104c
[ "UPL-1.0", "BSD-3-Clause", "EPL-2.0", "CC-BY-3.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CDDL-1.0", "CC0-1.0", "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-free-unknown", "GPL-2.0-only", ...
permissive
coherence-community/coherence-spring
ab17ed8010b971e16766452cf936a7e2a865cc43
b1eb9e90e8c90188df985b42fe89206dad535a67
refs/heads/main
2023-09-02T07:56:48.464208
2023-09-01T15:56:09
2023-09-01T15:56:09
8,587,598
30
22
UPL-1.0
2023-09-14T20:28:57
2013-03-05T19:46:48
Java
UTF-8
Java
false
false
9,801
java
/* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (c) 2021, 2022 Oracle and/or its affiliates. */ package com.oracle.coherence.spring.messaging; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import com.oracle.coherence.spring.annotation.CoherencePublisher; import com.oracle.coherence.spring.annotation.CoherencePublisherScan; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.Aware; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.AspectJTypeFilter; import org.springframework.core.type.filter.AssignableTypeFilter; import org.springframework.core.type.filter.RegexPatternTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * {@link ImportBeanDefinitionRegistrar} implementation to scan and register Coherence publishers. * * @author Artem Bilan * @author Gary Russell * * @since 3.0 */ public class CoherencePublisherScanRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { private final Map<TypeFilter, ImportBeanDefinitionRegistrar> componentRegistrars = new HashMap<>(); private ResourceLoader resourceLoader; private Environment environment; public CoherencePublisherScanRegistrar() { this.componentRegistrars.put(new AnnotationTypeFilter(CoherencePublisher.class, true), new CoherencePublisherRegistrar()); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { final Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(CoherencePublisherScan.class.getName()); Assert.notNull(annotationAttributes, "No matching CoherencePublisherScan was found."); Collection<String> basePackages = getBasePackages(importingClassMetadata, registry); if (basePackages.isEmpty()) { basePackages = Collections.singleton(ClassUtils.getPackageName(importingClassMetadata.getClassName())); } final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false, this.environment) { @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isIndependent() && !beanDefinition.getMetadata().isAnnotation(); } @Override protected BeanDefinitionRegistry getRegistry() { return registry; } }; filter(registry, annotationAttributes, scanner); scanner.setResourceLoader(this.resourceLoader); for (String basePackage : basePackages) { Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage); for (BeanDefinition candidateComponent : candidateComponents) { if (candidateComponent instanceof AnnotatedBeanDefinition) { for (ImportBeanDefinitionRegistrar registrar : this.componentRegistrars.values()) { registrar.registerBeanDefinitions(((AnnotatedBeanDefinition) candidateComponent).getMetadata(), registry); } } } } } /** * Get the collection of base packages from the {@link CoherencePublisherScan} annotation if available. * @param importingClassMetadata the AnnotationMetadata * @param registry the BeanDefinitionRegistry * @return the basePackages, never null */ protected Collection<String> getBasePackages(AnnotationMetadata importingClassMetadata, @SuppressWarnings("unused") BeanDefinitionRegistry registry) { Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(CoherencePublisherScan.class.getName()); Set<String> basePackages = new HashSet<>(); if (annotationAttributes == null) { return basePackages; } for (String pkg : (String[]) annotationAttributes.get("value")) { if (StringUtils.hasText(pkg)) { basePackages.add(pkg); } } for (Class<?> clazz : (Class<?>[]) annotationAttributes.get("basePackageClasses")) { basePackages.add(ClassUtils.getPackageName(clazz)); } return basePackages; } private void filter(BeanDefinitionRegistry registry, Map<String, Object> componentScan, ClassPathScanningCandidateComponentProvider scanner) { if ((boolean) componentScan.get("useDefaultFilters")) { for (TypeFilter typeFilter : this.componentRegistrars.keySet()) { scanner.addIncludeFilter(typeFilter); } } for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("includeFilters")) { for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) { scanner.addIncludeFilter(typeFilter); } } for (AnnotationAttributes filter : (AnnotationAttributes[]) componentScan.get("excludeFilters")) { for (TypeFilter typeFilter : typeFiltersFor(filter, registry)) { scanner.addExcludeFilter(typeFilter); } } } private List<TypeFilter> typeFiltersFor(AnnotationAttributes filter, BeanDefinitionRegistry registry) { List<TypeFilter> typeFilters = new ArrayList<>(); FilterType filterType = filter.getEnum("type"); for (Class<?> filterClass : filter.getClassArray("classes")) { switch (filterType) { case ANNOTATION: Assert.isAssignable(Annotation.class, filterClass, "An error occurred while processing a @CoherencePublisherScan ANNOTATION type filter: "); @SuppressWarnings("unchecked") Class<Annotation> annotationType = (Class<Annotation>) filterClass; typeFilters.add(new AnnotationTypeFilter(annotationType)); break; case ASSIGNABLE_TYPE: typeFilters.add(new AssignableTypeFilter(filterClass)); break; case CUSTOM: Assert.isAssignable(TypeFilter.class, filterClass, "An error occurred while processing a @CoherencePublisherScan CUSTOM type filter: "); TypeFilter typeFilter = BeanUtils.instantiateClass(filterClass, TypeFilter.class); invokeAwareMethods(filter, this.environment, this.resourceLoader, registry); typeFilters.add(typeFilter); break; default: throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); } } for (String expression : filter.getStringArray("pattern")) { switch (filterType) { case ASPECTJ: typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader())); break; case REGEX: typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression))); break; default: throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType); } } return typeFilters; } private static void invokeAwareMethods(Object parserStrategyBean, Environment environment, ResourceLoader resourceLoader, BeanDefinitionRegistry registry) { if (parserStrategyBean instanceof Aware) { if (parserStrategyBean instanceof BeanClassLoaderAware) { ClassLoader classLoader = (registry instanceof ConfigurableBeanFactory) ? ((ConfigurableBeanFactory) registry).getBeanClassLoader() : resourceLoader.getClassLoader(); if (classLoader != null) { ((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader); } } if (parserStrategyBean instanceof BeanFactoryAware && registry instanceof BeanFactory) { ((BeanFactoryAware) parserStrategyBean).setBeanFactory((BeanFactory) registry); } if (parserStrategyBean instanceof EnvironmentAware) { ((EnvironmentAware) parserStrategyBean).setEnvironment(environment); } if (parserStrategyBean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) parserStrategyBean).setResourceLoader(resourceLoader); } } } }
[ "gunnar.hillert@oracle.com" ]
gunnar.hillert@oracle.com
f8d2c37934b074e4a2fbc0187aef545f0dcdf5fe
0203c612b12f5247b05e8c575820de2a593212b7
/Week6/Task10/src/sample/Controller.java
d4b8237fe6d0e812461577605bd9fe930a811a07
[]
no_license
VeselinTodorov2000/Java-OOP-2021
72995291f00f22cc552c26abac093a2400bb669c
98e4705de5e91bf9107d710f042fdc4b12cd064d
refs/heads/main
2023-06-04T01:49:25.221947
2021-06-21T20:22:17
2021-06-21T20:22:17
342,679,554
0
0
null
null
null
null
UTF-8
Java
false
false
1,945
java
package sample; import java.net.URL; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; public class Controller { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private Button btnCalculate; @FXML private Button btnQuit; @FXML private TextField txtDecimalNumber; @FXML private TextField txtOnesComplement; @FXML private TextField txtTwosComplement; @FXML private TextField txtSum; @FXML void btnCalculateOnAction(ActionEvent event) { byte entered = Byte.parseByte(txtDecimalNumber.getText()); byte onesComplement = (byte)(entered ^ 1); byte twosComplement = (byte)(onesComplement + 1); txtOnesComplement.setText(String.format("%d", onesComplement)); txtTwosComplement.setText(String.format("%d", twosComplement)); txtSum.setText(String.format("%d", onesComplement + twosComplement)); } @FXML void btnQuitOnAction(ActionEvent event) { Platform.exit(); } @FXML void initialize() { assert btnCalculate != null : "fx:id=\"btnCalculate\" was not injected: check your FXML file 'sample.fxml'."; assert btnQuit != null : "fx:id=\"btnQuit\" was not injected: check your FXML file 'sample.fxml'."; assert txtDecimalNumber != null : "fx:id=\"txtDecimalNumber\" was not injected: check your FXML file 'sample.fxml'."; assert txtOnesComplement != null : "fx:id=\"txtOnesComplement\" was not injected: check your FXML file 'sample.fxml'."; assert txtTwosComplement != null : "fx:id=\"txtTwosComplement\" was not injected: check your FXML file 'sample.fxml'."; assert txtSum != null : "fx:id=\"txtSum\" was not injected: check your FXML file 'sample.fxml'."; } }
[ "slavovt@uni-sofia.bg" ]
slavovt@uni-sofia.bg
eb665103d6cc1b3cf5c448483fe8e8e9a115d4ab
753c19c237b3a24a5e58938ba530b26284c2cbc2
/app/src/main/java/com/fred_w/demo/codercommunity/mvp/model/entity/AccessToken.java
42ca65f3e2044cb1fb1d9ac8a85441e5bba417dd
[]
no_license
wjl7123093/CoderCommunity
df1ecf810affe9b24b618e3c85e805a964132f63
766bbe98188d6319727cf83dfe6cba3bfdc7fd93
refs/heads/master
2021-09-04T08:57:09.162253
2018-01-17T13:57:31
2018-01-17T13:57:31
115,528,585
0
0
null
null
null
null
UTF-8
Java
false
false
1,651
java
package com.fred_w.demo.codercommunity.mvp.model.entity; /** * AccessToken Entity * * @author Fred_W * @version v1.0.0 * * @crdate 2017-12-31 * @update */ public class AccessToken { private int code; private String access_token; private String refresh_token; private String token_type; private int expires_in; private int uid; @Override public String toString() { return "AccessToken{" + "access_token='" + access_token + '\'' + ", refresh_token='" + refresh_token + '\'' + ", token_type='" + token_type + '\'' + ", expires_in=" + expires_in + ", uid=" + uid + '}'; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getRefresh_token() { return refresh_token; } public void setRefresh_token(String refresh_token) { this.refresh_token = refresh_token; } public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } }
[ "wjl7123093@163.com" ]
wjl7123093@163.com
141eda8136a251a4c14900d7319fa6c14a33121b
f2e83d1fcbfcca23313f5d12af309b71e686d106
/Desktop/KOSMO/workspace/java/KKosmo/src/object06/cooperation/Student.java
6a89b4b2121c66cb58fa0f98442135e0f4074358
[]
no_license
jason-moonKor/Kosmo0815class-Java
129a7c93fef5fd97d8a99fa8b99c96eb2c65a136
6875623bcd411a5f9a14c782bd805105bed03a83
refs/heads/main
2023-07-16T03:49:47.809679
2021-09-03T09:16:08
2021-09-03T09:16:08
402,705,729
0
0
null
null
null
null
UTF-8
Java
false
false
705
java
package object06.cooperation; public class Student { String studentName; public int grade; public int money; public int busFee = 1000; public int subFee = 1500; public Student(String studentName, int money) { this.studentName = studentName; this.money = money; } public void takeBus(Bus bus) { System.out.println(this.studentName + "이 버스를 탔습니다"); bus.take(busFee); this.money -= busFee; } public void takeSubway(Subway subway) { System.out.println(this.studentName+ "이 지하철을 탔습니다"); subway.take(subFee); this.money -= subFee; } public void showInfo() { System.out.println(studentName + "의 남은 돈은 " + money + "입니다."); } }
[ "jaesangv@naver.com" ]
jaesangv@naver.com
2ac25ae54e740bfe0885d2bc795bf7e634a6284c
091cf57a4726e99b8f6cf90f197ed96aae7fbead
/src/main/java/com/seezoon/service/modules/sys/entity/SysParam.java
7b13cd6bf4c84a656cedbe2b3ae9f73da6ced5b2
[]
no_license
734839030/seezoon-boot
5b3274b81ff4157778d1a83175ba4f7ccf4ad7ea
a965385c0b1b0f92114338cf0c0d2e2528e20455
refs/heads/master
2023-01-29T23:47:49.105120
2020-05-06T03:39:16
2020-05-06T03:39:16
155,083,708
14
8
null
2023-01-06T05:07:03
2018-10-28T15:07:14
JavaScript
UTF-8
Java
false
false
988
java
package com.seezoon.service.modules.sys.entity; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.seezoon.boot.common.entity.BaseEntity; /** * 系统参数 * * @author hdf 2018年4月1日 */ public class SysParam extends BaseEntity<String> { /** * */ private static final long serialVersionUID = 1L; /** * 名称 */ @NotNull @Length(min=1,max=50) private String name; /** * 键 */ @NotNull @Length(min=1,max=50) private String paramKey; /** * 值 */ @NotNull @Length(min=1,max=50) private String paramValue; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParamKey() { return paramKey; } public void setParamKey(String paramKey) { this.paramKey = paramKey; } public String getParamValue() { return paramValue; } public void setParamValue(String paramValue) { this.paramValue = paramValue; } }
[ "hdf@qq.com" ]
hdf@qq.com
c3db427afa86a9e7d6b4c49f3f2fd3c31446e3f2
4ebde5edac16dfb32adda59f6158c46b9db33d63
/src/CriarPersonagemMonstro.java
8ff3adb4f6853453e3d3c29ce605dce6c4e4a1bf
[]
no_license
giokittens/MonstroVCRobo
b914641cf00026ad84f07a0d356a133f89316907
d3c8f4e4258fd51d40c286ad2146f79249b83f8b
refs/heads/master
2020-09-06T00:11:40.180477
2019-11-07T15:23:03
2019-11-07T15:23:03
220,254,108
0
0
null
null
null
null
UTF-8
Java
false
false
10,797
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. */ /** * * @author Aluno */ public class CriarPersonagemMonstro extends javax.swing.JFrame { /** * Creates new form CriarPersonagemMonstro */ public CriarPersonagemMonstro() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { CampoAtaque = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); CampoNome = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); CampoHP = new javax.swing.JSlider(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); CampoDefesa = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); CampoAgilidade = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); CampoAtaque.setBackground(new java.awt.Color(51, 204, 255)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mostronnn.png"))); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N jLabel2.setText("Definição do Monstro"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Nome"); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("HP"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("Ataque"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("Defesa"); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setText("Agilidade"); jButton1.setText("Salvar"); javax.swing.GroupLayout CampoAtaqueLayout = new javax.swing.GroupLayout(CampoAtaque); CampoAtaque.setLayout(CampoAtaqueLayout); CampoAtaqueLayout.setHorizontalGroup( CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addGap(168, 168, 168) .addComponent(jLabel2) .addContainerGap(137, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, CampoAtaqueLayout.createSequentialGroup() .addContainerGap() .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton1)) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAgilidade, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(CampoHP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CampoNome) .addComponent(jTextField2) .addComponent(CampoDefesa)) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7)))) .addGap(37, 37, 37)) ); CampoAtaqueLayout.setVerticalGroup( CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(CampoAtaqueLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(CampoAtaqueLayout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoHP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(3, 3, 3) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoDefesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CampoAgilidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE) .addComponent(jButton1)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAtaque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CampoAtaque, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CriarPersonagemMonstro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CriarPersonagemMonstro().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField CampoAgilidade; private javax.swing.JPanel CampoAtaque; private javax.swing.JTextField CampoDefesa; private javax.swing.JSlider CampoHP; private javax.swing.JTextField CampoNome; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
[ "" ]
a86a455f36e3d711154d437cc8b782b312283b93
8d366835936f55d0db8f65492cdcca5990d400ef
/app/src/main/java/com/dgsw/doorlock/tool/task/GetRFIDTask.java
027f671a10fc1cc23d60f3f5d0716e83e5ff294b
[]
no_license
DGSWDoorlock/AndroidApp
a3e3818eb7636194df465fc50216d6c6f5e709a0
d85d4e9418e79c49ac6b1779fd2d0a8805342d63
refs/heads/master
2021-09-01T15:20:19.546500
2017-12-27T17:16:51
2017-12-27T17:16:51
114,576,343
0
0
null
null
null
null
UTF-8
Java
false
false
2,421
java
package com.dgsw.doorlock.tool.task; import android.os.AsyncTask; import android.util.Log; import com.dgsw.doorlock.data.EntryInfo; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import static com.dgsw.doorlock.activity.Main.IP_ADDRESS; /** * Created by kimji on 2017-12-17. */ public class GetRFIDTask extends AsyncTask<EntryInfo, Integer, String> { private final String id; private String RFID; public GetRFIDTask(String id) { this.id = id; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(EntryInfo[] infos) { try { URL Url = new URL(" http://" + IP_ADDRESS + ":8080/ENT_SYSTEM/webresources/com.dgsw.entinfo/" + URLEncoder.encode(id, "UTF-8"));//받을 주소 + ID HttpURLConnection conn = (HttpURLConnection) Url.openConnection();//연결해줄 Connection conn.setRequestMethod("GET");//POST 형식 conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true);//입력 가능 int Res = conn.getResponseCode(); if (Res != HttpURLConnection.HTTP_OK) Log.e("RESPONSE_CODE", Res + ""); BufferedReader br; try { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception e) { e.printStackTrace(); br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } String line = br.readLine(); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(line); RFID = jsonObject.get("rfid").toString(); br.close(); } catch (IOException | ParseException e) { e.printStackTrace(); } return RFID; } @Override protected void onProgressUpdate(Integer... params) { } @Override protected void onPostExecute(String result) { super.onPostExecute(result); } }
[ "kimjioh0927@gmail.com" ]
kimjioh0927@gmail.com
0e59eefffeadb8a78f60aced557956e19d091d11
7111b3e8d178b5084e9335f6dd8ebc345c4ee052
/array method return type.java
b6bfc4f2b28568364f2c4683c5f7c7e5296bc87a
[]
no_license
CanonJavaDev/practice
b0e92da11c2064c4b69628a458d189dd4c232412
559d13ce58f76912aed0d392264376bd89dbf51d
refs/heads/master
2021-01-17T16:03:09.058189
2017-02-23T23:32:15
2017-02-23T23:32:15
82,977,904
0
0
null
2017-02-23T23:32:16
2017-02-23T22:31:47
Java
UTF-8
Java
false
false
678
java
//array method return type class Test { int[] m1( ) //Method return type is array { System.out.println("Method----1"); int [ ] a = {10,20,30}; return a; } void m2(double[] d) // Method argument is array { System.out.println("Method---2"); for (double dd : d) { System.out.println(dd); } } public static void main(String[] args) { Test t =new Test(); // instance, constructor int[] x = t.m1(); for (int xx : x) { System.out.println(xx); } double[] d = {10.5,20.6,30.7}; t.m2(d); } } /* C:\Users\Ritesh\Desktop\corejava\Sample>java Test Method----1 10 20 30 Method---2 10.5 20.6 30.7 */
[ "ritesh@nallola.com" ]
ritesh@nallola.com
0285498a6419ca3032675a6ab49a342eff568449
b3f9f7bfbf69c52eb07daf3a6d041ad56fe95254
/src/main/java/com/lypgod/test/ThinkingInJava/Ch14_TypeInformation/Practice6/Shapes.java
5a67c8108ece56342c96a7582d1f415d3c475861
[]
no_license
lypgod/ThinkingInJavaPractice
33c13a8ad07648560d24060206db537e6d95aa76
b3ced3631e751c09914af6d47fe0e3c17846801a
refs/heads/master
2021-01-12T13:57:43.799008
2016-11-04T19:48:10
2016-11-04T19:48:10
69,253,448
0
0
null
null
null
null
UTF-8
Java
false
false
1,202
java
package com.lypgod.test.ThinkingInJava.Ch14_TypeInformation.Practice6;//: typeinfo/Shapes.java import java.util.Arrays; import java.util.List; abstract class Shape { void draw() { System.out.println(this + ".draw()"); } abstract public String toString(); } class Circle extends Shape { boolean flag = false; public String toString() { return (flag ? "H" : "Unh") + "ighlighted " + "Circle"; } } class Square extends Shape { boolean flag = false; public String toString() { return (flag ? "H" : "Unh") + "ighlighted " + "Square"; } } class Triangle extends Shape { boolean flag = false; public String toString() { return (flag ? "H" : "Unh") + "ighlighted " + "Triangle"; } } public class Shapes { public static void setFlag(Shape s) { if (s instanceof Triangle) ((Triangle) s).flag = true; } public static void main(String[] args) { // upcasting to Shape: List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle()); for (Shape shape : shapeList) { setFlag(shape); System.out.println(shape); } } }
[ "lypgod@hotmail.com" ]
lypgod@hotmail.com
94d8ee5116c6055eadf506691bdc24e2aae660b8
cec628def1aad94ccbefa814d2a0dbd51588e9bd
/css.lib/src/org/netbeans/modules/css/lib/ErrorNode.java
8a25d727f8630db671bdd52b96ae54844f454a5e
[]
no_license
emilianbold/netbeans-releases
ad6e6e52a896212cb628d4522a4f8ae685d84d90
2fd6dc84c187e3c79a959b3ddb4da1a9703659c7
refs/heads/master
2021-01-12T04:58:24.877580
2017-10-17T14:38:27
2017-10-17T14:38:27
78,269,363
30
15
null
2020-10-13T08:36:08
2017-01-07T09:07:28
null
UTF-8
Java
false
false
2,797
java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2011 Sun Microsystems, Inc. */ package org.netbeans.modules.css.lib; import org.netbeans.modules.css.lib.api.NodeType; import org.netbeans.modules.css.lib.api.ProblemDescription; /** * * @author marekfukala */ public class ErrorNode extends RuleNode { private ProblemDescription problemDescription; public ErrorNode(int from, int to, ProblemDescription pd, CharSequence source) { super(NodeType.error, source); this.from = from; this.to = to; this.problemDescription = pd; } @Override public NodeType type() { return NodeType.error; } public ProblemDescription getProblemDescription() { return problemDescription; } }
[ "mfukala@netbeans.org" ]
mfukala@netbeans.org
d1af097645c3a90b5f9f1d0617d49e938b65653c
154ee51b147a8aad410fc966bf3aec0ac16f33fa
/nrakpo/src/main/java/com/vidakovic/nrakpo/aspect/timer/PrometheusService.java
f2773bfea82dfb742f3dc59a8ab8e0bc57b4e067
[]
no_license
VidakovicDominik/nrakpo
3b81b0465abe7f3912ca8c48a06a1a63c762a7eb
a378304552eb7fb5dc5cda3b2f0f3ebf666fd2d4
refs/heads/master
2020-06-25T22:42:46.743751
2020-02-04T16:33:00
2020-02-04T16:33:00
199,443,322
0
0
null
null
null
null
UTF-8
Java
false
false
829
java
package com.vidakovic.nrakpo.aspect.timer; import io.micrometer.prometheus.PrometheusMeterRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.Duration; /** * <p> * <b>Title: TimerService </b> * </p> * <p> * <b> Description: * * * </b> * </p> * <p> * <b>Copyright:</b> Copyright (c) ETK 2020 * </p> * <p> * <b>Company:</b> Ericsson Nikola Tesla d.d. * </p> * * @author ezviddo * @version PA1 * <p> * <b>Version History:</b> * </p> * <br> * PA1 04-Feb-20 * @since 04-Feb-20 14:17:42 */ @Service public class PrometheusService { @Autowired PrometheusMeterRegistry meterRegistry; public void record(Duration duration, String meterName){ meterRegistry.timer(meterName).record(duration); } }
[ "dominik.vidakovic@ericsson.com" ]
dominik.vidakovic@ericsson.com
42699b2ed705503084df6cbb94b25d97977a8f25
f7393adbe4582f440ecbfe2b74562f25d3ae1b67
/Common/src/main/java/cn/qqtheme/framework/util/ScreenUtils.java
7d6eadfd12fff00776a706c3d59afdc217cc07e5
[ "Apache-2.0" ]
permissive
alicfeng/sise
b7a20329ca1c80cc575e8e9e2ad48364db4ec639
230dcdd417ca1b9b034d8c7d95ef193a446999e9
refs/heads/master
2021-06-16T16:42:29.309496
2017-05-15T12:05:29
2017-05-15T12:05:29
59,456,580
3
0
null
null
null
null
UTF-8
Java
false
false
2,923
java
package cn.qqtheme.framework.util; import android.app.Activity; import android.content.Context; import android.util.DisplayMetrics; import android.view.Window; import android.view.WindowManager; /** * 获取屏幕宽高等信息、全屏切换、保持屏幕常亮、截屏等 * * @author liyujiang[QQ:1032694760] * @since 2015/11/26 */ public final class ScreenUtils { private static boolean isFullScreen = false; /** * Display metrics display metrics. * * @param context the context * @return the display metrics */ public static DisplayMetrics displayMetrics(Context context) { DisplayMetrics dm = new DisplayMetrics(); WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); LogUtils.debug("screen width=" + dm.widthPixels + "px, screen height=" + dm.heightPixels + "px, densityDpi=" + dm.densityDpi + ", density=" + dm.density); return dm; } /** * Width pixels int. * * @param context the context * @return the int */ public static int widthPixels(Context context) { return displayMetrics(context).widthPixels; } /** * Height pixels int. * * @param context the context * @return the int */ public static int heightPixels(Context context) { return displayMetrics(context).heightPixels; } /** * Density float. * * @param context the context * @return the float */ public static float density(Context context) { return displayMetrics(context).density; } /** * Density dpi int. * * @param context the context * @return the int */ public static int densityDpi(Context context) { return displayMetrics(context).densityDpi; } /** * Is full screen boolean. * * @return the boolean */ public static boolean isFullScreen() { return isFullScreen; } /** * Toggle full displayMetrics. * * @param activity the activity */ public static void toggleFullScreen(Activity activity) { Window window = activity.getWindow(); int flagFullscreen = WindowManager.LayoutParams.FLAG_FULLSCREEN; if (isFullScreen) { window.clearFlags(flagFullscreen); isFullScreen = false; } else { window.setFlags(flagFullscreen, flagFullscreen); isFullScreen = true; } } /** * 保持屏幕常亮 * * @param activity the activity */ public static void keepBright(Activity activity) { //需在setContentView前调用 int keepScreenOn = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; activity.getWindow().setFlags(keepScreenOn, keepScreenOn); } }
[ "1096105191@qq.com" ]
1096105191@qq.com
8cc9391357e3ba391df696e8d8e07427fec76f45
540ed9a87297b21b506c2499493680f87f53c8af
/src/util/FileOutputStreamUtil.java
81177e643dbfe797f7f90d73261a87a2f5464a65
[]
no_license
sb0321/multipleThreadFolder
11da7f3aed4d94dcd01fba890bcc2bb0b78d1402
7ed54a1ec657cffa016e702190a6facccac4801e
refs/heads/master
2023-03-19T07:10:14.832194
2021-03-18T19:01:05
2021-03-18T19:01:05
349,180,825
0
0
null
null
null
null
UTF-8
Java
false
false
1,187
java
package util; import java.io.*; public class FileOutputStreamUtil { private final String THREAD_NAME; private static final String DIR_PROPERTY = "user.dir"; private static final String FOLDER = "/folder/"; private final String ROOT; public FileOutputStreamUtil(String name) { this.THREAD_NAME = name; ROOT = System.getProperty(DIR_PROPERTY) + FOLDER; System.out.println(ROOT); } public void makeDirIfDoesNotExist() { File root = new File(ROOT); File d = new File(ROOT + THREAD_NAME); if (!root.isDirectory() && root.mkdir()) { System.out.println("경로 생성: " + root.toPath()); } if(!d.isDirectory() && d.mkdir()) { System.out.println(THREAD_NAME + " 쓰레드의 폴더 생성: " + d.toPath()); } } public void makeFile(String name) { String fileName = name + ".txt"; try { FileWriter fileWriter = new FileWriter(ROOT + THREAD_NAME + "/" + fileName); fileWriter.write(name); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
[ "woltaryksb1@gmail.com" ]
woltaryksb1@gmail.com
60283471f43d72fd32eab6074306cc03f98749a9
c8556e99c99ae77ed78732694771c1420b1ae75e
/common-tools/src/main/java/design/first/commons/tools/RSACoder.java
6238788d56503ffc34ef7e7d9be7dcf52397401e
[]
no_license
First2019/maven-cloud
6de7afdb15a6b1cc1a323b1f52b0935dbae46f87
f3913775fb5da9c61bbbf08fb0a8c3c23997867b
refs/heads/master
2023-03-18T19:34:20.057767
2021-03-18T06:12:06
2021-03-18T06:12:06
325,499,755
0
0
null
null
null
null
UTF-8
Java
false
false
8,107
java
package design.first.commons.tools; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; /** * 非对称加密算法RSA算法组件 * 非对称算法一般是用来传送对称加密算法的密钥来使用的,相对于DH算法,RSA算法只需要一方构造密钥,不需要 * 大费周章的构造各自本地的密钥对了。DH算法只能算非对称算法的底层实现。而RSA算法实现起来较为简单 */ public class RSACoder { //非对称密钥算法 public static final String KEY_ALGORITHM = "RSA"; /** * 密钥长度,DH算法的默认密钥长度是1024 * 密钥长度必须是64的倍数,在512到65536位之间 */ private static final int KEY_SIZE = 512; //公钥 private static final String PUBLIC_KEY = "RSAPublicKey"; //私钥 private static final String PRIVATE_KEY = "RSAPrivateKey"; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //初始化密钥 //生成密钥对 Map<String, Object> keyMap = initKey(); //公钥 byte[] publicKey =getPublicKey(keyMap); //私钥 byte[] privateKey = getPrivateKey(keyMap); System.out.println("byte公钥12:\n" + publicKey[5]); String s = Base64.encodeBase64String(publicKey); byte[] bytes = Base64.decodeBase64(s); System.out.println("byte公钥12:\n" + bytes[5]); System.out.println("Base64公钥:\n" + Base64.encodeBase64String(publicKey)); System.out.println("Base64私钥:\n" + Base64.encodeBase64String(privateKey)); System.out.println("================密钥对构造完毕,甲方将公钥公布给乙方,开始进行加密数据的传输============="); String str = "RSA密码交换算法"; System.out.println("\n===========甲方向乙方发送加密数据=============="); System.out.println("原文:" + str); //甲方进行数据的加密 byte[] code1 = encryptByPrivateKey(str.getBytes(), privateKey); System.out.println("加密后的数据:" + Base64.encodeBase64String(code1)); System.out.println("===========乙方使用甲方提供的公钥对数据进行解密=============="); //乙方进行数据的解密 byte[] decode1 = decryptByPublicKey(code1, publicKey); System.out.println("乙方解密后的数据:" + new String(decode1) + "\n\n"); System.out.println("===========反向进行操作,乙方向甲方发送数据==============\n\n"); str = "乙方向甲方发送数据RSA算法"; System.out.println("原文:" + str); //乙方使用公钥对数据进行加密 byte[] code2 = encryptByPublicKey(str.getBytes(), publicKey); System.out.println("===========乙方使用公钥对数据进行加密=============="); System.out.println("加密后的数据:" + Base64.encodeBase64String(code2)); System.out.println("=============乙方将数据传送给甲方======================"); System.out.println("===========甲方使用私钥对数据进行解密=============="); //甲方使用私钥对数据进行解密 byte[] decode2 = decryptByPrivateKey(code2, privateKey); System.out.println("甲方解密后的数据:" + new String(decode2)); } /** * 初始化密钥对 * @return Map 甲方密钥的Map */ public static Map<String, Object> initKey() throws Exception { //实例化密钥生成器 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); //初始化密钥生成器 keyPairGenerator.initialize(KEY_SIZE); //生成密钥对 KeyPair keyPair = keyPairGenerator.generateKeyPair(); //甲方公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); //甲方私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); //将密钥存储在map中 Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * 私钥加密 * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception { //取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); //数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * 公钥加密 * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 */ public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //初始化公钥 //密钥材料转换 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); //产生公钥 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); //数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pubKey); return cipher.doFinal(data); } /** * 私钥解密 * * @param data 待解密数据 * @param key 私密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception { //取得私钥 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //生成私钥 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec); //数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } /** * 公钥解密 * * @param data 待解密数据 * @param key 密钥 * @return byte[] 解密数据 */ public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //初始化公钥 //密钥材料转换 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); //产生公钥 PublicKey pubKey = keyFactory.generatePublic(x509KeySpec); //数据解密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pubKey); return cipher.doFinal(data); } /** * 取得私钥 * * @param keyMap 密钥map * @return byte[] 私钥 */ public static byte[] getPrivateKey(Map<String, Object> keyMap) { Key key = (Key) keyMap.get(PRIVATE_KEY); return key.getEncoded(); } /** * 取得公钥 * * @param keyMap 密钥map * @return byte[] 公钥 */ public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return key.getEncoded(); } }
[ "790867216@qq.com" ]
790867216@qq.com
7870cb3344e6d063567ba3666d80ff86a8ed3f79
2b981496f2b1194101926ad32a5372444ed72ba3
/src/MainWithoutClasses.java
6de7045b94cd9c1060d9a71a4d3a557aa7d05804
[]
no_license
nguyen41v/Comp131-Lab-5
282b2937101a1eaf44501922d13c8a67705fe180
977332afdb711e9ac78cfae70a32ce089a33f340
refs/heads/master
2020-04-10T20:45:12.526702
2018-03-07T20:11:38
2018-03-07T20:11:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,774
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.Math; import java.util.ArrayList; import java.util.Arrays; public class MainWithoutClasses { /* constant for the data file */ public static String FILE_PATH = "src/active-businesses.tsv"; /* constants for column indices */ public static int FORMAL_NAME_INDEX = 0; public static int INFORMAL_NAME_INDEX = 1; public static int ADDRESS_INDEX = 2; public static int CITY_INDEX = 3; public static int ZIP_CODE_INDEX = 4; public static int CATEGORY_INDEX = 5; public static int START_DATE_INDEX = 6; public static int LATITUDE_INDEX = 7; public static int LONGITUDE_INDEX = 8; /* Oxy's coordinates */ public static double OXY_LATITUDE = 34.126813; public static double OXY_LONGITUDE = -118.211904; /* 1 degree longitude is about 57 miles (at 34 latitude) */ public static double DEGREES_TO_MILES = 57; /** * Reads * @return a list of businesses, each a list of strings */ public static ArrayList<ArrayList<String>> read_businesses() { ArrayList<ArrayList<String>> businesses = new ArrayList<ArrayList<String>>(); ArrayList<String> lines = read_lines(); int i = 0; while (i < lines.size()) { String line = lines.get(i); ArrayList<String> business = line_to_business(lines.get(i)); businesses.add(business); i ++; } return businesses; } /** * Reads data file into a list of strings. * * @return an ArrayList of strings, each a line in the data file */ public static ArrayList<String> read_lines() { ArrayList<String> lines = new ArrayList<String>(); String line = ""; try { BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH)); line = reader.readLine(); while (line != null) { lines.add(line); line = reader.readLine(); } } catch (IOException e) { System.out.println("Working Directory is " + System.getProperty("user.dir") + "."); System.out.println("Cannot find '" + FILE_PATH + "'; quitting."); System.exit(1); } return lines; } /** * Converts a line of data into multiple fields * * @param line a line from the data file * @return the different fields, as strings */ public static ArrayList<String> line_to_business(String line) { // this creates a list of strings from a single line of the data file // each string corresponds to a field - formal name, informal name, address, etc. ArrayList<String> fields = new ArrayList<String>(Arrays.asList(line.split("\t"))); // we are using the list of strings to represent the business, so we just return it return fields; } /** * Calculates the distance of a coordinate from Oxy * * @param business the target business * @param latitude the latitude of the destination * @param longitude the longitude of the destination * @return the distance from Oxy, in miles */ public static double distance_from(ArrayList<String> business, double latitude, double longitude) { double biz_lat = get_latitude(business); double biz_long = get_longitude(business); double lat_diff = biz_lat - latitude; double long_diff = biz_long - longitude; double coord_dist = java.lang.Math.sqrt((lat_diff * lat_diff) + (long_diff * long_diff)); return coord_dist * DEGREES_TO_MILES; } /** * Extracts the latitude from a business * * @param business the target business * @return the latitude of the business */ public static double get_latitude(ArrayList<String> business) { double lat = Double.parseDouble(business.get(LATITUDE_INDEX)); return lat; } /** * Extracts the longitude from a business * * @param business the target business * @return the longitude of the business */ public static double get_longitude(ArrayList<String> business) { double lon = Double.parseDouble(business.get(LONGITUDE_INDEX)); return lon; } /** * Determines if a business is categorized as a restaurant * * @param business the target business * @return true if the business is a restaurant, false otherwise */ public static boolean is_restaurant(ArrayList<String> business) { // note: to compare Strings, DO NOT use == // instead, use the .equals method // For example, DO NOT DO // // if ("hello" == "world") { ... } // // Instead, do // // if ("hello".equals("world")) { ... } String Businessname = business.get(CATEGORY_INDEX); return Businessname.equals("Full-service restaurants"); } /** * Determines if a business is a restaurant within a mile of Oxy * * @param business the target business * @return true if the business is a restaurant near Oxy, false otherwise */ public static boolean is_restaurant_near_oxy(ArrayList<String> business) { //double latitude = get_latitude(business); //double longitude = get_longitude(business); double distance = distance_from(business, OXY_LATITUDE, OXY_LONGITUDE); return (is_restaurant(business) && distance < 1); } /** * Prints the name of a business * * @param business the target business */ public static void print_business_name(ArrayList<String> business) { // see note in is_restaurant about comparing Strings // if (business.get(INFORMAL_NAME_INDEX).equals("")){ System.out.println(business.get(FORMAL_NAME_INDEX)); }else if (!business.get(INFORMAL_NAME_INDEX).equals("")) { System.out.println(business.get(INFORMAL_NAME_INDEX));} } /** * Print the names of restaurants near Oxy */ public static void main(String[] args) { ArrayList<ArrayList<String>> businesses = read_businesses(); int biz_index = 0; while (biz_index < businesses.size()) { ArrayList<String> business = businesses.get(biz_index); if (is_restaurant_near_oxy(business)) { print_business_name(business); } biz_index ++; } } }
[ "vietvanessa@gmail.com" ]
vietvanessa@gmail.com
d317e905f0747313430bf337323d902fdff44899
618bff98f8b0b2e0258b4ef069ff373ee3b7cc76
/app/src/main/java/com/atozmak/devtfdemo/entities/ArticleDetail.java
4b6be5125dffc185a0e9ca6a4a019b35ec01581d
[]
no_license
lostinthefall/DevtfDemo
2388d48e0fdf4255ed778a1f8d3fdb79c55e26d1
8b6e24804916819473566538a1604eaa9b07ce1c
refs/heads/master
2020-07-05T05:04:53.603308
2016-03-20T08:31:01
2016-03-20T08:31:01
54,305,874
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
package com.atozmak.devtfdemo.entities; /** * Created by Mak on 2016/3/19. */ public class ArticleDetail { public String postId; public String content; public ArticleDetail() { } public ArticleDetail(String postId, String content) { this.postId = postId; this.content = content; } }
[ "zhuangyinwu@gmail.com" ]
zhuangyinwu@gmail.com
a1c76c0e8dabed6d2e87142198f3b61b3bf66b08
00dd0e5eaa44900f3e147e332b80ea06bcf407aa
/src/com/aerospike/benchmarks/Workload.java
dcf16e6f6ec530463ccaf0b95be54fd0dc4ff2c1
[]
no_license
aminer/llist-benchmark-tool
e7fd024200fd68134bb62ee5280471ad4ef04f6f
eefe1542e0a4ee7cd73e6b27cb04e0d3f56ae8ac
refs/heads/master
2016-09-05T19:11:03.463053
2015-07-17T22:56:44
2015-07-17T22:56:44
37,932,398
0
0
null
null
null
null
UTF-8
Java
false
false
1,034
java
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements WHICH ARE COMPATIBLE WITH THE APACHE LICENSE, VERSION 2.0. * * 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.aerospike.benchmarks; /** * Benchmark workload type. */ public enum Workload { /** * Initialize data with sequential key writes. */ INITIALIZE, /** * Read/Update. Perform random key, random read all bins or write all bins workload. */ READ_UPDATE, }
[ "rihane.amine@hotmail.com" ]
rihane.amine@hotmail.com
72ab146ef737d5813f6cd8cb654b080803e7603d
122e91f41ecdb52826b2b9af1b0d57ab9d9d6117
/app/src/androidTest/java/net/skhu/androidmidtest/ExampleInstrumentedTest.java
99ccfbbd2459499391f502dddce49f619bf82ba8
[]
no_license
anpiso/androidMidTest
5dd671230f14a74441e066a0b8af275a8fbf3e9a
dd07bb55555f1b91f2ba9f8fbf1453de12e60099
refs/heads/master
2022-06-08T11:49:30.288648
2020-05-06T08:51:11
2020-05-06T08:51:11
261,082,708
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package net.skhu.androidmidtest; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.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() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("net.skhu.androidmidtest", appContext.getPackageName()); } }
[ "ehdwnd9238@gmail.com" ]
ehdwnd9238@gmail.com
ccb6eaab68d640031985fc733177cdb5a0d9f9fe
b7478c7cacc237ae56f34986fa1bfcb7416dcb6e
/main/java/utils/JwtUtil.java
bbbdabdd873e5f1ee4006e47ee902271450bfa82
[]
no_license
Semperdecus/Kwetter
ee775526efb5877c857d64df2b8ed6b8528796e3
b0f3a6235f34aba56c292b58f5f664342fe85b5b
refs/heads/master
2023-01-10T05:01:05.851025
2019-06-08T20:44:26
2019-06-08T20:44:26
171,243,102
0
0
null
2023-01-01T07:57:25
2019-02-18T08:22:45
Java
UTF-8
Java
false
false
5,208
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 utils; import java.util.Date; import javax.xml.bind.DatatypeConverter; import models.Account; import io.jsonwebtoken.*; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.Key; import java.util.Properties; import javax.crypto.spec.SecretKeySpec; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import gherkin.deps.com.google.gson.JsonObject; import static io.jsonwebtoken.security.Keys.secretKeyFor; import java.io.IOException; import javax.crypto.spec.SecretKeySpec; import javax.json.JsonArray; /** * * @author teren */ public class JwtUtil { /** * Expiration time of JWT token in milliseconds 604 800 000 = 1 week */ private final long EXPIRATIONTIME = 604800000; public JwtUtil() { } public String makeAccountJwtToken(String id, String issuer, Account account) throws IOException { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setId(id) .setIssuedAt(now) .setSubject(createJSONAccount(account)) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); Date exp; //if it has been specified, let's add the expiration if (EXPIRATIONTIME >= 0) { long expMillis = nowMillis + EXPIRATIONTIME; exp = new Date(expMillis); builder.setExpiration(exp); } JsonObject token = new JsonObject(); token.addProperty("token", builder.compact()); token.addProperty("expiresIn", exp.toString()); //Builds the JWT and serializes it to a compact, URL-safe string return token.toString(); } public String apiKey() throws IOException { String apiKey = null; InputStream inputStream = null; try { Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { prop.load(inputStream); } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } Date time = new Date(System.currentTimeMillis()); // get the property value and print it out apiKey = prop.getProperty("apiKey"); } catch (Exception e) { System.out.println("Exception: " + e); } finally { inputStream.close(); } return apiKey; } public String createJSONAccount(Account account) { String jsonInString = ""; ObjectMapper mapper = new ObjectMapper(); try { // Convert object to JSON string jsonInString = mapper.writeValueAsString(account); // System.out.println(jsonInString); // Convert object to JSON string and pretty print //jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(account); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonInString; } public boolean validateJwt(String jwsString) throws IOException { String[] splited = jwsString.split(" "); int length = splited.length; //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey()); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); Jws<Claims> jws; try { jws = Jwts.parser() .setSigningKey(signingKey) .parseClaimsJws(splited[length -1]); return true; } catch (JwtException ex) { ex.printStackTrace(); // we *cannot* use the JWT as intended by its creator } return false; } }
[ "terence@simdo.nl" ]
terence@simdo.nl
44a2514ea63c78a736f19c50d7ab26fd63fdd22e
e605abef2bfe8283c73a8013c0efcbb80ae8bac3
/src/main/java/com/ngo/cg/exception/NoSuchDonationException.java
fca68b7009488f903c2ddc44cf967f3b0be11243
[]
no_license
sriaashritha/NGO
e46710719529787a55ad490517101dbaa3cd05bf
3201ed768b57a0f5feae5c209fc53b794884ac5b
refs/heads/master
2023-03-31T00:34:23.625092
2021-03-30T19:36:06
2021-03-30T19:36:06
353,118,995
0
0
null
null
null
null
UTF-8
Java
false
false
224
java
package com.ngo.cg.exception; public class NoSuchDonationException extends Exception { private static final long serialVersionUID = 1L; public NoSuchDonationException(String errorMessage) { super(errorMessage); } }
[ "vtu9510@veltechuniv.edu.in" ]
vtu9510@veltechuniv.edu.in
67328021694558e9a6704e1fad62b2b40a8fb061
353ae5b753263a68af145c3d624952040618f7b6
/src/main/java/com/dao/AddrMapper.java
81d1c7e29b0d62aa406a8e73160c747b20c9925f
[]
no_license
snowfengjia/jianhuoShop
2d982297cbf5f77fcb15ad82ea63a350511e7511
705cf25f4489b4d2440b8febdc0b7c35180ec2b2
refs/heads/master
2020-03-25T22:56:34.150478
2018-11-14T10:17:12
2018-11-14T10:17:12
144,251,863
2
0
null
null
null
null
UTF-8
Java
false
false
766
java
package com.dao; import java.util.List; import java.util.Map; import com.pojo.Addr; /** * @author Administrator * 订单状态mapper */ public interface AddrMapper { int deleteByPrimaryKey(Integer fid); int insert(Addr record); int insertSelective(Addr record); Addr selectByPrimaryKey(Integer fid); int updateByPrimaryKeySelective(Addr record); int updateByPrimaryKey(Addr record); public Addr checkUname(Map<String, Object> uname); // 查询所有信息 public List<Addr> getAll(Map<String, Object> map); // 获取条数 public int getCount(Map<String, Object> po); // 分页 public List<Addr> getByPage(Map<String, Object> map); // 模糊查询并分页 public List<Addr> select(Map<String, Object> map); }
[ "f17521089278@163.com" ]
f17521089278@163.com
23b4fb7124343906e567716598945109310ea1f5
87b691743c3024ad1798b45fc868e22c45a4cbce
/src/main/java/net/floodlightcontroller/packetstreamer/PacketStreamerHandler.java
402dffdb989fd0bb52e5f99a21a81306df82693b
[ "Apache-2.0" ]
permissive
jimmyoic/floodlight-qosmanager
97b7ac3934a1363c4c4f664bbddf375c35440387
4d20272ed68aec92433c834c31a6ebaea0063b51
refs/heads/master
2021-01-09T23:42:13.155477
2015-01-07T13:39:48
2015-01-07T13:39:48
21,138,890
12
4
null
null
null
null
UTF-8
Java
false
false
6,900
java
package net.floodlightcontroller.packetstreamer; import net.floodlightcontroller.core.annotations.LogMessageCategory; import net.floodlightcontroller.core.annotations.LogMessageDoc; import net.floodlightcontroller.core.annotations.LogMessageDocs; import net.floodlightcontroller.packetstreamer.thrift.*; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Map; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The PacketStreamer handler class that implements the service APIs. */ @LogMessageCategory("OpenFlow Message Tracing") public class PacketStreamerHandler implements PacketStreamer.Iface { /** * The queue wrapper class that contains the queue for the streamed packets. */ protected class SessionQueue { protected BlockingQueue<ByteBuffer> pQueue; /** * The queue wrapper constructor */ public SessionQueue() { this.pQueue = new LinkedBlockingQueue<ByteBuffer>(); } /** * The access method to get to the internal queue. */ public BlockingQueue<ByteBuffer> getQueue() { return this.pQueue; } } /** * The class logger object */ protected static Logger log = LoggerFactory.getLogger(PacketStreamerServer.class); /** * A sessionId-to-queue mapping */ protected Map<String, SessionQueue> msgQueues; /** * The handler's constructor */ public PacketStreamerHandler() { this.msgQueues = new ConcurrentHashMap<String, SessionQueue>(); } /** * The implementation for getPackets() function. * This is a blocking API. * * @param sessionid * @return A list of packets associated with the session */ @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Interrupted while waiting for session start", explanation="The thread was interrupted waiting " + "for the packet streamer session to start", recommendation=LogMessageDoc.CHECK_CONTROLLER), @LogMessageDoc(level="ERROR", message="Interrupted while waiting for packets", explanation="The thread was interrupted waiting " + "for packets", recommendation=LogMessageDoc.CHECK_CONTROLLER), }) public List<ByteBuffer> getPackets(String sessionid) throws org.apache.thrift.TException { List<ByteBuffer> packets = new ArrayList<ByteBuffer>(); int count = 0; while (!msgQueues.containsKey(sessionid) && count++ < 100) { log.debug("Queue for session {} doesn't exist yet.", sessionid); try { Thread.sleep(100); // Wait 100 ms to check again. } catch (InterruptedException e) { log.error("Interrupted while waiting for session start"); } } if (count < 100) { SessionQueue pQueue = msgQueues.get(sessionid); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); // Block if queue is empty try { packets.add(queue.take()); queue.drainTo(packets); } catch (InterruptedException e) { log.error("Interrupted while waiting for packets"); } } return packets; } /** * The implementation for pushMessageSync() function. * * @param msg * @return 1 for success, 0 for failure * @throws TException */ @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Could not push empty message", explanation="An empty message was sent to the packet streamer", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG), @LogMessageDoc(level="ERROR", message="queue for session {sessionId} is null", explanation="The queue for the packet streamer session " + "is missing", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG), }) public int pushMessageSync(Message msg) throws org.apache.thrift.TException { if (msg == null) { log.error("Could not push empty message"); return 0; } List<String> sessionids = msg.getSessionIDs(); for (String sid : sessionids) { SessionQueue pQueue = null; if (!msgQueues.containsKey(sid)) { pQueue = new SessionQueue(); msgQueues.put(sid, pQueue); } else { pQueue = msgQueues.get(sid); } log.debug("pushMessageSync: SessionId: " + sid + " Receive a message, " + msg.toString() + "\n"); ByteBuffer bb = ByteBuffer.wrap(msg.getPacket().getData()); //ByteBuffer dst = ByteBuffer.wrap(msg.getPacket().toString().getBytes()); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); if (queue != null) { if (!queue.offer(bb)) { log.error("Failed to queue message for session: " + sid); } else { log.debug("insert a message to session: " + sid); } } else { log.error("queue for session {} is null", sid); } } return 1; } /** * The implementation for pushMessageAsync() function. * * @param msg * @throws TException */ @Override public void pushMessageAsync(Message msg) throws org.apache.thrift.TException { pushMessageSync(msg); return; } /** * The implementation for terminateSession() function. * It removes the session to queue association. * @param sessionid * @throws TException */ @Override public void terminateSession(String sessionid) throws org.apache.thrift.TException { if (!msgQueues.containsKey(sessionid)) { return; } SessionQueue pQueue = msgQueues.get(sessionid); log.debug("terminateSession: SessionId: " + sessionid + "\n"); String data = "FilterTimeout"; ByteBuffer bb = ByteBuffer.wrap(data.getBytes()); BlockingQueue<ByteBuffer> queue = pQueue.getQueue(); if (queue != null) { if (!queue.offer(bb)) { log.error("Failed to queue message for session: " + sessionid); } msgQueues.remove(sessionid); } else { log.error("queue for session {} is null", sessionid); } } }
[ "jimmyoic@gmail.com" ]
jimmyoic@gmail.com
d0ae45a9dbce69419fe70e78a8d88e8c1ba0f5da
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_e67d2acfe8112a311fdb5af31767119d184d6362/Pointer/11_e67d2acfe8112a311fdb5af31767119d184d6362_Pointer_s.java
dbbb1e084bcc6e694e59a8d1a2d37f4656603592
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
152,476
java
/* * BridJ - Dynamic and blazing-fast native interop for Java. * http://bridj.googlecode.com/ * * Copyright (c) 2010-2013, Olivier Chafik (http://ochafik.com/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.bridj; import org.bridj.util.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.nio.*; import java.lang.annotation.Annotation; import java.util.*; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import static org.bridj.SizeT.safeIntCast; /** * Pointer to a native memory location.<br> * Pointer is the entry point of any pointer-related operation in BridJ. * <p> * <u><b>Manipulating memory</b></u> * <p> * <ul> * <li>Wrapping a memory address as a pointer : {@link Pointer#pointerToAddress(long)} * </li> * <li>Reading / writing a primitive from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}()} / {@link Pointer#set${prim.CapName}(${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}()} / {@link Pointer#set${sizePrim}(long)} <br> #end *</li> * <li>Reading / writing the nth contiguous primitive value from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}AtIndex(long)} / {@link Pointer#set${prim.CapName}AtIndex(long, ${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}AtIndex(long)} / {@link Pointer#set${sizePrim}AtIndex(long, long)} <br> #end *</li> * <li>Reading / writing a primitive from / to the pointed memory location with a byte offset:<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}AtOffset(long)} / {@link Pointer#set${prim.CapName}AtOffset(long, ${prim.Name})} <br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}AtOffset(long)} / {@link Pointer#set${sizePrim}AtOffset(long, long)} <br> #end *</li> * <li>Reading / writing an array of primitives from / to the pointed memory location :<br> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}s(int)} / {@link Pointer#set${prim.CapName}s(${prim.Name}[])} ; With an offset : {@link Pointer#get${prim.CapName}sAtOffset(long, int)} / {@link Pointer#set${prim.CapName}sAtOffset(long, ${prim.Name}[])}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}s(int)} / {@link Pointer#set${sizePrim}s(long[])} ; With an offset : {@link Pointer#get${sizePrim}sAtOffset(long, int)} / {@link Pointer#set${sizePrim}sAtOffset(long, long[])}<br> #end * </li> * <li>Reading / writing an NIO buffer of primitives from / to the pointed memory location :<br> #foreach ($prim in $primitivesNoBool) #if ($prim.Name != "char")* {@link Pointer#get${prim.BufferName}(long)} (can be used for writing as well) / {@link Pointer#set${prim.CapName}s(${prim.BufferName})}<br> #end #end * </li> * <li>Reading / writing a String from / to the pointed memory location using the default charset :<br> #foreach ($string in ["C", "WideC"]) * {@link Pointer#get${string}String()} / {@link Pointer#set${string}String(String)} ; With an offset : {@link Pointer#get${string}StringAtOffset(long)} / {@link Pointer#set${string}StringAtOffset(long, String)}<br> #end * </li> * <li>Reading / writing a String with control on the charset :<br> * {@link Pointer#getStringAtOffset(long, StringType, Charset)} / {@link Pointer#setStringAtOffset(long, String, StringType, Charset)}<br> * </ul> * <p> * <u><b>Allocating memory</b></u> * <p> * <ul> * <li>Getting the pointer to a struct / a C++ class / a COM object : * {@link Pointer#pointerTo(NativeObject)} * </li> * <li>Allocating a dynamic callback (without a static {@link Callback} definition, which would be the preferred way) :<br> * {@link Pointer#allocateDynamicCallback(DynamicCallback, org.bridj.ann.Convention.Style, Type, Type[])} * </li> * <li>Allocating a primitive with / without an initial value (zero-initialized) :<br> #foreach ($prim in $primitives) * {@link Pointer#pointerTo${prim.CapName}(${prim.Name})} / {@link Pointer#allocate${prim.CapName}()}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}(long)} / {@link Pointer#allocate${sizePrim}()}<br> #end * </li> * <li>Allocating an array of primitives with / without initial values (zero-initialized) :<br> #foreach ($prim in $primitivesNoBool) * {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])} or {@link Pointer#pointerTo${prim.CapName}s(${prim.BufferName})} / {@link Pointer#allocate${prim.CapName}s(long)}<br> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}s(long[])} / {@link Pointer#allocate${sizePrim}s(long)}<br> #end * {@link Pointer#pointerToBuffer(Buffer)} / n/a<br> * </li> * <li>Allocating a native String :<br> #foreach ($string in ["C", "WideC"]) * {@link Pointer#pointerTo${string}String(String) } (default charset)<br> #end * {@link Pointer#pointerToString(String, StringType, Charset) }<br> * </li> * <li>Allocating a {@link ListType#Dynamic} Java {@link java.util.List} that uses native memory storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list):<br> * {@link Pointer#allocateList(Class, long) } * </li> * <li>Transforming a pointer to a Java {@link java.util.List} that uses the pointer as storage (think of getting back the pointer with {@link NativeList#getPointer()} when you're done mutating the list, if it's {@link ListType#Dynamic}) :<br> * {@link Pointer#asList(ListType) }<br> * {@link Pointer#asList() }<br> * </li> * </ul> * <p> * <u><b>Casting pointers</b></u> * <p> * <ul> * <li>Cast a pointer to a {@link DynamicFunction} :<br> * {@link Pointer#asDynamicFunction(org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } * </li> * <li>Cast a pointer to a {@link StructObject} or a {@link Callback} (as the ones generated by <a href="http://code.google.com/p/jnaerator/">JNAerator</a>) <br>: * {@link Pointer#as(Class) } * </li> * <li>Cast a pointer to a complex type pointer (use {@link org.bridj.cpp.CPPType#getCPPType(Object[])} to create a C++ template type, for instance) :<br> * {@link Pointer#as(Type) } * </li> * <li>Get an untyped pointer :<br> * {@link Pointer#asUntyped() } * </li> * </ul> * <p> * <u><b>Dealing with pointer bounds</b></u> * <p> * <ul> * <li>Pointers to memory allocated through Pointer.pointerTo*, Pointer.allocate* have validity bounds that help prevent buffer overflows, at least when the Pointer API is used * </li> * <li>{@link Pointer#offset(long)}, {@link Pointer#next(long)} and other similar methods retain pointer bounds * </li> * <li>{@link Pointer#getValidBytes()} and {@link Pointer#getValidElements()} return the amount of valid memory readable from the pointer * </li> * <li>Bounds can be declared manually with {@link Pointer#validBytes(long)} (useful for memory allocated by native code) * </li> * </ul> */ public abstract class Pointer<T> implements Comparable<Pointer<?>>, Iterable<T> { #macro (declareCheckedPeerAtOffset $byteOffset $validityCheckLength) long checkedPeer = peer + $byteOffset; if (validStart != UNKNOWN_VALIDITY && ( checkedPeer < validStart || (checkedPeer + $validityCheckLength) > validEnd )) { invalidPeer(checkedPeer, $validityCheckLength); } #end #macro (declareCheckedPeer $validityCheckLength) #declareCheckedPeerAtOffset("0", $validityCheckLength) #end #macro (docAllocateCopy $cPrimName $primWrapper) /** * Allocate enough memory for a single $cPrimName value, copy the value provided in argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param value initial value for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName value given in argument */ #end #macro (docAllocateArrayCopy $cPrimName $primWrapper) /** * Allocate enough memory for values.length $cPrimName values, copy the values provided as argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon : <pre>{@code for (float f : pointerTo(1f, 2f, 3.3f)) System.out.println(f); }</pre> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName consecutive values provided in argument */ #end #macro (docAllocateArray2DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 2D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 2D C array would be */ #end #macro (docAllocateArray3DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 3D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 3D C array would be */ #end #macro (docAllocate $cPrimName $primWrapper) /** * Allocate enough memory for a $cPrimName value and return a pointer to it.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * @return pointer to a single zero-initialized $cPrimName value */ #end #macro (docAllocateArray $cPrimName $primWrapper) /** * Allocate enough memory for arrayLength $cPrimName values and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon. * @return pointer to arrayLength zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray2D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @return pointer to dim1 * dim2 zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray3D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 * dim3 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * @return pointer to dim1 * dim2 * dim3 zero-initialized $cPrimName consecutive values */ #end #macro (docGet $cPrimName $primWrapper) /** * Read a $cPrimName value from the pointed memory location */ #end #macro (docGetOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Read a $cPrimName value from the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docGetIndex $typeName $equivalentOffsetCall) /** * Read the nth contiguous $typeName value from the pointed memory location.<br> * Equivalent to <code>${equivalentOffsetCall}</code>. * @param valueIndex index of the value to read */ #end #macro (docGetArray $cPrimName $primWrapper) /** * Read an array of $cPrimName values of the specified length from the pointed memory location */ #end #macro (docGetRemainingArray $cPrimName $primWrapper) /** * Read the array of remaining $cPrimName values from the pointed memory location */ #end #macro (docGetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Read an array of $cPrimName values of the specified length from the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docSet $cPrimName $primWrapper) /** * Write a $cPrimName value to the pointed memory location */ #end #macro (docSetOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Write a $cPrimName value to the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end #macro (docSetIndex $typeName $equivalentOffsetCall) /** * Write the nth contiguous $typeName value to the pointed memory location.<br> * Equivalent to <code>${equivalentOffsetCall}</code>. * @param valueIndex index of the value to write * @param value $typeName value to write */ #end #macro (docSetArray $cPrimName $primWrapper) /** * Write an array of $cPrimName values to the pointed memory location */ #end #macro (docSetArrayOffset $cPrimName $primWrapper $signatureWithoutOffset) /** * Write an array of $cPrimName values to the pointed memory location shifted by a byte offset * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues). Please favour {@link $signatureWithoutOffset} over this method. */ #end /** The NULL pointer is <b>always</b> Java's null value */ public static final Pointer NULL = null; /** * Size of a pointer in bytes. <br> * This is 4 bytes in a 32 bits environment and 8 bytes in a 64 bits environment.<br> * Note that some 64 bits environments allow for 32 bits JVM execution (using the -d32 command line argument for Sun's JVM, for instance). In that case, Java programs will believe they're executed in a 32 bits environment. */ public static final int SIZE = Platform.POINTER_SIZE; static { Platform.initLibrary(); } protected static long UNKNOWN_VALIDITY = -1; protected static long NO_PARENT = 0/*-1*/; /** * Default alignment used to allocate memory from the static factory methods in Pointer class (any value lower or equal to 1 means no alignment) */ public static final int defaultAlignment = Integer.parseInt(Platform.getenvOrProperty("BRIDJ_DEFAULT_ALIGNMENT", "bridj.defaultAlignment", "-1")); protected final PointerIO<T> io; protected final long peer, offsetInParent; protected final Pointer<?> parent; protected volatile Object sibling; protected final long validStart, validEnd; /** * Object responsible for reclamation of some pointed memory when it's not used anymore. */ public interface Releaser { void release(Pointer<?> p); } Pointer(PointerIO<T> io, long peer, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, Object sibling) { this.io = io; this.peer = peer; this.validStart = validStart; this.validEnd = validEnd; this.parent = parent; this.offsetInParent = offsetInParent; this.sibling = sibling; if (peer == 0) throw new IllegalArgumentException("Pointer instance cannot have NULL peer ! (use null Pointer instead)"); if (BridJ.debugPointers) creationTrace = new RuntimeException().fillInStackTrace(); } Throwable creationTrace; #foreach ($data in [ ["Ordered", true, ""], ["Disordered", false, "_disordered"] ]) #set ($orderingPrefix = $data.get(0)) #set ($ordered = $data.get(1)) #set ($nativeSuffix = $data.get(2)) static class ${orderingPrefix}Pointer<T> extends Pointer<T> { ${orderingPrefix}Pointer(PointerIO<T> io, long peer, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, Object sibling) { super(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } @Override public boolean isOrdered() { return $ordered; } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end @Override public Pointer<T> set${prim.CapName}(${prim.Name} value) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setInt((int)value); #end #declareCheckedPeer(${primSize}) #if ($prim.Name != "byte" && $prim.Name != "boolean") JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); #else JNI.set_${prim.Name}(checkedPeer, value); #end return this; } @Override public Pointer<T> set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setIntAtOffset(byteOffset, (int)value); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize}") #if ($prim.Name != "byte" && $prim.Name != "boolean") JNI.set_${prim.Name}${nativeSuffix}(checkedPeer, value); #else JNI.set_${prim.Name}(checkedPeer, value); #end return this; } @Override public ${prim.Name} get${prim.CapName}() { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return (char)getInt(); #end #declareCheckedPeer(${primSize}) #if ($prim.Name != "byte" && $prim.Name != "boolean") return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); #else return JNI.get_${prim.Name}(checkedPeer); #end } @Override public ${prim.Name} get${prim.CapName}AtOffset(long byteOffset) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return (char)getIntAtOffset(byteOffset); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize}") #if ($prim.Name != "byte" && $prim.Name != "boolean") return JNI.get_${prim.Name}${nativeSuffix}(checkedPeer); #else return JNI.get_${prim.Name}(checkedPeer); #end } #end #foreach ($sizePrim in ["SizeT", "CLong"]) #macro (setPrimitiveValue $primName $peer $value) #if ($primName != "byte" && $primName != "boolean") JNI.set_${primName}${nativeSuffix}($peer, $value); #else JNI.set_${primName}($peer, value); #end #end @Override public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length) { if (values == null) throw new IllegalArgumentException("Null values"); if (${sizePrim}.SIZE == 8) { setLongsAtOffset(byteOffset, values, valuesOffset, length); } else { int n = length; #declareCheckedPeerAtOffset("byteOffset" "n * 4") long peer = checkedPeer; int valuesIndex = valuesOffset; for (int i = 0; i < n; i++) { int value = (int)values[valuesIndex]; #setPrimitiveValue("int" "peer" "value") peer += 4; valuesIndex++; } } return this; } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, int[] values) { if (${sizePrim}.SIZE == 4) { setIntsAtOffset(byteOffset, values); } else { int n = values.length; #declareCheckedPeerAtOffset("byteOffset" "n * 8") long peer = checkedPeer; for (int i = 0; i < n; i++) { int value = values[i]; #setPrimitiveValue("long" "peer" "value") peer += 8; } } return this; } #end } #end /** * Create a {@code Pointer<T>} type. <br> * For Instance, {@code Pointer.pointerType(Integer.class) } returns a type that represents {@code Pointer<Integer> } */ public static Type pointerType(Type targetType) { return org.bridj.util.DefaultParameterizedType.paramType(Pointer.class, targetType); } /** * Create a {@code IntValuedEnum<T>} type. <br> * For Instance, {@code Pointer.intEnumType(SomeEnum.class) } returns a type that represents {@code IntValuedEnum<SomeEnum> } */ public static <E extends Enum<E>> Type intEnumType(Class<? extends IntValuedEnum<E>> targetType) { return org.bridj.util.DefaultParameterizedType.paramType(IntValuedEnum.class, targetType); } /** * Manually release the memory pointed by this pointer if it was allocated on the Java side.<br> * If the pointer is an offset version of another pointer (using {@link Pointer#offset(long)} or {@link Pointer#next(long)}, for instance), this method tries to release the original pointer.<br> * If the memory was not allocated from the Java side, this method does nothing either.<br> * If the memory was already successfully released, this throws a RuntimeException. * @throws RuntimeException if the pointer was already released */ public synchronized void release() { Object sibling = this.sibling; this.sibling = null; if (sibling instanceof Pointer) ((Pointer)sibling).release(); } /** * Compare to another pointer based on pointed addresses. * @param p other pointer * @return 1 if this pointer's address is greater than p's (or if p is null), -1 if the opposite is true, 0 if this and p point to the same memory location. */ //@Override public int compareTo(Pointer<?> p) { if (p == null) return 1; long p1 = getPeer(), p2 = p.getPeer(); return p1 == p2 ? 0 : p1 < p2 ? -1 : 1; } /** * Compare the byteCount bytes at the memory location pointed by this pointer to the byteCount bytes at the memory location pointer by other using the C @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcmp/">memcmp</a> function.<br> * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytes(Pointer<?> other, long byteCount) { return compareBytesAtOffset(0, other, 0, byteCount); } /** * Compare the byteCount bytes at the memory location pointed by this pointer shifted by byteOffset to the byteCount bytes at the memory location pointer by other shifted by otherByteOffset using the C @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcmp/">memcmp</a> function.<br> * @deprecated Avoid using the byte offset methods variants unless you know what you're doing (may cause alignment issues) * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytesAtOffset(long byteOffset, Pointer<?> other, long otherByteOffset, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") return JNI.memcmp(checkedPeer, other.getCheckedPeer(otherByteOffset, byteCount), byteCount); } /** * Compute a hash code based on pointed address. */ @Override public int hashCode() { int hc = new Long(getPeer()).hashCode(); return hc; } @Override public String toString() { return "Pointer(peer = 0x" + Long.toHexString(getPeer()) + ", targetType = " + Utils.toString(getTargetType()) + ", order = " + order() + ")"; } protected final void invalidPeer(long peer, long validityCheckLength) { throw new IndexOutOfBoundsException("Cannot access to memory data of length " + validityCheckLength + " at offset " + (peer - getPeer()) + " : valid memory start is " + validStart + ", valid memory size is " + (validEnd - validStart)); } private final long getCheckedPeer(long byteOffset, long validityCheckLength) { #declareCheckedPeerAtOffset("byteOffset" "validityCheckLength") return checkedPeer; } /** * Returns a pointer which address value was obtained by this pointer's by adding a byte offset.<br> * The returned pointer will prevent the memory associated to this pointer from being automatically reclaimed as long as it lives, unless Pointer.release() is called on the originally-allocated pointer. * @param byteOffset offset in bytes of the new pointer vs. this pointer. The expression {@code p.offset(byteOffset).getPeer() - p.getPeer() == byteOffset} is always true. */ public Pointer<T> offset(long byteOffset) { return offset(byteOffset, getIO()); } <U> Pointer<U> offset(long byteOffset, PointerIO<U> pio) { if (byteOffset == 0) return pio == this.io ? (Pointer<U>)this : as(pio); long newPeer = getPeer() + byteOffset; Object newSibling = getSibling() != null ? getSibling() : this; if (validStart == UNKNOWN_VALIDITY) return newPointer(pio, newPeer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, newSibling); if (newPeer > validEnd || newPeer < validStart) throw new IndexOutOfBoundsException("Invalid pointer offset : " + byteOffset + " (validBytes = " + getValidBytes() + ") !"); return newPointer(pio, newPeer, isOrdered(), validStart, validEnd, null, NO_PARENT, null, newSibling); } /** * Creates a pointer that has the given number of valid bytes ahead.<br> * If the pointer was already bound, the valid bytes must be lower or equal to the current getValidBytes() value. */ public Pointer<T> validBytes(long byteCount) { long peer = getPeer(); long newValidEnd = peer + byteCount; if (validStart == peer && validEnd == newValidEnd) return this; if (validEnd != UNKNOWN_VALIDITY && newValidEnd > validEnd) throw new IndexOutOfBoundsException("Cannot extend validity of pointed memory from " + validEnd + " to " + newValidEnd); Object newSibling = getSibling() != null ? getSibling() : this; return newPointer(getIO(), peer, isOrdered(), validStart, newValidEnd, parent, offsetInParent, null, newSibling); } /** * Creates a pointer that forgot any memory validity information.<br> * Such pointers are typically faster than validity-aware pointers, since they perform less checks at each operation, but they're more prone to crashes if misused. * @deprecated Pointers obtained via this method are faster but unsafe and are likely to cause crashes hard to debug if your logic is wrong. */ @Deprecated public Pointer<T> withoutValidityInformation() { long peer = getPeer(); if (validStart == UNKNOWN_VALIDITY) return this; Object newSibling = getSibling() != null ? getSibling() : this; return newPointer(getIO(), peer, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, parent, offsetInParent, null, newSibling); } /** * Creates a copy of the pointed memory location (allocates a new area of memory) and returns a pointer to it.<br> * The pointer's bounds must be known (see {@link Pointer#getValidBytes()}, {@link Pointer#validBytes(long)} or {@link Pointer#validElements(long)}). */ public Pointer<T> clone() { long length = getValidElements(); if (length < 0) throw new UnsupportedOperationException("Number of bytes unknown, unable to clone memory (use validBytes(long))"); Pointer<T> c = allocateArray(getIO(), length); copyTo(c); return c; } /** * Creates a pointer that has the given number of valid elements ahead.<br> * If the pointer was already bound, elementCount must be lower or equal to the current getValidElements() value. */ public Pointer<T> validElements(long elementCount) { return validBytes(elementCount * getIO("Cannot define elements validity").getTargetSize()); } /** * Returns a pointer to this pointer.<br> * It will only succeed if this pointer was dereferenced from another pointer.<br> * Let's take the following C++ code : * <pre>{@code int** pp = ...; int* p = pp[10]; int** ref = &p; ASSERT(pp == ref); }</pre> * Here is its equivalent Java code : * <pre>{@code Pointer<Pointer<Integer>> pp = ...; Pointer<Integer> p = pp.get(10); Pointer<Pointer<Integer>> ref = p.getReference(); assert pp.equals(ref); }</pre> */ public Pointer<Pointer<T>> getReference() { if (parent == null) throw new UnsupportedOperationException("Cannot get reference to this pointer, it wasn't created from Pointer.getPointer(offset) or from a similar method."); PointerIO io = getIO(); return parent.offset(offsetInParent).as(io == null ? null : io.getReferenceIO()); } /** * Get the address of the memory pointed to by this pointer ("cast this pointer to long", in C jargon).<br> * This is equivalent to the C code {@code (size_t)&pointer} * @return Address of the memory pointed to by this pointer */ public final long getPeer() { return peer; } /** * Create a native callback which signature corresponds to the provided calling convention, return type and parameter types, and which redirects calls to the provided Java {@link org.bridj.DynamicCallback} handler.<br/> * For instance, a callback of C signature <code>double (*)(float, int)</code> that adds its two arguments can be created with :<br> * <code>{@code * Pointer callback = Pointer.allocateDynamicCallback( * new DynamicCallback<Integer>() { * public Double apply(Object... args) { * float a = (Float)args[0]; * int b = (Integer)args[1]; * return (double)(a + b); * } * }, * null, // Use the platform's default calling convention * int.class, // return type * float.class, double.class // parameter types * ); * }</code><br> * For the <code>void</code> return type, you can use {@link java.lang.Void} :<br> * <code>{@code * Pointer callback = Pointer.allocateDynamicCallback( * new DynamicCallback<Void>() { * public Void apply(Object... args) { * ... * return null; // Void cannot be instantiated anyway ;-) * } * }, * null, // Use the platform's default calling convention * int.class, // return type * float.class, double.class // parameter types * ); * }</code><br> * @return Pointer to a native callback that redirects calls to the provided Java callback instance, and that will be destroyed whenever the pointer is released (make sure you keep a reference to it !) */ public static <R> Pointer<DynamicFunction<R>> allocateDynamicCallback(DynamicCallback<R> callback, org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { if (callback == null) throw new IllegalArgumentException("Java callback handler cannot be null !"); if (returnType == null) throw new IllegalArgumentException("Callback return type cannot be null !"); if (parameterTypes == null) throw new IllegalArgumentException("Invalid (null) list of parameter types !"); try { MethodCallInfo mci = new MethodCallInfo(returnType, parameterTypes, false); Method method = DynamicCallback.class.getMethod("apply", Object[].class); mci.setMethod(method); mci.setJavaSignature("([Ljava/lang/Object;)Ljava/lang/Object;"); mci.setCallingConvention(callingConvention); mci.setGenericCallback(true); mci.setJavaCallback(callback); //System.out.println("Java sig return CRuntime.createCToJavaCallback(mci, DynamicCallback.class); } catch (Exception ex) { throw new RuntimeException("Failed to allocate dynamic callback for convention " + callingConvention + ", return type " + Utils.toString(returnType) + " and parameter types " + Arrays.asList(parameterTypes) + " : " + ex, ex); } } /** * Cast this pointer to another pointer type * @param newIO */ public <U> Pointer<U> as(PointerIO<U> newIO) { return viewAs(isOrdered(), newIO); } /** * Create a view of this pointer that has the byte order provided in argument, or return this if this pointer already uses the requested byte order. * @param order byte order (endianness) of the returned pointer */ public Pointer<T> order(ByteOrder order) { if (order.equals(ByteOrder.nativeOrder()) == isOrdered()) return this; return viewAs(!isOrdered(), getIO()); } /** * Get the byte order (endianness) of this pointer. */ public ByteOrder order() { ByteOrder order = isOrdered() ? ByteOrder.nativeOrder() : ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; return order; } <U> Pointer<U> viewAs(boolean ordered, PointerIO<U> newIO) { if (newIO == io && ordered == isOrdered()) return (Pointer<U>)this; else return newPointer(newIO, getPeer(), ordered, getValidStart(), getValidEnd(), getParent(), getOffsetInParent(), null, getSibling() != null ? getSibling() : this); } /** * Get the PointerIO instance used by this pointer to get and set pointed values. */ public final PointerIO<T> getIO() { return io; } /** * Whether this pointer reads data in the system's native byte order or not. * See {@link Pointer#order()}, {@link Pointer#order(ByteOrder)} */ public abstract boolean isOrdered(); final long getOffsetInParent() { return offsetInParent; } final Pointer<?> getParent() { return parent; } final Object getSibling() { return sibling; } final long getValidEnd() { return validEnd; } final long getValidStart() { return validStart; } /** * Cast this pointer to another pointer type<br> * Synonym of {@link Pointer#as(Class)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); * }</code><br> * @param <U> type of the elements pointed by the returned pointer * @param type type of the elements pointed by the returned pointer * @return pointer to type U elements at the same address as this pointer */ public <U> Pointer<U> as(Type type) { PointerIO<U> pio = PointerIO.getInstance(type); return as(pio); } /** * Cast this pointer to another pointer type.<br> * Synonym of {@link Pointer#as(Type)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); // or pointerT.as(U.class); * }</code><br> * @param <U> type of the elements pointed by the returned pointer * @param type type of the elements pointed by the returned pointer * @return pointer to type U elements at the same address as this pointer */ public <U> Pointer<U> as(Class<U> type) { return as((Type)type); } /** * Cast this pointer as a function pointer to a function that returns the specified return type and takes the specified parameter types.<br> * See for instance the following C code that uses a function pointer : * <pre>{@code * double (*ptr)(int, const char*) = someAddress; * double result = ptr(10, "hello"); * }</pre> * Its Java equivalent with BridJ is the following : * <pre>{@code * DynamicFunction ptr = someAddress.asDynamicFunction(null, double.class, int.class, Pointer.class); * double result = (Double)ptr.apply(10, pointerToCString("hello")); * }</pre> * Also see {@link CRuntime#getDynamicFunctionFactory(org.bridj.NativeLibrary, org.bridj.ann.Convention.Style, java.lang.reflect.Type, java.lang.reflect.Type[]) } for more options. * @param callingConvention calling convention used by the function (if null, default is typically {@link org.bridj.ann.Convention.Style#CDecl}) * @param returnType return type of the function * @param parameterTypes parameter types of the function */ public <R> DynamicFunction<R> asDynamicFunction(org.bridj.ann.Convention.Style callingConvention, Type returnType, Type... parameterTypes) { return CRuntime.getInstance().getDynamicFunctionFactory(null, callingConvention, returnType, parameterTypes).newInstance(this); } /** * Cast this pointer to an untyped pointer.<br> * Synonym of {@code ptr.as((Class<?>)null)}.<br> * See {@link Pointer#as(Class)}<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * void* pointer = (void*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<?> pointer = pointerT.asUntyped(); // or pointerT.as((Class<?>)null); * }</code><br> * @return untyped pointer pointing to the same address as this pointer */ public Pointer<?> asUntyped() { return as((Class<?>)null); } /** * Get the amount of memory known to be valid from this pointer, or -1 if it is unknown.<br> * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) * @return amount of bytes that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getValidBytes() { long ve = getValidEnd(); return ve == UNKNOWN_VALIDITY ? -1 : ve - getPeer(); } /** * Get the amount of memory known to be valid from this pointer (expressed in elements of the target type, see {@link Pointer#getTargetType()}) or -1 if it is unknown.<br> * Memory validity information is available when the pointer was allocated by BridJ (with {@link Pointer#allocateBytes(long)}, for instance), created out of another pointer which memory validity information is available (with {@link Pointer#offset(long)}, {@link Pointer#next()}, {@link Pointer#next(long)}) or created from a direct NIO buffer ({@link Pointer#pointerToBuffer(Buffer)}, {@link Pointer#pointerToInts(IntBuffer)}...) * @return amount of elements that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getValidElements() { long bytes = getValidBytes(); long elementSize = getTargetSize(); if (bytes < 0 || elementSize <= 0) return -1; return bytes / elementSize; } /** * Returns an iterator over the elements pointed by this pointer.<br> * If this pointer was allocated from Java with the allocateXXX, pointerToXXX methods (or is a view or a clone of such a pointer), the iteration is safely bounded.<br> * If this iterator is just a wrapper for a native-allocated pointer (or a view / clone of such a pointer), iteration will go forever (until illegal areas of memory are reached and cause a JVM crash). */ public ListIterator<T> iterator() { return new ListIterator<T>() { Pointer<T> next = Pointer.this.getValidElements() != 0 ? Pointer.this : null; Pointer<T> previous; //@Override public T next() { if (next == null) throw new NoSuchElementException(); T value = next.get(); previous = next; long valid = next.getValidElements(); next = valid < 0 || valid > 1 ? next.next(1) : null; return value; } //@Override public void remove() { throw new UnsupportedOperationException(); } //@Override public boolean hasNext() { long rem; return next != null && ((rem = next.getValidBytes()) < 0 || rem > 0); } //@Override public void add(T o) { throw new UnsupportedOperationException(); } //@Override public boolean hasPrevious() { return previous != null; } //@Override public int nextIndex() { throw new UnsupportedOperationException(); } //@Override public T previous() { //TODO return previous; throw new UnsupportedOperationException(); } //@Override public int previousIndex() { throw new UnsupportedOperationException(); } //@Override public void set(T o) { if (previous == null) throw new NoSuchElementException("You haven't called next() prior to calling ListIterator.set(E)"); previous.set(o); } }; } /** * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) */ public static <N extends NativeObject> Pointer<N> pointerTo(N instance) { return pointerTo(instance, null); } /** * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) */ public static <N extends NativeObjectInterface> Pointer<N> pointerTo(N instance) { return (Pointer)pointerTo((NativeObject)instance); } /** * Get a pointer to a native object, specifying the type of the pointer's target.<br> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static <R extends NativeObject> Pointer<R> pointerTo(NativeObject instance, Type targetType) { return instance == null ? null : (Pointer<R>)instance.peer; } /** * Get the address of a native object, specifying the type of the pointer's target (same as {@code pointerTo(instance, targetType).getPeer()}, see {@link Pointer#pointerTo(NativeObject, Type)}).<br> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static long getAddress(NativeObject instance, Class targetType) { return getPeer(pointerTo(instance, targetType)); } #docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Type)") public <O extends NativeObject> O getNativeObjectAtOffset(long byteOffset, Type type) { return (O)BridJ.createNativeObjectFromPointer((Pointer<O>)(byteOffset == 0 ? this : offset(byteOffset)), type); } #docSet("native object", "O extends NativeObject") public <O extends NativeObject> Pointer<T> setNativeObject(O value, Type type) { BridJ.copyNativeObjectToAddress(value, type, (Pointer)this); return this; } #docGetOffset("native object", "O extends NativeObject", "Pointer#getNativeObject(Class)") public <O extends NativeObject> O getNativeObjectAtOffset(long byteOffset, Class<O> type) { return (O)getNativeObjectAtOffset(byteOffset, (Type)type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Class<O> type) { return (O)getNativeObject((Type)type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Type type) { O o = (O)getNativeObjectAtOffset(0, type); return o; } /** * Check that the pointer's peer is aligned to the target type alignment. * @throws RuntimeException If the target type of this pointer is unknown * @return getPeer() % alignment == 0 */ public boolean isAligned() { return isAligned(getIO("Cannot check alignment").getTargetAlignment()); } /** * Check that the pointer's peer is aligned to the given alignment. * If the pointer has no peer, this method returns true. * @return getPeer() % alignment == 0 */ public boolean isAligned(long alignment) { return isAligned(getPeer(), alignment); } /** * Check that the provided address is aligned to the given alignment. * @return address % alignment == 0 */ protected static boolean isAligned(long address, long alignment) { return computeRemainder(address, alignment) == 0; } protected static int computeRemainder(long address, long alignment) { switch ((int)alignment) { case -1: case 0: case 1: return 0; case 2: return (int)(address & 1); case 4: return (int)(address & 3); case 8: return (int)(address & 7); case 16: return (int)(address & 15); case 32: return (int)(address & 31); case 64: return (int)(address & 63); default: if (alignment < 0) return 0; return (int)(address % alignment); } } /** * Dereference this pointer (*ptr).<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) printf("%i\n", *array); }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { System.out.println("%i\n".format(array.get())); array = array.next(); } }</pre> Here is a simpler equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int value : array) // array knows its size, so we can iterate on it System.out.println("%i\n".format(value)); }</pre> @throws RuntimeException if called on an untyped {@code Pointer<?>} instance (see {@link Pointer#getTargetType()}) */ public T get() { return get(0); } /** * Returns null if pointer is null, otherwise dereferences the pointer (calls pointer.get()). */ public static <T> T get(Pointer<T> pointer) { return pointer == null ? null : pointer.get(); } /** Gets the n-th element from this pointer.<br> This is equivalent to the C/C++ square bracket syntax.<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; int index = 5; int value = array[index]; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); int index = 5; int value = array.get(index); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @throws RuntimeException if called on an untyped {@code Pointer<?>} instance ({@link Pointer#getTargetType()}) */ public T get(long index) { return getIO("Cannot get pointed value").get(this, index); } /** Assign a value to the pointed memory location, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).<br> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) { int value = index; *array = value; } }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { int value = index; array.set(value); array = array.next(); } }</pre> @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) */ public T set(T value) { return set(0, value); } private static long getTargetSizeToAllocateArrayOrThrow(PointerIO<?> io) { long targetSize = -1; if (io == null || (targetSize = io.getTargetSize()) < 0) throwBecauseUntyped("Cannot allocate array "); return targetSize; } private static void throwBecauseUntyped(String message) { throw new RuntimeException("Pointer is not typed (call Pointer.as(Type) to create a typed pointer) : " + message); } static void throwUnexpected(Throwable ex) { throw new RuntimeException("Unexpected error", ex); } /** Sets the n-th element from this pointer, and return it (different behaviour from {@link List\#set(int, Object)} which returns the old value of that element !!!).<br> This is equivalent to the C/C++ square bracket assignment syntax.<br> Take the following C++ code fragment : <pre>{@code float* array = new float[10]; int index = 5; float value = 12; array[index] = value; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; ... Pointer<Float> array = allocateFloats(10); int index = 5; float value = 12; array.set(index, value); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @param value value to set at pointed memory location @throws RuntimeException if called on a raw and untyped {@code Pointer} instance (see {@link Pointer#asUntyped()} and {@link Pointer#getTargetType()}) @return The value that was given (not the old value as in {@link List\#set(int, Object)} !!!) */ public T set(long index, T value) { getIO("Cannot set pointed value").set(this, index, value); return value; } /** * Get a pointer's peer (see {@link Pointer#getPeer}), or zero if the pointer is null. */ public static long getPeer(Pointer<?> pointer) { return pointer == null ? 0 : pointer.getPeer(); } /** * Get the unitary size of the pointed elements in bytes. * @throws RuntimeException if the target type is unknown (see {@link Pointer#getTargetType()}) */ public long getTargetSize() { return getIO("Cannot compute target size").getTargetSize(); } /** * Returns a pointer to the next target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return next(1) */ public Pointer<T> next() { return next(1); } /** * Returns a pointer to the n-th next (or previous) target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return offset(getTargetSize() * delta) */ public Pointer<T> next(long delta) { return offset(getIO("Cannot get pointers to next or previous targets").getTargetSize() * delta); } /** * Release pointers, if they're not null (see {@link Pointer#release}). */ public static void release(Pointer... pointers) { for (Pointer pointer : pointers) if (pointer != null) pointer.release(); } /** * Test equality of the pointer using the address.<br> * @return true if and only if obj is a Pointer instance and {@code obj.getPeer() == this.getPeer() } */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Pointer)) return false; Pointer p = (Pointer)obj; return getPeer() == p.getPeer(); } /** * Create a pointer out of a native memory address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == address } */ @Deprecated public static Pointer<?> pointerToAddress(long peer) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, long size) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, Class<P> targetClass, final Releaser releaser) { return pointerToAddress(peer, (Type)targetClass, releaser); } /** * Create a pointer out of a native memory address * @param targetType type of the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, Type targetType, final Releaser releaser) { PointerIO<P> pio = PointerIO.getInstance(targetType); return newPointer(pio, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, releaser, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io, Releaser releaser) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, Releaser releaser) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static Pointer<?> pointerToAddress(long peer, long size, Releaser releaser) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static <P> Pointer<P> pointerToAddress(long peer, long size, PointerIO<P> io, Releaser releaser) { return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static <P> Pointer<P> pointerToAddress(long peer, Class<P> targetClass) { return pointerToAddress(peer, (Type)targetClass); } /** * Create a pointer out of a native memory address * @param targetType type of the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static <P> Pointer<P> pointerToAddress(long peer, Type targetType) { return newPointer((PointerIO<P>)PointerIO.getInstance(targetType), peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> pointerToAddress(long peer, long size, PointerIO<U> io) { return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> newPointer( PointerIO<U> io, long peer, boolean ordered, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, final Releaser releaser, Object sibling) { if (peer == 0) return null; if (validEnd != UNKNOWN_VALIDITY) { long size = validEnd - validStart; if (size <= 0) return null; } if (releaser == null) { if (ordered) { return new OrderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } else { return new DisorderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling); } } else { assert sibling == null; #macro (bodyOfPointerWithReleaser) private volatile Releaser rel = releaser; //@Override public synchronized void release() { if (rel != null) { Releaser rel = this.rel; this.rel = null; rel.release(this); } } protected void finalize() { release(); } @Deprecated public synchronized Pointer<U> withReleaser(final Releaser beforeDeallocation) { final Releaser thisReleaser = rel; rel = null; return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation == null ? thisReleaser : new Releaser() { //@Override public void release(Pointer<?> p) { beforeDeallocation.release(p); if (thisReleaser != null) thisReleaser.release(p); } }, null); } #end if (ordered) { return new OrderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { #bodyOfPointerWithReleaser() }; } else { return new DisorderedPointer<U>(io, peer, validStart, validEnd, parent, offsetInParent, sibling) { #bodyOfPointerWithReleaser() }; } } } #docAllocate("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointer(Class<P> type) { return (Pointer<P>)(Pointer)allocate(PointerIO.getInstance(type)); } #docAllocateArray("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointers(Class<P> type, long arrayLength) { return (Pointer<P>)(Pointer)allocateArray(PointerIO.getInstance(type), arrayLength); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Class<P> targetType) { return allocatePointer((Type)targetType); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Type targetType) { return (Pointer<Pointer<P>>)(Pointer)allocate(PointerIO.getPointerInstance(targetType)); } /** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Type targetType) { return allocatePointer(pointerType(targetType)); }/** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Class<P> targetType) { return allocatePointerPointer((Type)targetType); } #docAllocate("untyped pointer", "Pointer<?>") /** * Create a memory area large enough to hold an untyped pointer. * @return a pointer to a new memory area large enough to hold a single untyped pointer */ public static <V> Pointer<Pointer<?>> allocatePointer() { return (Pointer)allocate(PointerIO.getPointerInstance()); } #docAllocateArray("untyped pointer", "Pointer<?>") public static Pointer<Pointer<?>> allocatePointers(int arrayLength) { return (Pointer<Pointer<?>>)(Pointer)allocateArray(PointerIO.getPointerInstance(), arrayLength); } /** * Create a memory area large enough to hold an array of arrayLength typed pointers. * @param targetType target type of element pointers in the resulting pointer array. * @param arrayLength size of the allocated array, in elements * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers */ public static <P> Pointer<Pointer<P>> allocatePointers(Class<P> targetType, int arrayLength) { return allocatePointers((Type)targetType, arrayLength); } /** * Create a memory area large enough to hold an array of arrayLength typed pointers. * @param targetType target type of element pointers in the resulting pointer array. * @param arrayLength size of the allocated array, in elements * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers */ public static <P> Pointer<Pointer<P>> allocatePointers(Type targetType, int arrayLength) { return (Pointer<Pointer<P>>)(Pointer)allocateArray(PointerIO.getPointerInstance(targetType), arrayLength); // TODO } /** * Create a memory area large enough to a single items of type elementClass. * @param elementClass type of the array elements * @return a pointer to a new memory area large enough to hold a single item of type elementClass. */ public static <V> Pointer<V> allocate(Class<V> elementClass) { return allocate((Type)elementClass); } /** * Create a memory area large enough to a single items of type elementClass. * @param elementClass type of the array elements * @return a pointer to a new memory area large enough to hold a single item of type elementClass. */ public static <V> Pointer<V> allocate(Type elementClass) { return allocateArray(elementClass, 1); } /** * Create a memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve the element * @return a pointer to a new memory area large enough to hold one item of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocate(PointerIO<V> io) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io), null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param arrayLength length of the array in elements * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength, final Releaser beforeDeallocation) { return allocateBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, beforeDeallocation); } /** * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param io PointerIO instance able to store and retrieve elements of the array * @param byteSize length of the array in bytes * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes */ public static <V> Pointer<V> allocateBytes(PointerIO<V> io, long byteSize, final Releaser beforeDeallocation) { return allocateAlignedBytes(io, byteSize, defaultAlignment, beforeDeallocation); } /** * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}), ensuring the pointer to the memory is aligned to the provided boundary. * @param io PointerIO instance able to store and retrieve elements of the array * @param byteSize length of the array in bytes * @param alignment boundary to which the returned pointer should be aligned * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes */ public static <V> Pointer<V> allocateAlignedBytes(PointerIO<V> io, long byteSize, int alignment, final Releaser beforeDeallocation) { if (byteSize == 0) return null; if (byteSize < 0) throw new IllegalArgumentException("Cannot allocate a negative amount of memory !"); long address, offset = 0; if (alignment <= 1) address = JNI.mallocNulled(byteSize); else { //address = JNI.mallocNulledAligned(byteSize, alignment); //if (address == 0) { // invalid alignment (< sizeof(void*) or not a power of 2 address = JNI.mallocNulled(byteSize + alignment - 1); long remainder = address % alignment; if (remainder > 0) offset = alignment - remainder; } } if (address == 0) throw new RuntimeException("Failed to allocate " + byteSize); Pointer<V> ptr = newPointer(io, address, true, address, address + byteSize + offset, null, NO_PARENT, beforeDeallocation == null ? freeReleaser : new Releaser() { //@Override public void release(Pointer<?> p) { beforeDeallocation.release(p); freeReleaser.release(p); } }, null); if (offset > 0) ptr = ptr.offset(offset); return ptr; } /** * Create a pointer that depends on this pointer and will call a releaser prior to release this pointer, when it is GC'd.<br> * This pointer MUST NOT be used anymore. * @deprecated This method can easily be misused and is reserved to advanced users. * @param beforeDeallocation releaser that should be run before this pointer's releaser (if any). * @return a new pointer to the same memory location as this pointer */ @Deprecated public synchronized Pointer<T> withReleaser(final Releaser beforeDeallocation) { return newPointer(getIO(), getPeer(), isOrdered(), getValidStart(), getValidEnd(), null, NO_PARENT, beforeDeallocation, null); } static Releaser freeReleaser = new FreeReleaser(); static class FreeReleaser implements Releaser { //@Override public void release(Pointer<?> p) { assert p.getSibling() == null; assert p.validStart == p.getPeer(); if (BridJ.debugPointers) BridJ.info("Freeing pointer " + p + " (peer = " + p.peer + ", validStart = " + p.validStart + ", validEnd = " + p.validEnd + ", validBytes = " + p.getValidBytes() + ")\n(Creation trace = \n\t" + Utils.toString(p.creationTrace).replaceAll("\n", "\n\t") + "\n)", new RuntimeException().fillInStackTrace()); if (!BridJ.debugNeverFree) JNI.free(p.getPeer()); } } /** * Create a memory area large enough to hold arrayLength items of type elementClass. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateArray(Class<V> elementClass, long arrayLength) { return allocateArray((Type)elementClass, arrayLength); } /** * Create a memory area large enough to hold arrayLength items of type elementClass. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateArray(Type elementClass, long arrayLength) { if (arrayLength == 0) return null; PointerIO pio = PointerIO.getInstance(elementClass); if (pio == null) throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); return (Pointer<V>)allocateArray(pio, arrayLength); } /** * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param alignment boundary to which the returned pointer should be aligned * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateAlignedArray(Class<V> elementClass, long arrayLength, int alignment) { return allocateAlignedArray((Type)elementClass, arrayLength, alignment); } /** * Create a memory area large enough to hold arrayLength items of type elementClass, ensuring the pointer to the memory is aligned to the provided boundary. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param alignment boundary to which the returned pointer should be aligned * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateAlignedArray(Type elementClass, long arrayLength, int alignment) { PointerIO io = PointerIO.getInstance(elementClass); if (io == null) throw new UnsupportedOperationException("Cannot allocate memory for type " + (elementClass instanceof Class ? ((Class)elementClass).getName() : elementClass.toString())); return allocateAlignedBytes(io, getTargetSizeToAllocateArrayOrThrow(io) * arrayLength, alignment, null); } /** * Create a pointer to the memory location used by a direct NIO buffer.<br> * If the NIO buffer is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerToArray(Object)}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.<br> * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer. */ public static Pointer<?> pointerToBuffer(Buffer buffer) { if (buffer == null) return null; #foreach ($prim in $primitivesNoBool) if (buffer instanceof ${prim.BufferName}) return (Pointer)pointerTo${prim.CapName}s((${prim.BufferName})buffer); #end throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); } /** * When a pointer was created with {@link Pointer#pointerToBuffer(Buffer)} on a non-direct buffer, a native copy of the buffer data was made. * This method updates the original buffer with the native memory, and does nothing if the buffer is direct <b>and</b> points to the same memory location as this pointer.<br> * @throws IllegalArgumentException if buffer is direct and does not point to the exact same location as this Pointer instance */ public void updateBuffer(Buffer buffer) { if (buffer == null) throw new IllegalArgumentException("Cannot update a null Buffer !"); if (Utils.isDirect(buffer)) { long address = JNI.getDirectBufferAddress(buffer); if (address != getPeer()) { throw new IllegalArgumentException("Direct buffer does not point to the same location as this Pointer instance, updating it makes no sense !"); } } else { #foreach ($prim in $primitivesNoBool) #if ($prim.Name != "char") if (buffer instanceof ${prim.BufferName}) { ((${prim.BufferName})buffer).duplicate().put(get${prim.BufferName}()); return; } #end #end throw new UnsupportedOperationException("Unhandled buffer type : " + buffer.getClass().getName()); } } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive: $prim.Name -- #docAllocateCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}(${prim.Name} value) { Pointer<${prim.WrapperName}> mem = allocate(PointerIO.get${prim.CapName}Instance()); mem.set${prim.CapName}(value); return mem; } #docAllocateArrayCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.Name}... values) { if (values == null) return null; Pointer<${prim.WrapperName}> mem = allocateArray(PointerIO.get${prim.CapName}Instance(), values.length); mem.set${prim.CapName}sAtOffset(0, values, 0, values.length); return mem; } #docAllocateArray2DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> pointerTo${prim.CapName}s(${prim.Name}[][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length; Pointer<Pointer<${prim.WrapperName}>> mem = allocate${prim.CapName}s(dim1, dim2); for (int i1 = 0; i1 < dim1; i1++) mem.set${prim.CapName}sAtOffset(i1 * dim2 * ${primSize}, values[i1], 0, dim2); return mem; } #docAllocateArray3DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> pointerTo${prim.CapName}s(${prim.Name}[][][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length, dim3 = values[0][0].length; Pointer<Pointer<Pointer<${prim.WrapperName}>>> mem = allocate${prim.CapName}s(dim1, dim2, dim3); for (int i1 = 0; i1 < dim1; i1++) { int offset1 = i1 * dim2; for (int i2 = 0; i2 < dim2; i2++) { int offset2 = (offset1 + i2) * dim3; mem.set${prim.CapName}sAtOffset(offset2 * ${primSize}, values[i1][i2], 0, dim3); } } return mem; } #docAllocate($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}() { return allocate(PointerIO.get${prim.CapName}Instance()); } #docAllocateArray($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}s(long arrayLength) { return allocateArray(PointerIO.get${prim.CapName}Instance(), arrayLength); } #docAllocateArray2D($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> allocate${prim.CapName}s(long dim1, long dim2) { return allocateArray(PointerIO.getArrayInstance(PointerIO.get${prim.CapName}Instance(), new long[] { dim1, dim2 }, 0), dim1); } #docAllocateArray3D($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> allocate${prim.CapName}s(long dim1, long dim2, long dim3) { long[] dims = new long[] { dim1, dim2, dim3 }; return allocateArray( PointerIO.getArrayInstance( //PointerIO.get${prim.CapName}Instance(), PointerIO.getArrayInstance( PointerIO.get${prim.CapName}Instance(), dims, 1 ), dims, 0 ), dim1 ) ; } #end #foreach ($prim in $primitivesNoBool) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive (no bool): $prim.Name -- /** * Create a pointer to the memory location used by a direct NIO ${prim.BufferName}.<br> * If the NIO ${prim.BufferName} is not direct, then its backing Java array is copied to some native memory and will never be updated by changes to the native memory (calls {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])}), unless a call to {@link Pointer#updateBuffer(Buffer)} is made manually.<br> * The returned pointer (and its subsequent views returned by {@link Pointer#offset(long)} or {@link Pointer#next(long)}) can be used safely : it retains a reference to the original NIO buffer, so that this latter cannot be garbage collected before the pointer.</br> */ public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.BufferName} buffer) { if (buffer == null) return null; if (!buffer.isDirect()) { return pointerTo${prim.CapName}s(buffer.array()); //throw new UnsupportedOperationException("Cannot create pointers to indirect ${prim.BufferName} buffers"); } long address = JNI.getDirectBufferAddress(buffer); long size = JNI.getDirectBufferCapacity(buffer); // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! size *= ${primSize}; //System.out.println("Buffer capacity = " + size); if (address == 0 || size == 0) return null; PointerIO<${prim.WrapperName}> io = CommonPointerIOs.${prim.Name}IO; boolean ordered = buffer.order().equals(ByteOrder.nativeOrder()); return newPointer(io, address, ordered, address, address + size, null, NO_PARENT, null, buffer); } #end /** * Get the type of pointed elements. */ public Type getTargetType() { PointerIO<T> io = getIO(); return io == null ? null : io.getTargetType(); } /** * Read an untyped pointer value from the pointed memory location * @deprecated Avoid using untyped pointers, if possible. */ @Deprecated public Pointer<?> getPointer() { return getPointerAtOffset(0, (PointerIO)null); } /** * Read a pointer value from the pointed memory location shifted by a byte offset */ public Pointer<?> getPointerAtOffset(long byteOffset) { return getPointerAtOffset(byteOffset, (PointerIO)null); } #docGetIndex("pointer" "getPointerAtOffset(valueIndex * Pointer.SIZE)") public Pointer<?> getPointerAtIndex(long valueIndex) { return getPointerAtOffset(valueIndex * Pointer.SIZE); } /** * Read a pointer value from the pointed memory location.<br> * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(Class<U> c) { return getPointerAtOffset(0, (PointerIO<U>)PointerIO.getInstance(c)); } /** * Read a pointer value from the pointed memory location * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(PointerIO<U> pio) { return getPointerAtOffset(0, pio); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, Class<U> c) { return getPointerAtOffset(byteOffset, (Type)c); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param t type of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, Type t) { return getPointerAtOffset(byteOffset, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointerAtOffset(long byteOffset, PointerIO<U> pio) { long value = getSizeTAtOffset(byteOffset); if (value == 0) return null; return newPointer(pio, value, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, this, byteOffset, null, null); } /** * Write a pointer value to the pointed memory location */ public Pointer<T> setPointer(Pointer<?> value) { return setPointerAtOffset(0, value); } /** * Write a pointer value to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointerAtOffset(long byteOffset, Pointer<?> value) { setSizeTAtOffset(byteOffset, value == null ? 0 : value.getPeer()); return this; } #docSetIndex("pointer" "setPointerAtOffset(valueIndex * Pointer.SIZE, value)") public Pointer<T> setPointerAtIndex(long valueIndex, Pointer<?> value) { setPointerAtOffset(valueIndex * Pointer.SIZE, value); return this; } /** * Read an array of untyped pointer values from the pointed memory location shifted by a byte offset * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ public Pointer<?>[] getPointersAtOffset(long byteOffset, int arrayLength) { return getPointersAtOffset(byteOffset, arrayLength, (PointerIO)null); } /** * Read the array of remaining untyped pointer values from the pointed memory location * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ @Deprecated public Pointer<?>[] getPointers() { long rem = getValidElements("Cannot create array if remaining length is not known. Please use getPointers(int length) instead."); return getPointersAtOffset(0L, (int)rem); } /** * Read an array of untyped pointer values from the pointed memory location * @deprecated Use a typed version instead : {@link Pointer#getPointersAtOffset(long, int, Type)}, {@link Pointer#getPointersAtOffset(long, int, Class)} or {@link Pointer#getPointersAtOffset(long, int, PointerIO)} */ @Deprecated public Pointer<?>[] getPointers(int arrayLength) { return getPointersAtOffset(0, arrayLength); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t type of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, Type t) { return getPointersAtOffset(byteOffset, arrayLength, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t class of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, Class<U> t) { return getPointersAtOffset(byteOffset, arrayLength, (Type)t); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointersAtOffset(long byteOffset, int arrayLength, PointerIO pio) { Pointer<U>[] values = (Pointer<U>[])new Pointer[arrayLength]; int s = Platform.POINTER_SIZE; for (int i = 0; i < arrayLength; i++) values[i] = getPointerAtOffset(byteOffset + i * s, pio); return values; } /** * Write an array of pointer values to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointersAtOffset(long byteOffset, Pointer<?>[] values) { return setPointersAtOffset(byteOffset, values, 0, values.length); } /** * Write length pointer values from the given array (starting at the given value offset) to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointersAtOffset(long byteOffset, Pointer<?>[] values, int valuesOffset, int length) { if (values == null) throw new IllegalArgumentException("Null values"); int n = length, s = Platform.POINTER_SIZE; for (int i = 0; i < n; i++) setPointerAtOffset(byteOffset + i * s, values[valuesOffset + i]); return this; } /** * Write an array of pointer values to the pointed memory location */ public Pointer<T> setPointers(Pointer<?>[] values) { return setPointersAtOffset(0, values); } /** * Read an array of elements from the pointed memory location shifted by a byte offset.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArrayAtOffset(long byteOffset, int length) { return getIO("Cannot create sublist").getArray(this, byteOffset, length); } /** * Read an array of elements from the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArray(int length) { return getArrayAtOffset(0L, length); } /** * Read the array of remaining elements from the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method returns primitive arrays (e.g. {@code int[] }), unlike {@link Pointer#toArray } (which returns arrays of objects so primitives end up being boxed, e.g. {@code Integer[] }) * @return an array of values of the requested length. The array is an array of primitives if the pointer's target type is a primitive or a boxed primitive type */ public Object getArray() { return getArray((int)getValidElements()); } /** * Read an NIO {@link Buffer} of elements from the pointed memory location shifted by a byte offset.<br> * @return an NIO {@link Buffer} of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBufferAtOffset(long byteOffset, int length) { return (B)getIO("Cannot create Buffer").getBuffer(this, byteOffset, length); } /** * Read an NIO {@link Buffer} of elements from the pointed memory location.<br> * @return an NIO {@link Buffer} of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBuffer(int length) { return (B)getBufferAtOffset(0L, length); } /** * Read the NIO {@link Buffer} of remaining elements from the pointed memory location.<br> * @return an array of values of the requested length. * @throws UnsupportedOperationException if this pointer's target type is not a Java primitive type with a corresponding NIO {@link Buffer} class. */ public <B extends Buffer> B getBuffer() { return (B)getBuffer((int)getValidElements()); } /** * Write an array of elements to the pointed memory location shifted by a byte offset.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) */ public Pointer<T> setArrayAtOffset(long byteOffset, Object array) { getIO("Cannot create sublist").setArray(this, byteOffset, array); return this; } /** * Allocate enough memory for array.length values, copy the values of the array provided as argument into it and return a pointer to that memory.<br> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to {@link Pointer#release()}.<br> * The pointer won't be garbage-collected until all its views are garbage-collected themselves ({@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) * @param array primitive array containing the initial values for the created memory area * @return pointer to a new memory location that initially contains the consecutive values provided in argument */ public static <T> Pointer<T> pointerToArray(Object array) { if (array == null) return null; PointerIO<T> io = PointerIO.getArrayIO(array); if (io == null) throwBecauseUntyped("Cannot create pointer to array"); Pointer<T> ptr = allocateArray(io, java.lang.reflect.Array.getLength(array)); io.setArray(ptr, 0, array); return ptr; } /** * Write an array of elements to the pointed memory location.<br> * For pointers to primitive types (e.g. {@code Pointer<Integer> }), this method accepts primitive arrays (e.g. {@code int[] }) instead of arrays of boxed primitives (e.g. {@code Integer[] }) */ public Pointer<T> setArray(Object array) { return setArrayAtOffset(0L, array); } #foreach ($sizePrim in ["SizeT", "CLong"]) //-- size primitive: $sizePrim -- #docAllocateCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}(long value) { Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); p.set${sizePrim}(value); return p; } #docAllocateCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}(${sizePrim} value) { Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); p.set${sizePrim}(value); return p; } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(long... values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(${sizePrim}... values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(int[] values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}sAtOffset(0, values); } #docAllocateArray($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}s(long arrayLength) { return allocateArray(PointerIO.get${sizePrim}Instance(), arrayLength); } #docAllocate($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}() { return allocate(PointerIO.get${sizePrim}Instance()); } #docGet($sizePrim $sizePrim) public long get${sizePrim}() { return ${sizePrim}.SIZE == 8 ? getLong() : getInt(); } #docGetOffset($sizePrim $sizePrim "Pointer#get${sizePrim}()") public long get${sizePrim}AtOffset(long byteOffset) { return ${sizePrim}.SIZE == 8 ? getLongAtOffset(byteOffset) : getIntAtOffset(byteOffset); } #docGetIndex($sizePrim "get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE") public long get${sizePrim}AtIndex(long valueIndex) { return get${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE); } #docGetRemainingArray($sizePrim $sizePrim) public long[] get${sizePrim}s() { long rem = getValidElements("Cannot create array if remaining length is not known. Please use get${sizePrim}s(int length) instead."); if (${sizePrim}.SIZE == 8) return getLongs((int)rem); return get${sizePrim}s((int)rem); } #docGetArray($sizePrim $sizePrim) public long[] get${sizePrim}s(int arrayLength) { if (${sizePrim}.SIZE == 8) return getLongs(arrayLength); return get${sizePrim}sAtOffset(0, arrayLength); } #docGetArrayOffset($sizePrim $sizePrim "Pointer#get${sizePrim}s(int)") public long[] get${sizePrim}sAtOffset(long byteOffset, int arrayLength) { if (${sizePrim}.SIZE == 8) return getLongsAtOffset(byteOffset, arrayLength); int[] values = getIntsAtOffset(byteOffset, arrayLength); long[] ret = new long[arrayLength]; for (int i = 0; i < arrayLength; i++) { ret[i] = //0xffffffffL & values[i]; } return ret; } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(long value) { if (${sizePrim}.SIZE == 8) setLong(value); else { setInt(SizeT.safeIntCast(value)); } return this; } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(${sizePrim} value) { return set${sizePrim}(value.longValue()); } #docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(long)") public Pointer<T> set${sizePrim}AtOffset(long byteOffset, long value) { if (${sizePrim}.SIZE == 8) setLongAtOffset(byteOffset, value); else { setIntAtOffset(byteOffset, SizeT.safeIntCast(value)); } return this; } #docSetIndex($sizePrim "set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value)") public Pointer<T> set${sizePrim}AtIndex(long valueIndex, long value) { return set${sizePrim}AtOffset(valueIndex * ${sizePrim}.SIZE, value); } #docSetOffset($sizePrim $sizePrim "Pointer#set${sizePrim}(${sizePrim})") public Pointer<T> set${sizePrim}AtOffset(long byteOffset, ${sizePrim} value) { return set${sizePrim}AtOffset(byteOffset, value.longValue()); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long[] values) { if (${sizePrim}.SIZE == 8) return setLongs(values); return set${sizePrim}sAtOffset(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(int[] values) { if (${sizePrim}.SIZE == 4) return setInts(values); return set${sizePrim}sAtOffset(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(${sizePrim}[] values) { return set${sizePrim}sAtOffset(0, values); } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values) { return set${sizePrim}sAtOffset(byteOffset, values, 0, values.length); } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(long[])") public abstract Pointer<T> set${sizePrim}sAtOffset(long byteOffset, long[] values, int valuesOffset, int length); #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(${sizePrim}...)") public Pointer<T> set${sizePrim}sAtOffset(long byteOffset, ${sizePrim}... values) { if (values == null) throw new IllegalArgumentException("Null values"); int n = values.length, s = ${sizePrim}.SIZE; for (int i = 0; i < n; i++) set${sizePrim}AtOffset(byteOffset + i * s, values[i].longValue()); return this; } #docSetArrayOffset($sizePrim $sizePrim "Pointer#set${sizePrim}s(int[])") public abstract Pointer<T> set${sizePrim}sAtOffset(long byteOffset, int[] values); #end void setSignedIntegralAtOffset(long byteOffset, long value, long sizeOfIntegral) { switch ((int)sizeOfIntegral) { case 1: if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE) throw new RuntimeException("Value out of byte bounds : " + value); setByteAtOffset(byteOffset, (byte)value); break; case 2: if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) throw new RuntimeException("Value out of short bounds : " + value); setShortAtOffset(byteOffset, (short)value); break; case 4: if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) throw new RuntimeException("Value out of int bounds : " + value); setIntAtOffset(byteOffset, (int)value); break; case 8: setLongAtOffset(byteOffset, value); break; default: throw new IllegalArgumentException("Cannot write integral type of size " + sizeOfIntegral + " (value = " + value + ")"); } } long getSignedIntegralAtOffset(long byteOffset, long sizeOfIntegral) { switch ((int)sizeOfIntegral) { case 1: return getByteAtOffset(byteOffset); case 2: return getShortAtOffset(byteOffset); case 4: return getIntAtOffset(byteOffset); case 8: return getLongAtOffset(byteOffset); default: throw new IllegalArgumentException("Cannot read integral type of size " + sizeOfIntegral); } } #docAllocateCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointer(Pointer<T> value) { Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocate(PointerIO.getPointerInstance()); p.setPointerAtOffset(0, value); return p; } #docAllocateArrayCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointers(Pointer<T>... values) { if (values == null) return null; int n = values.length, s = Pointer.SIZE; PointerIO<Pointer> pio = PointerIO.getPointerInstance(); // TODO get actual pointer instances PointerIO !!! Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocateArray(pio, n); for (int i = 0; i < n; i++) { p.setPointerAtOffset(i * s, values[i]); } return p; } /** * Copy all values from an NIO buffer to the pointed memory location shifted by a byte offset */ public Pointer<T> setValuesAtOffset(long byteOffset, Buffer values) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy length values from an NIO buffer (beginning at element at valuesOffset index) to the pointed memory location shifted by a byte offset */ public Pointer<T> setValuesAtOffset(long byteOffset, Buffer values, int valuesOffset, int length) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}sAtOffset(byteOffset, (${prim.BufferName})values, valuesOffset, length); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy values from an NIO buffer to the pointed memory location */ public Pointer<T> setValues(Buffer values) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}s((${prim.BufferName})values); return this; } #end throw new UnsupportedOperationException("Unhandled buffer type : " + values.getClass().getName()); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function.<br> * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead. */ @Deprecated public Pointer<T> copyBytesAtOffsetTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") JNI.memcpy(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); return this; } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function.<br> * If the destination and source memory locations are likely to overlap, {@link Pointer#moveBytesAtOffsetTo(long, Pointer, long, long)} must be used instead.<br> * See {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)} for more options. */ @Deprecated public Pointer<T> copyBytesTo(Pointer<?> destination, long byteCount) { return copyBytesAtOffsetTo(0, destination, 0, byteCount); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ @Deprecated public Pointer<T> moveBytesAtOffsetTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { #declareCheckedPeerAtOffset("byteOffset" "byteCount") JNI.memmove(destination.getCheckedPeer(byteOffsetInDestination, byteCount), checkedPeer, byteCount); return this; } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer, using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ public Pointer<T> moveBytesTo(Pointer<?> destination, long byteCount) { return moveBytesAtOffsetTo(0, destination, 0, byteCount); } /** * Copy all valid bytes from the memory location indicated by this pointer to that of another pointer, using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memmove/">memmove</a> C function.<br> * Works even if the destination and source memory locations are overlapping. */ public Pointer<T> moveBytesTo(Pointer<?> destination) { return moveBytesTo(destination, getValidBytes("Cannot move an unbounded memory location. Please use validBytes(long).")); } final long getValidBytes(String error) { long rem = getValidBytes(); if (rem < 0) throw new IndexOutOfBoundsException(error); return rem; } final long getValidElements(String error) { long rem = getValidElements(); if (rem < 0) throw new IndexOutOfBoundsException(error); return rem; } final PointerIO<T> getIO(String error) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped(error); return io; } /** * Copy remaining bytes from this pointer to a destination using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function (see {@link Pointer#copyBytesTo(Pointer, long)}, {@link Pointer#getValidBytes()}) */ public Pointer<T> copyTo(Pointer<?> destination) { return copyTo(destination, getValidElements()); } /** * Copy remaining elements from this pointer to a destination using the @see <a href="http://www.cplusplus.com/reference/clibrary/cstring/memcpy/">memcpy</a> C function (see {@link Pointer#copyBytesAtOffsetTo(long, Pointer, long, long)}, {@link Pointer#getValidBytes}) */ public Pointer<T> copyTo(Pointer<?> destination, long elementCount) { PointerIO<T> io = getIO("Cannot copy untyped pointer without byte count information. Please use copyBytesAtOffsetTo(offset, destination, destinationOffset, byteCount) instead"); return copyBytesAtOffsetTo(0, destination, 0, elementCount * io.getTargetSize()); } /** * Find the first appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (behaviour equivalent to <a href="http://linux.die.net/man/3/memmem">memmem</a>, which is used underneath on platforms where it is available) */ public Pointer<T> find(Pointer<?> needle) { if (needle == null) return null; long firstOccurrence = JNI.memmem( getPeer(), getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), needle.getPeer(), needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") ); return pointerToAddress(firstOccurrence, io); } /** * Find the last appearance of the sequence of valid bytes pointed by needle in the memory area pointed to by this bounded pointer (also see {@link Pointer#find(Pointer)}). */ public Pointer<T> findLast(Pointer<?> needle) { if (needle == null) return null; long lastOccurrence = JNI.memmem_last( getPeer(), getValidBytes("Cannot search an unbounded memory area. Please set bounds with validBytes(long)."), needle.getPeer(), needle.getValidBytes("Cannot search for an unbounded content. Please set bounds with validBytes(long).") ); return pointerToAddress(lastOccurrence, io); } #foreach ($prim in $primitives) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive: $prim.Name -- #docSet(${prim.Name} ${prim.WrapperName}) public abstract Pointer<T> set${prim.CapName}(${prim.Name} value); #docSetOffset(${prim.Name} ${prim.WrapperName} "Pointer#set${prim.CapName}(${prim.Name})") public abstract Pointer<T> set${prim.CapName}AtOffset(long byteOffset, ${prim.Name} value); #docSetIndex(${prim.Name} "set${prim.CapName}AtOffset(valueIndex * $primSize, value)") public Pointer<T> set${prim.CapName}AtIndex(long valueIndex, ${prim.Name} value) { return set${prim.CapName}AtOffset(valueIndex * $primSize, value); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.Name}[] values) { return set${prim.CapName}sAtOffset(0, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values) { return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given array offset and for the given length from the provided array. */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] values, int valuesOffset, int length) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return setIntsAtOffset(byteOffset, wcharsToInts(values, valuesOffset, length)); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) { JNI.set_${prim.Name}_array_disordered(checkedPeer, values, valuesOffset, length); return this; } #end JNI.set_${prim.Name}_array(checkedPeer, values, valuesOffset, length); return this; } #docGet(${prim.Name} ${prim.WrapperName}) public abstract ${prim.Name} get${prim.CapName}(); #docGetOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}()") public abstract ${prim.Name} get${prim.CapName}AtOffset(long byteOffset); #docGetIndex(${prim.Name} "get${prim.CapName}AtOffset(valueIndex * $primSize)") public ${prim.Name} get${prim.CapName}AtIndex(long valueIndex) { return get${prim.CapName}AtOffset(valueIndex * $primSize); } #docGetArray(${prim.Name} ${prim.WrapperName}) public ${prim.Name}[] get${prim.CapName}s(int length) { return get${prim.CapName}sAtOffset(0, length); } #docGetRemainingArray(${prim.Name} ${prim.WrapperName}) public ${prim.Name}[] get${prim.CapName}s() { long validBytes = getValidBytes("Cannot create array if remaining length is not known. Please use get${prim.CapName}s(int length) instead."); return get${prim.CapName}s((int)(validBytes / ${primSize})); } #docGetArrayOffset(${prim.Name} ${prim.WrapperName} "Pointer#get${prim.CapName}s(int)") public ${prim.Name}[] get${prim.CapName}sAtOffset(long byteOffset, int length) { #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) return intsToWChars(getIntsAtOffset(byteOffset, length)); #end #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) return JNI.get_${prim.Name}_array_disordered(checkedPeer, length); #end return JNI.get_${prim.Name}_array(checkedPeer, length); } #end #foreach ($prim in $primitivesNoBool) #if ($prim.Name == "char") #set ($primSize = "Platform.WCHAR_T_SIZE") #else #set ($primSize = $prim.Size) #end //-- primitive (no bool): $prim.Name -- #if ($prim.Name != "char") /** * Read ${prim.Name} values into the specified destination array from the pointed memory location */ public void get${prim.CapName}s(${prim.Name}[] dest) { get${prim.BufferName}().get(dest); } /** * Read ${prim.Name} values into the specified destination buffer from the pointed memory location */ public void get${prim.CapName}s(${prim.BufferName} dest) { dest.duplicate().put(get${prim.BufferName}()); } /** * Read length ${prim.Name} values into the specified destination array from the pointed memory location shifted by a byte offset, storing values after the provided destination offset. */ public void get${prim.CapName}sAtOffset(long byteOffset, ${prim.Name}[] dest, int destOffset, int length) { get${prim.BufferName}AtOffset(byteOffset, length).get(dest, destOffset, length); } #end /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.BufferName} values) { return set${prim.CapName}sAtOffset(0, values, 0, values.capacity()); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values) { return set${prim.CapName}sAtOffset(byteOffset, values, 0, values.capacity()); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given buffer offset and for the given length from the provided buffer. */ public Pointer<T> set${prim.CapName}sAtOffset(long byteOffset, ${prim.BufferName} values, long valuesOffset, long length) { if (values == null) throw new IllegalArgumentException("Null values"); #if ($prim.Name == "char") if (Platform.WCHAR_T_SIZE == 4) { for (int i = 0; i < length; i++) setCharAtOffset(byteOffset + i, values.get((int)(valuesOffset + i))); return this; } #end if (values.isDirect()) { long len = length * ${primSize}, off = valuesOffset * ${primSize}; long cap = JNI.getDirectBufferCapacity(values); // HACK (TODO?) the JNI spec says size is in bytes, but in practice on mac os x it's in elements !!! cap *= ${primSize}; if (cap < off + len) throw new IndexOutOfBoundsException("The provided buffer has a capacity (" + cap + " bytes) smaller than the requested write operation (" + len + " bytes starting at byte offset " + off + ")"); #declareCheckedPeerAtOffset("byteOffset" "${primSize} * length") JNI.memcpy(checkedPeer, JNI.getDirectBufferAddress(values) + off, len); } #if ($prim.Name != "char") else if (values.isReadOnly()) { get${prim.BufferName}AtOffset(byteOffset, length).put(values.duplicate()); } #end else { set${prim.CapName}sAtOffset(byteOffset, values.array(), (int)(values.arrayOffset() + valuesOffset), (int)length); } return this; } #if ($prim.Name != "char") /** * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location */ public ${prim.BufferName} get${prim.BufferName}(long length) { return get${prim.BufferName}AtOffset(0, length); } /** * Get a direct buffer of ${prim.Name} values that points to this pointer's target memory locations */ public ${prim.BufferName} get${prim.BufferName}() { long validBytes = getValidBytes("Cannot create buffer if remaining length is not known. Please use get${prim.BufferName}(long length) instead."); return get${prim.BufferName}AtOffset(0, validBytes / ${primSize}); } /** * Get a direct buffer of ${prim.Name} values of the specified length that points to this pointer's target memory location shifted by a byte offset */ public ${prim.BufferName} get${prim.BufferName}AtOffset(long byteOffset, long length) { long blen = ${primSize} * length; #declareCheckedPeerAtOffset("byteOffset" "blen") ByteBuffer buffer = JNI.newDirectByteBuffer(checkedPeer, blen); buffer.order(order()); // mutates buffer order #if ($prim.Name == "byte") return buffer; #else return buffer.as${prim.BufferName}(); #end } #end #end /** * Type of a native character string.<br> * In the native world, there are several ways to represent a string.<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} */ public enum StringType { /** * C strings (a.k.a "NULL-terminated strings") have no size limit and are the most used strings in the C world. * They are stored with the bytes of the string (using either a single-byte encoding such as ASCII, ISO-8859 or windows-1252 or a C-string compatible multi-byte encoding, such as UTF-8), followed with a zero byte that indicates the end of the string.<br> * Corresponding C types : {@code char* }, {@code const char* }, {@code LPCSTR }<br> * Corresponding Pascal type : {@code PChar }<br> * See {@link Pointer#pointerToCString(String)}, {@link Pointer#getCString()} and {@link Pointer#setCString(String)} */ C(false, true), /** * Wide C strings are stored as C strings (see {@link StringType#C}) except they are composed of shorts instead of bytes (and are ended by one zero short value = two zero byte values). * This allows the use of two-bytes encodings, which is why this kind of strings is often found in modern Unicode-aware system APIs.<br> * Corresponding C types : {@code wchar_t* }, {@code const wchar_t* }, {@code LPCWSTR }<br> * See {@link Pointer#pointerToWideCString(String)}, {@link Pointer#getWideCString()} and {@link Pointer#setWideCString(String)} */ WideC(true, true), /** * Pascal strings can be up to 255 characters long.<br> * They are stored with a first byte that indicates the length of the string, followed by the ascii or extended ascii chars of the string (no support for multibyte encoding).<br> * They are often used in very old Mac OS programs and / or Pascal programs.<br> * Usual corresponding C types : {@code unsigned char* } and {@code const unsigned char* }<br> * Corresponding Pascal type : {@code ShortString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalShort(false, true), /** * Wide Pascal strings are ref-counted unicode strings that look like WideC strings but are prepended with a ref count and length (both 32 bits ints).<br> * They are the current default in Delphi (2010).<br> * Corresponding Pascal type : {@code WideString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalWide(true, true), /** * Pascal ANSI strings are ref-counted single-byte strings that look like C strings but are prepended with a ref count and length (both 32 bits ints).<br> * Corresponding Pascal type : {@code AnsiString } (see @see <a href="http://www.codexterity.com/delphistrings.htm">http://www.codexterity.com/delphistrings.htm</a>)<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ PascalAnsi(false, true), /** * Microsoft's BSTR strings, used in COM, OLE, MS.NET Interop and MS.NET Automation functions.<br> * See @see <a href="http://msdn.microsoft.com/en-us/library/ms221069.aspx">http://msdn.microsoft.com/en-us/library/ms221069.aspx</a> for more details.<br> * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ BSTR(true, true), /** * STL strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ support reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ STL(false, false), /** * STL wide strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ supports reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType, Charset)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ WideSTL(true, false); //MFCCString, //CComBSTR, //_bstr_t final boolean isWide, canCreate; StringType(boolean isWide, boolean canCreate) { this.isWide = isWide; this.canCreate = canCreate; } } private static void notAString(StringType type, String reason) { throw new RuntimeException("There is no " + type + " String here ! (" + reason + ")"); } protected void checkIntRefCount(StringType type, long byteOffset) { int refCount = getIntAtOffset(byteOffset); if (refCount <= 0) notAString(type, "invalid refcount: " + refCount); } /** * Read a native string from the pointed memory location using the default charset.<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getString(StringType type) { return getStringAtOffset(0, type, null); } /** * Read a native string from the pointed memory location, using the provided charset or the system's default if not provided. * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options. * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used * @return string read from native memory */ public String getString(StringType type, Charset charset) { return getStringAtOffset(0, type, charset); } String getSTLStringAtOffset(long byteOffset, StringType type, Charset charset) { // Assume the following layout : // - fixed buff of 16 chars // - ptr to dynamic array if the string is bigger // - size of the string (size_t) // - max allowed size of the string without the need for reallocation boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; long length = getSizeTAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = this; } else { pOff = 0; p = getPointerAtOffset(byteOffset + fixedBuffSize + Pointer.SIZE); } int endChar = wide ? p.getCharAtOffset(pOff + length * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + length); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + length); return p.getStringAtOffset(pOff, wide ? StringType.WideC : StringType.C, charset); } static <U> Pointer<U> setSTLString(Pointer<U> pointer, long byteOffset, String s, StringType type, Charset charset) { boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * Platform.WCHAR_T_SIZE : fixedBuffLength; long lengthOffset = byteOffset + fixedBuffSize + Pointer.SIZE; long capacityOffset = lengthOffset + Pointer.SIZE; long length = s.length(); if (pointer == null)// { && length > fixedBuffLength - 1) throw new UnsupportedOperationException("Cannot create STL strings (yet)"); long currentLength = pointer.getSizeTAtOffset(lengthOffset); long currentCapacity = pointer.getSizeTAtOffset(capacityOffset); if (currentLength < 0 || currentCapacity < 0 || currentLength > currentCapacity) notAString(type, "STL string format not recognized : currentLength = " + currentLength + ", currentCapacity = " + currentCapacity); if (length > currentCapacity) throw new RuntimeException("The target STL string is not large enough to write a string of length " + length + " (current capacity = " + currentCapacity + ")"); pointer.setSizeTAtOffset(lengthOffset, length); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = pointer; } else { pOff = 0; p = pointer.getPointerAtOffset(byteOffset + fixedBuffSize + SizeT.SIZE); } int endChar = wide ? p.getCharAtOffset(pOff + currentLength * Platform.WCHAR_T_SIZE) : p.getByteAtOffset(pOff + currentLength); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + currentLength); p.setStringAtOffset(pOff, s, wide ? StringType.WideC : StringType.C, charset); return pointer; } /** * Read a native string from the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param charset Character set used to convert bytes to String characters. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getStringAtOffset(long byteOffset, StringType type, Charset charset) { try { long len; switch (type) { case PascalShort: len = getByteAtOffset(byteOffset) & 0xff; return new String(getBytesAtOffset(byteOffset + 1, safeIntCast(len)), charset(charset)); case PascalWide: checkIntRefCount(type, byteOffset - 8); case BSTR: len = getIntAtOffset(byteOffset - 4); if (len < 0 || ((len & 1) == 1)) notAString(type, "invalid byte length: " + len); //len = wcslen(byteOffset); if (getCharAtOffset(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getCharsAtOffset(byteOffset, safeIntCast(len / Platform.WCHAR_T_SIZE))); case PascalAnsi: checkIntRefCount(type, byteOffset - 8); len = getIntAtOffset(byteOffset - 4); if (len < 0) notAString(type, "invalid byte length: " + len); if (getByteAtOffset(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); case C: len = strlen(byteOffset); return new String(getBytesAtOffset(byteOffset, safeIntCast(len)), charset(charset)); case WideC: len = wcslen(byteOffset); return new String(getCharsAtOffset(byteOffset, safeIntCast(len))); case STL: case WideSTL: return getSTLStringAtOffset(byteOffset, type, charset); default: throw new RuntimeException("Unhandled string type : " + type); } } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Write a native string to the pointed memory location using the default charset.<br> * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options. * @param s string to write * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setString(String s, StringType type) { return setString(this, 0, s, type, null); } /** * Write a native string to the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param s string to write * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setStringAtOffset(long byteOffset, String s, StringType type, Charset charset) { return setString(this, byteOffset, s, type, charset); } private static String charset(Charset charset) { return (charset == null ? Charset.defaultCharset() : charset).name(); } static <U> Pointer<U> setString(Pointer<U> pointer, long byteOffset, String s, StringType type, Charset charset) { try { if (s == null) return null; byte[] bytes; char[] chars; int bytesCount, headerBytes; int headerShift; switch (type) { case PascalShort: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); if (bytesCount > 255) throw new IllegalArgumentException("Pascal strings cannot be more than 255 chars long (tried to write string of byte length " + bytesCount + ")"); pointer.setByteAtOffset(byteOffset, (byte)bytesCount); pointer.setBytesAtOffset(byteOffset + 1, bytes, 0, bytesCount); break; case C: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); pointer.setBytesAtOffset(byteOffset, bytes, 0, bytesCount); pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); break; case WideC: chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) pointer = (Pointer<U>)allocateChars(bytesCount + 2); pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); break; case PascalWide: headerBytes = 8; chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 8, 1); // refcount pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case PascalAnsi: headerBytes = 8; bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) { pointer = (Pointer<U>)allocateBytes(headerBytes + bytesCount + 1); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 8, 1); // refcount pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header pointer.setBytesAtOffset(byteOffset, bytes); pointer.setByteAtOffset(byteOffset + bytesCount, (byte)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case BSTR: headerBytes = 4; chars = s.toCharArray(); bytesCount = chars.length * Platform.WCHAR_T_SIZE; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setIntAtOffset(byteOffset - 4, bytesCount); // length header IN BYTES pointer.setCharsAtOffset(byteOffset, chars); pointer.setCharAtOffset(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case STL: case WideSTL: return setSTLString(pointer, byteOffset, s, type, charset); default: throw new RuntimeException("Unhandled string type : " + type); } return (Pointer<U>)pointer; } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Allocate memory and write a string to it, using the system's default charset to convert the string (See {@link StringType} for details on the supported types).<br> * See {@link Pointer#setString(String, StringType)}, {@link Pointer#getString(StringType)}. * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to create. */ public static Pointer<?> pointerToString(String string, StringType type, Charset charset) { return setString(null, 0, string, type, charset); } #macro (defPointerToString $string $eltWrapper) /** * Allocate memory and write a ${string} string to it, using the system's default charset to convert the string. (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}String(String)}, {@link Pointer#get${string}String()}.<br> * See {@link Pointer#pointerToString(String, StringType, Charset)} for choice of the String type or Charset. */ public static Pointer<$eltWrapper> pointerTo${string}String(String string) { return setString(null, 0, string, StringType.${string}, null); } /** * Allocate an array of pointers to strings. */ public static Pointer<Pointer<$eltWrapper>> pointerTo${string}Strings(final String... strings) { if (strings == null) return null; final int len = strings.length; final Pointer<$eltWrapper>[] pointers = (Pointer<$eltWrapper>[])new Pointer[len]; Pointer<Pointer<$eltWrapper>> mem = allocateArray((PointerIO<Pointer<$eltWrapper>>)(PointerIO)PointerIO.getPointerInstance(${eltWrapper}.class), len, new Releaser() { //@Override public void release(Pointer<?> p) { Pointer<Pointer<$eltWrapper>> mem = (Pointer<Pointer<$eltWrapper>>)p; for (int i = 0; i < len; i++) { Pointer<$eltWrapper> pp = pointers[i]; if (pp != null) pp.release(); } }}); for (int i = 0; i < len; i++) mem.set(i, pointers[i] = pointerTo${string}String(strings[i])); return mem; } #end #defPointerToString("C" "Byte") #defPointerToString("WideC" "Character") #foreach ($string in ["C", "WideC"]) //-- StringType: $string -- /** * Read a ${string} string using the default charset from the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#get${string}StringAtOffset(long)}, {@link Pointer#getString(StringType)} and {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options */ public String get${string}String() { return get${string}StringAtOffset(0); } /** * Read a ${string} string using the default charset from the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#getStringAtOffset(long, StringType, Charset)} for more options */ public String get${string}StringAtOffset(long byteOffset) { return getStringAtOffset(byteOffset, StringType.${string}, null); } /** * Write a ${string} string using the default charset to the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}StringAtOffset(long, String)} and {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options */ public Pointer<T> set${string}String(String s) { return set${string}StringAtOffset(0, s); } /** * Write a ${string} string using the default charset to the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#setStringAtOffset(long, String, StringType, Charset)} for more options */ public Pointer<T> set${string}StringAtOffset(long byteOffset, String s) { return setStringAtOffset(byteOffset, s, StringType.${string}, null); } #end /** * Get the length of the C string at the pointed memory location shifted by a byte offset (see {@link StringType#C}). */ protected long strlen(long byteOffset) { #declareCheckedPeerAtOffset("byteOffset" "1") return JNI.strlen(checkedPeer); } /** * Get the length of the wide C string at the pointed memory location shifted by a byte offset (see {@link StringType#WideC}). */ protected long wcslen(long byteOffset) { #declareCheckedPeerAtOffset("byteOffset" "Platform.WCHAR_T_SIZE") return JNI.wcslen(checkedPeer); } /** * Write zero bytes to all of the valid bytes pointed by this pointer */ public void clearValidBytes() { long bytes = getValidBytes(); if (bytes < 0) throw new UnsupportedOperationException("Number of valid bytes is unknown. Please use clearBytes(long) or validBytes(long)."); clearBytes(bytes); } /** * Write zero bytes to the first length bytes pointed by this pointer */ public void clearBytes(long length) { clearBytesAtOffset(0, length, (byte)0); } /** * Write a byte {@code value} to each of the {@code length} bytes at the address pointed to by this pointer shifted by a {@code byteOffset} */ public void clearBytesAtOffset(long byteOffset, long length, byte value) { #declareCheckedPeerAtOffset("byteOffset" "length") JNI.memset(checkedPeer, value, length); } /** * Find the first occurrence of a value in the memory block of length searchLength bytes pointed by this pointer shifted by a byteOffset */ public Pointer<T> findByte(long byteOffset, byte value, long searchLength) { #declareCheckedPeerAtOffset("byteOffset" "searchLength") long found = JNI.memchr(checkedPeer, value, searchLength); return found == 0 ? null : offset(found - checkedPeer); } /** * Alias for {@link Pointer#get(long)} defined for more natural use from the Scala language. */ public final T apply(long index) { return get(index); } /** * Alias for {@link Pointer\#set(long, Object)} defined for more natural use from the Scala language. */ public final void update(long index, T element) { set(index, element); } /** * Create an array with all the values in the bounded memory area.<br> * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. * @throws IndexOutOfBoundsException if this pointer's bounds are unknown */ public T[] toArray() { getIO("Cannot create array"); return toArray((int)getValidElements("Length of pointed memory is unknown, cannot create array out of this pointer")); } T[] toArray(int length) { Class<?> c = Utils.getClass(getIO("Cannot create array").getTargetType()); if (c == null) throw new RuntimeException("Unable to get the target type's class (target type = " + io.getTargetType() + ")"); return (T[])toArray((Object[])Array.newInstance(c, length)); } /** * Create an array with all the values in the bounded memory area, reusing the provided array if its type is compatible and its size is big enough.<br> * Note that if you wish to get an array of primitives (if T is boolean, char or a numeric type), then you need to call {@link Pointer#getArray()}. * @throws IndexOutOfBoundsException if this pointer's bounds are unknown */ public <U> U[] toArray(U[] array) { int n = (int)getValidElements(); if (n < 0) throwBecauseUntyped("Cannot create array"); if (array.length != n) return (U[])toArray(); for (int i = 0; i < n; i++) array[i] = (U)get(i); return array; } /** * Types of pointer-based list implementations that can be created through {@link Pointer#asList()} or {@link Pointer#asList(ListType)}. */ public enum ListType { /** * Read-only list */ Unmodifiable, /** * List is modifiable and can shrink, but capacity cannot be increased (some operations will hence throw UnsupportedOperationException when the capacity is unsufficient for the requested operation) */ FixedCapacity, /** * List is modifiable and its underlying memory will be reallocated if it needs to grow beyond its current capacity. */ Dynamic } /** * Create a {@link ListType#FixedCapacity} native list that uses this pointer as storage (and has this pointer's pointed valid elements as initial content).<br> * Same as {@link Pointer#asList(ListType)}({@link ListType#FixedCapacity}). */ public NativeList<T> asList() { return asList(ListType.FixedCapacity); } /** * Create a native list that uses this pointer as <b>initial</b> storage (and has this pointer's pointed valid elements as initial content).<br> * If the list is {@link ListType#Dynamic} and if its capacity is grown at some point, this pointer will probably no longer point to the native memory storage of the list, so you need to get back the pointer with {@link NativeList#getPointer()} when you're done mutating the list. */ public NativeList<T> asList(ListType type) { return new DefaultNativeList(this, type); } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param io Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(PointerIO<E> io, long capacity) { NativeList<E> list = new DefaultNativeList(allocateArray(io, capacity), ListType.Dynamic); list.clear(); return list; } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param type Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(Class<E> type, long capacity) { return allocateList((Type)type, capacity); } /** * Create a {@link ListType#Dynamic} list with the provided initial capacity (see {@link ListType#Dynamic}). * @param type Type of the elements of the list * @param capacity Initial capacity of the list */ public static <E> NativeList<E> allocateList(Type type, long capacity) { return (NativeList)allocateList(PointerIO.getInstance(type), capacity); } private static char[] intsToWChars(int[] in) { int n = in.length; char[] out = new char[n]; for (int i = 0; i < n; i++) out[i] = (char)in[i]; return out; } private static int[] wcharsToInts(char[] in, int valuesOffset, int length) { int[] out = new int[length]; for (int i = 0; i < length; i++) out[i] = in[valuesOffset + i]; return out; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
c2df0aaba5cde0e465dd1606bd8fb56f5022d0a1
d73e0d5c800ef6fc2782cc16779602554fdd3d7a
/src/main/java/addressbook/Util.java
b4620747c9fa859f7b4c11da991a488805fa1f1d
[]
no_license
tosinoni/AddressBookSpring
c5e7dbc03832539d93ae521a5770db63cf38cbf2
0d84625a213740982fedb90ed87ad9f6b7c4c693
refs/heads/master
2021-05-02T11:25:47.365523
2018-02-08T17:48:07
2018-02-08T17:48:07
120,775,524
0
0
null
null
null
null
UTF-8
Java
false
false
492
java
package addressbook; import java.util.Collection; public class Util { public static <E> void addAllIfNotNull(Collection<E> list, Collection<? extends E> c) { if (c != null) { list.addAll(c); } } public static <E> void addIfNotNull(Collection<E> list, E c) { if (c != null) { list.add(c); } } public static<E> boolean isCollectionEmpty(Collection<E> list) { return list == null || list.isEmpty(); } }
[ "tosin.oni@carleton.ca" ]
tosin.oni@carleton.ca
7cafd904640b8e7db6a00c3ddb2b15f440750fcc
eb7ef0755288506490718792f6758e03d126e314
/KallSonysOms/KallSonysOms-bakend-clientService/src/main/java/org/datacontract/schemas/_2004/_07/productoentities/CategoriaEntity.java
b8f3dc2b55c4dd53ab63e60b20574273412e5572
[]
no_license
njmube/PICA
91815fd7a74abe13c5cb250efb3ea96aedeb1cd4
367df7186340748410019ae4194d325628462f9c
refs/heads/master
2020-12-20T23:46:48.443861
2017-05-31T13:06:02
2017-05-31T13:06:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,314
java
package org.datacontract.schemas._2004._07.productoentities; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para CategoriaEntity complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="CategoriaEntity"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Categoria" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="IdCategoria" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CategoriaEntity", propOrder = { "categoria", "idCategoria" }) public class CategoriaEntity { @XmlElement(name = "Categoria", nillable = true) protected String categoria; @XmlElement(name = "IdCategoria") protected Integer idCategoria; /** * Obtiene el valor de la propiedad categoria. * * @return * possible object is * {@link String } * */ public String getCategoria() { return categoria; } /** * Define el valor de la propiedad categoria. * * @param value * allowed object is * {@link String } * */ public void setCategoria(String value) { this.categoria = value; } /** * Obtiene el valor de la propiedad idCategoria. * * @return * possible object is * {@link Integer } * */ public Integer getIdCategoria() { return idCategoria; } /** * Define el valor de la propiedad idCategoria. * * @param value * allowed object is * {@link Integer } * */ public void setIdCategoria(Integer value) { this.idCategoria = value; } }
[ "j.albertopuentes@gmail.com" ]
j.albertopuentes@gmail.com
cb9f564020641afa150e14f8426a3145b8ba3e3f
d212614b72eeca746e8f8c3bbb2fcae8593ea9ea
/app/src/main/java/com/hapus/android/store/Product_details_activity.java
b3b4cad1e7ee0c7fbe520e0c9cbaa2dd08139707
[]
no_license
ksasanka11/Hapus
da17c5af5190d4e111db2f6152e4bb43580780f8
94a9534788b65a05b4a3c0e3f7706324eeae5d38
refs/heads/master
2022-11-04T07:30:53.127164
2019-05-15T08:02:32
2019-05-15T08:02:32
171,491,481
0
0
null
null
null
null
UTF-8
Java
false
false
5,865
java
package com.hapus.android.store; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.telephony.SmsManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.List; public class Product_details_activity extends AppCompatActivity { private ViewPager productImagesViewPager; private TabLayout viewpagerIndicator; private TextView productTitle; private TextView averageRatingMiniView; private TextView productPrice; private FloatingActionButton addToWishListbtn;//todo:wishlist activity private FirebaseFirestore mFirebaseFirestore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_product_details_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); productImagesViewPager = findViewById(R.id.product_images_viewpager); viewpagerIndicator = findViewById(R.id.viewpager_indicator); productTitle = findViewById(R.id.product_title); averageRatingMiniView = findViewById(R.id.tv_product_rating_miniview); productPrice = findViewById(R.id.product_price); mFirebaseFirestore = FirebaseFirestore.getInstance(); final List<String> productImages = new ArrayList<>(); Intent i = getIntent(); String productID = i.getStringExtra("productId"); Log.e("Products", productID); mFirebaseFirestore.collection("PRODUCTS").document(productID).get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ DocumentSnapshot documentSnapshot = task.getResult(); for(long x = 1; x <= (long)documentSnapshot.get("no_of_product_images"); x++){ productImages.add(documentSnapshot.get("product_image_"+x).toString()); } ProductImagesAdapter productImagesAdapter=new ProductImagesAdapter(productImages); productImagesViewPager.setAdapter(productImagesAdapter); productTitle.setText(documentSnapshot.get("product_title").toString()); averageRatingMiniView.setText(documentSnapshot.get("average_rating").toString()); productPrice.setText("Rs."+documentSnapshot.get("product_price").toString()+"/kg"); }else{ String error = task.getException().getMessage(); Toast.makeText(Product_details_activity.this, error, Toast.LENGTH_SHORT).show(); } } }); viewpagerIndicator.setupWithViewPager(productImagesViewPager,true); final Button sendMsg=findViewById(R.id.buy_now_btn); sendMsg.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ FirebaseFirestore.getInstance().collection("ADMIN_PHONE").document("nZHDmKKeN2ByVIeitiQR").get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if(task.isSuccessful()){ SmsManager smsManager = SmsManager.getDefault(); DocumentSnapshot documentSnapshot = task.getResult(); String phone_number = documentSnapshot.get("phone_number").toString(); smsManager.sendTextMessage(phone_number, null, "Hello", null, null); } } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.search_and_cart_icon, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { finish(); return true; } else if (id == R.id.main_search_icon) { //todo: search return true; } else if (id == R.id.main_cart_icon) { //todo: cart return true; } return super.onOptionsItemSelected(item); } }
[ "30541568+ksasanka11@users.noreply.github.com" ]
30541568+ksasanka11@users.noreply.github.com
f36da24543be4a4bc3dbeeb093f3f29b698e33d8
a418c919d65fa3b66becfe43d4f166d462f09bfe
/cachecloud-open-web/src/main/java/com/sohu/cache/entity/MachineInfo.java
50a24de61f446315871e2566a21f80d0d89a4a3f
[ "Apache-2.0" ]
permissive
luwenbin006/cachecloud
b977b3665893381ed87bc3956602040923b4c208
f69631196c6eeca350d08c27ceae0835bd4e8f21
refs/heads/master
2021-01-21T09:20:37.812445
2016-11-29T09:55:05
2016-11-29T09:55:05
56,665,982
1
0
null
2016-04-20T07:36:07
2016-04-20T07:36:07
null
UTF-8
Java
false
false
5,182
java
package com.sohu.cache.entity; import java.util.Date; import com.sohu.cache.util.ConstUtils; /** * 机器的属性信息 * * Created by lingguo on 14-6-27. */ public class MachineInfo { /** * 机器id */ private long id; /** * ssh用户名 */ private String sshUser= ConstUtils.USERNAME; /** * ssh密码 */ private String sshPasswd=ConstUtils.PASSWORD; /** * ip地址 */ private String ip; /** * 机房 */ private String room; /** * 内存,单位G */ private int mem; /** * cpu数量 */ private int cpu; /** * 是否虚机,0否,1是 */ private int virtual; /** * 宿主机ip */ private String realIp; /** * 上线时间 */ private Date serviceTime; /** * 故障次数 */ private int faultCount; /** * 修改时间 */ private Date modifyTime; /** * 是否启用报警,0否,1是 */ private int warn; /** * 是否可用,0否,1是 */ private int available; /** * 机器资源的类型,0表示我们提供的原生资源,其它整数对应外部应用提供的机器资源池 */ private int type; /** * groupId */ private int groupId; /** * 额外说明:(例如本机器有其他web或者其他服务) */ private String extraDesc; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSshUser() { return sshUser; } public void setSshUser(String sshUser) { this.sshUser = sshUser; } public String getSshPasswd() { return sshPasswd; } public void setSshPasswd(String sshPasswd) { this.sshPasswd = sshPasswd; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public int getMem() { return mem; } public void setMem(int mem) { this.mem = mem; } public int getCpu() { return cpu; } public void setCpu(int cpu) { this.cpu = cpu; } public int getVirtual() { return virtual; } public void setVirtual(int virtual) { this.virtual = virtual; } public String getRealIp() { return realIp; } public void setRealIp(String realIp) { this.realIp = realIp; } public Date getServiceTime() { return serviceTime; } public void setServiceTime(Date serviceTime) { this.serviceTime = serviceTime; } public int getFaultCount() { return faultCount; } public void setFaultCount(int faultCount) { this.faultCount = faultCount; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public int getWarn() { return warn; } public void setWarn(int warn) { this.warn = warn; } public int getAvailable() { return available; } public void setAvailable(int available) { this.available = available; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public String getExtraDesc() { return extraDesc; } public void setExtraDesc(String extraDesc) { this.extraDesc = extraDesc; } /** * 获取组描述 * @return */ public String getGroupDesc() { return MachineGroupEnum.getMachineGroupInfo(type); } @Override public String toString() { return "MachineInfo{" + "id=" + id + ", sshUser='" + sshUser + '\'' + ", sshPasswd='" + sshPasswd + '\'' + ", ip='" + ip + '\'' + ", room='" + room + '\'' + ", mem=" + mem + ", cpu=" + cpu + ", virtual=" + virtual + ", realIp='" + realIp + '\'' + ", serviceTime=" + serviceTime + ", faultCount=" + faultCount + ", modifyTime=" + modifyTime + ", warn=" + warn + ", available=" + available + ", type=" + type + ", groupId=" + groupId + ", extraDesc=" + extraDesc + '}'; } }
[ "carlosfu@163.com" ]
carlosfu@163.com
d928cc2b907a9fee83f1752caf8a58375abea553
fdcb69f1d67ea822e7cdf51a00b4381785e05ea9
/src/main/java/edu/web/ContentType.java
d5638c25dac00df5a3a6e972120ccfdb872ff849
[]
no_license
lanaflonPerso/ProgramingServlets
1add2cd0cda7e2ad06db2c4db963f21162211a19
dab4357680c6c21531a6bcbe96c02e41d049becc
refs/heads/master
2020-12-02T03:03:06.362668
2018-01-03T20:34:44
2018-01-03T20:34:44
230,866,127
0
1
null
2019-12-30T07:06:03
2019-12-30T07:06:02
null
UTF-8
Java
false
false
1,068
java
package edu.web; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by R.Karimov on 11/29/17. */ @WebServlet(name = "ContentType", urlPatterns = "/ContentType") public class ContentType extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); out.println("Rno\tName\tMath\tPhys\tComputer Sc\tTotal"); out.println("101\tSekhar\t90\t90\t90\t=SUM(B2:D2)"); out.println("102\tSrinivasan\t95\t95\t95\t=SUM(B2:D2)"); } }
[ "rkarimov.r@gmail.com" ]
rkarimov.r@gmail.com
0cef3ef04624595136a2d76f352f9a9f9faa8d3f
a1b8a83d2c7360284072548e5d0e3e16d79a6b58
/wyait-manage/src/main/java/com/wyait/manage/service/db1/ComboService.java
a9ea755fed23937b4c7f20bc592029c16c567978
[]
no_license
adolphs/system
443822789243c4590456e24dd5294430336f49cf
9a391d5249ac44b498b2e628dec5945a3acebf3c
refs/heads/main
2023-02-27T02:07:43.527298
2021-02-08T09:55:44
2021-02-08T09:55:44
305,930,810
0
0
null
null
null
null
UTF-8
Java
false
false
2,945
java
package com.wyait.manage.service.db1; import com.baomidou.mybatisplus.service.IService; import com.wyait.manage.entity.ComboDetailsVo; import com.wyait.manage.pojo.*; import com.wyait.manage.pojo.result.ResponseResult; import com.wyait.manage.utils.PageDataResult; import java.util.List; import java.util.Map; /** * @author h_baojian * @version 1.0 * @date 2020/7/3 21:00 */ public interface ComboService extends IService<Combo> { String setSituationTOW(Integer pid, Integer type, String situationDescribe, Integer situationId, Integer situationIdTOW); PageDataResult getComboList(Combo combo, Integer page, Integer limit); String setCombo(Combo combo); String delCombo(Integer comboId); ComboDetailsVo getComboDetailsVo(Integer id,Integer departmentId); String addDooo(Combo combo); String delComboDooo(ComboDooo comboDooo); String updateComboDooo(Combo combo); PageDataResult getComboSituationList(ComboSituation comboSituation, Integer page, Integer limit); String addComboSituation(Integer comboId, String situationDescribe, String detailsDescribe,Integer id); ComboSituation selectComboSituationById(Integer id); List<ComboSituation> selectPidByComboSituationId(Integer id); String addComboSituationV2(ComboSituation comboSituation); String delComboSituation(Integer id); List<ComboSituationDetails> selectSituationDetailsByComboSituationId(Integer id); String setComboSituationDetails(ComboSituationDetails comboSituationDetails); String delComboSituationDetails(Integer id); String setDataAndComboSituation(Integer dataId, Integer comboSituationId, Integer comboSituationDetailsId); List<ComboSituationDetails> getCmoboSituationDetails(Integer id); List<ComboSituation> findSituationByPid(Integer situationDetailsId); String delSituationByPidAndSituationId(Integer situationId, Integer pid); String putApprovalType(Integer comboId, Integer approvalType, String approvalText); List<Combo> findAllCombo(); List<ComboSituation> findAllComboSituation(Integer comboId); Map<String,Object> fetchMattersNums(); Combo getComboById(Integer id); ResponseResult APIComboList(String type); ResponseResult queryComboSituation(Integer comoId); ResponseResult queryComboSituationDetailsByPid(Integer comboSituationDetailsId); ResponseResult queryComboDataList(String comboSituationDetailsIds,Integer comboId) throws InterruptedException; ResponseResult getAllSituation(Integer comboId); /** * 获取套餐的流程图url * @param comboId 套餐id * @return */ ResponseResult getComboUrl(Integer comboId); /** * 根据套餐ID查询所涉及到的部门 * @param comboId * @return */ ResponseResult getDepartmentByComboId(Integer comboId); /** * 获取热门套餐 * @return */ ResponseResult getHotCombo(); }
[ "asa_don@163.com" ]
asa_don@163.com
b94cef6dba54eb88530f57e18c2e876b6819f0b7
9419f4ac1836eb7f08d0fc08c5c0d4e5b5860a67
/src/edu/npu/votingsystem/domain/Register.java
c632a5d4a889422ea3fc9d51da11fa2877af7f46
[]
no_license
Rohini341999/VotingSystem
80484137aec3fd6f7080838232936f84be854dff
413fe5b679fb1879482dfb70bdd8dcb2d41c0c73
refs/heads/main
2023-01-29T02:03:38.310446
2020-12-16T15:35:20
2020-12-16T15:35:20
322,014,748
0
1
null
null
null
null
UTF-8
Java
false
false
663
java
package edu.npu.votingsystem.domain; public class Register { private String fName,lName,username,password; public Register() { // TODO Auto-generated constructor stub } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getlName() { return lName; } public void setlName(String lName) { this.lName = lName; } public String getfName() { return fName; } public void setfName(String fName) { this.fName = fName; } }
[ "sonalkoli341999@gmail.com" ]
sonalkoli341999@gmail.com
3db4840c54e0e7eb64f983525dca6bf6aca72da9
15e4a6aff3a6af870e05ed4b9eb7a9d6abbaa215
/Tracker/src/Position.java
dd02424e9b7eeb540a8341e5a5c9c8c8f1859fba
[]
no_license
junechoi93/formicidae
b52c9762441e42e6f52f3a5110c6094471acb38e
2a7373d828a21a76f2d4c564a9605a74c2c5005a
refs/heads/master
2020-04-20T08:24:26.962847
2014-03-05T10:01:34
2014-03-05T10:01:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,619
java
import processing.core.PApplet; import processing.core.PVector; public class Position { PVector origin; PVector avgspeed; // Average speed in pixels/second float lastmovetime; // Last moved time in seconds static float averagingTime =1.0f; // Averaging time in seconds int channel; int id; int groupid; int groupsize; public Position(PVector origin, int channel, int id) { this.origin=origin; this.avgspeed=new PVector(0f,0f); this.lastmovetime= 0f; this.channel = channel; this.id = id; this.groupid = id; this.groupsize = 1; } public Position(int channel) { this.origin = new PVector(0f,0f); this.avgspeed=new PVector(0f,0f); this.lastmovetime = 0f; this.channel = channel; } int getcolor(PApplet parent) { final int colors[] = {0xffff0000, 0xff00ff00, 0xff0000ff, 0xffFFFF00, 0xffFF00FF, 0xff00ffff}; int col=colors[(id-1)%colors.length]; //PApplet.println("Color="+String.format("%x", col)); return col; } void move(PVector newpos, int groupid, int groupsize, float elapsed) { //PApplet.println("move("+newpos+","+elapsed+"), lastmovetime="+lastmovetime); if (lastmovetime!=0.0 && elapsed>lastmovetime) { PVector moved=newpos.get(); moved.sub(origin); moved.mult(1.0f/(elapsed-lastmovetime)); // Running average using exponential decay float k=(elapsed-lastmovetime)/averagingTime; if (k>1.0f) k=1.0f; avgspeed.mult(1-k); moved.mult(k); avgspeed.add(moved); //PApplet.println("\t\t\t\tk="+k+", Speed="+avgspeed); } origin=newpos; lastmovetime=elapsed; this.groupid=groupid; this.groupsize=groupsize; } }
[ "bst@tc.com" ]
bst@tc.com
3fae543be18ad4f65b6b5391ad3821be15eabd3e
3ed4c2da885a01a4d845088307ff6c241590b294
/Object Oriented/assignment-4-madubata-master/assignment-4-madubata-master/src/main/java/edu/neu/ccs/cs5004/Problem3/JournalPaper.java
b736b311aa181b5e93f1999a0e8e5699fcffd79a
[]
no_license
Moltenbrown/Computer-Science-Projects
033b410fb3b53180b559d82511972994ae247ff8
4d09c752004bdd6d04aa0a7f15132dc60d3ac9eb
refs/heads/master
2021-06-27T00:28:26.504303
2020-11-01T03:01:45
2020-11-01T03:01:45
164,078,244
0
0
null
2020-10-13T21:40:06
2019-01-04T08:11:42
Python
UTF-8
Java
false
false
3,170
java
package edu.neu.ccs.cs5004.Problem3; import java.util.Objects; /** * Represents a paper in a journal with all its details--the journal name, the * journal issue number, and the month as a three letter abbreviation, as strings. * * @author Goch */ public class JournalPaper extends AbstractPublication { private String journalName; private Integer issueNumber; private String month; /** * Creates a new journal paper from a title, an author, a journal name, a issue number, a month, * and a year. * @param title the paper title. * @param author the author wrote the paper. * @param journalName the name of the journal. * @param issueNumber the journal issue number. * @param month the month when the journal was published. * @param year the year when the journal was published. * @throws Exception occurs when the year entered does not contain 4 digits, or the month * entered is not a three letter abbreviation. */ public JournalPaper(String title, Person author, String journalName, Integer issueNumber, String month, Integer year) throws Exception{ super(title, author, year); this.journalName = journalName; this.issueNumber = issueNumber; this.month = month; if(month.length() < 3 || month.length() > 3){ throw new InvalidMonthException("The month must be in three letter abbreviated form."); } } /** * Returns the name of the journal. * @return the journal name. */ public String getJournalName() { return journalName; } /** * Returns the journal's issue number. * @return the journal issue number. */ public Integer getIssueNumber() { return issueNumber; } /** * Returns the month the journal was published. * @return the month the journal was published. */ public String getMonth() { return month; } /** * Evaluates whether the object being compared is the same as the journal paper. * @param o the object being compared to the journal paper. * @return true if the object is the same as the journal paper, and false otherwise. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof JournalPaper)) { return false; } if (!super.equals(o)) { return false; } JournalPaper that = (JournalPaper) o; return Objects.equals(journalName, that.journalName) && Objects.equals(issueNumber, that.issueNumber) && Objects.equals(month, that.month); } /** * Returns the integer hashcode representation of the journal paper. * @return the integer hashcode representation of the journal paper. */ @Override public int hashCode() { return Objects.hash(super.hashCode(), journalName, issueNumber, month); } /** * Return a string describing the journal paper, using the journal name, * the issue number, month, year, and title. * @return a string describing the conference paper. */ @Override public String toString() { return journalName + ", Issue No. " + issueNumber + ", " + month + " " + super.getYear() + ", " + super.getTitle(); } }
[ "madubata.u@husky.neu.edu" ]
madubata.u@husky.neu.edu
c49d6b3df749ea3e3a719030281342c04c44dbdf
d6090b00f33bbf5ef14d7cb2372bb3a0c04bd138
/src/com/weidi/bluetoothchat/widget/ChatImageView.java
e5cf74899ebcf9cfebd60bc9b5e38e9aa6873c9f
[]
no_license
weidi5858258/BluetoothChat
2de2fac837fdc1481853cc6238015140d6c925f8
f4183dcf7c2770fe27af4728a61cbfc5a840ac45
refs/heads/master
2021-05-10T18:40:27.015858
2018-01-20T04:15:46
2018-01-20T04:15:46
118,131,985
0
0
null
null
null
null
UTF-8
Java
false
false
5,924
java
package com.weidi.bluetoothchat.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.NinePatch; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.NinePatchDrawable; import android.util.AttributeSet; import android.widget.ImageView; import com.weidi.bluetoothchat.R; public class ChatImageView extends ImageView { private int mMaskResId; private Bitmap mBitmap; private Bitmap mMaskBmp; private NinePatchDrawable mMaskDrawable; private Bitmap mResult; private Paint mPaint; private Paint mMaskPaint; private Matrix mMatrix; public ChatImageView(Context context) { super(context); init(); } public ChatImageView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ChatImageView, 0, 0); if (a != null) { mMaskResId = a.getResourceId(R.styleable.ChatImageView_chat_image_mask, 0); a.recycle(); } init(); } private void init() { mMatrix = new Matrix(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); if (mMaskResId <= 0) { return; } mMaskBmp = BitmapFactory.decodeResource(getResources(),mMaskResId); if(mMaskBmp==null){ return; } byte[] ninePatchChunk = mMaskBmp.getNinePatchChunk(); if (ninePatchChunk != null && NinePatch.isNinePatchChunk(ninePatchChunk)) { mMaskDrawable = new NinePatchDrawable(getResources(), mMaskBmp, ninePatchChunk, new Rect(), null); } internalSetImage(); } private void internalSetImage() { if (mMaskResId <= 0) { return; } if (mBitmap == null) { return; } final int width = getWidth(); final int height = getHeight(); if (width <= 0 || height <= 0) { return; } boolean canReUseBitmap = mResult != null && mResult.getWidth() == width && mResult.getHeight() == height; if (!canReUseBitmap) { mResult = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(mResult); if (canReUseBitmap) { canvas.drawColor(Color.TRANSPARENT); } // CENTER_CROP Bitmap mMatrix.reset(); float scale; float dx = 0, dy = 0; int bmpWidth = mBitmap.getWidth(); int bmpHeight = mBitmap.getHeight(); if (bmpWidth * height > width * bmpHeight) { scale = (float) height / (float) bmpHeight; dx = (width - bmpWidth * scale) * 0.5f; } else { scale = (float) width / (float) bmpWidth; dy = (height - bmpHeight * scale) * 0.5f; } mMatrix.setScale(scale, scale); mMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f)); canvas.save(); canvas.concat(mMatrix); canvas.drawBitmap(mBitmap, 0, 0, mPaint); canvas.restore(); if (mMaskDrawable != null) { mMaskDrawable.getPaint().setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); mMaskDrawable.setBounds(0, 0, width, height); mMaskDrawable.draw(canvas); } else if (mMaskBmp != null) { if (mMaskPaint == null) { mMaskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mMaskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } canvas.drawBitmap(mMaskBmp, 0, 0, mMaskPaint); } super.setImageBitmap(mResult); } @Override public void setImageBitmap(Bitmap bm) { mBitmap = bm; if (mMaskResId > 0 && mBitmap != null) { internalSetImage(); } else { super.setImageBitmap(bm); } } @Override // public void setImageResource(@DrawableRes int resId) { public void setImageResource(int resId) { mBitmap = getBitmapFromDrawable(getResources().getDrawable(resId)); internalSetImage(); } @Override public void setImageDrawable(Drawable drawable) { Bitmap bmp = getBitmapFromDrawable(drawable); if (mBitmap == bmp) { super.setImageDrawable(drawable); } else { mBitmap = bmp; internalSetImage(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); internalSetImage(); } private Bitmap getBitmapFromDrawable(Drawable drawable) { if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } try { Bitmap bitmap; if (drawable instanceof ColorDrawable) { bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } catch (OutOfMemoryError e) { return null; } } }
[ "weidi5858258@sina.com" ]
weidi5858258@sina.com
a2909e6a11dd4ee11d9560ca9bd9358b6d58f8ab
3acf3be737b76584a818a73acfead5a23472ad46
/src/main/java/com/gcaraciolo/payroll/domain/ChangeEmployeeMailTransaction.java
cb992bc0e4b560d4f716c7a7f6d3108f7a1e6225
[]
no_license
gcaraciolo/payroll
3a702d924b24b949819dcdb94ac76e97d967745e
3c6c459623ea59001f554abf8a2606691f54a937
refs/heads/master
2020-09-07T02:58:46.432279
2019-11-12T00:59:25
2019-11-12T00:59:25
220,636,835
2
1
null
null
null
null
UTF-8
Java
false
false
310
java
package com.gcaraciolo.payroll.domain; public class ChangeEmployeeMailTransaction extends ChangeEmployeeMethodTransaction { public ChangeEmployeeMailTransaction(Integer empId) { super(empId); } @Override protected PaymentMethod getMethod() { return new MailMethod(); } }
[ "gcaraciolo@gmail.com" ]
gcaraciolo@gmail.com
959ea27df12ea412b297f6b1c9123d440f0d09a2
275bdfd603e2890ffeedd71a1778ff89f1385228
/gcp/src/main/java/com/example/oauth2/Setup.java
9ea09559e002453f0dc1ef4f253ed4f9d74ee9e6
[]
no_license
kariyappah/myprojects
fab87dec16d93f40fc66aeb09679cbdf0f6cfedd
d69fb769fefeb00a0e7fe1f831cc26607e0f5e74
refs/heads/master
2021-01-19T12:25:14.541044
2017-08-21T06:18:46
2017-08-21T06:18:46
100,784,801
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.example.oauth2; public class Setup { public static final String CLIENT_ID = "95344702868-m3qt0589t2m0oahscg21mgudkofjpsum.apps.googleusercontent.com"; public static final String CLIENT_SECRET = "5QX5SjLrYHRPNhzA1ZsKnn2v"; public static final String REDIRECT_URL = "https://mygcpproject-10081982.appspot.com/oauth2callback"; }
[ "manasu@manasu" ]
manasu@manasu
d1901ad85eecb430e9def69e62d7d8b1a4526173
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/JetBrains--intellij-community/9065a9cb83f6dc01ca89bfabfe44404e15438682/before/Dictionary.java
c46e7f90f312f5d732879967631036ec860b0f34
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
883
java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.spellchecker.dictionary; import org.jetbrains.annotations.NotNull; import java.util.Set; public interface Dictionary { Set<String> getWords(); void acceptWord(@NotNull String word); void replaceAllWords(Set<String> newWords); String getName(); }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
3c613ed85c0ef3788e72d9119d0aab8be3d34834
b0261e231fc02a2a1714327807a38a9579e9652d
/fromLocal/VendingMachine/src/main/java/com/bl/vendingmachine/controller/VendingMachineController.java
247dff393880c7db3215038e002552811223aea4
[]
no_license
thebenlarson/classProjects
48982430dacf62ea9493ffc6a36f24d7efa9d44f
bb815e2a4bd66412973df4848a09e5792154613c
refs/heads/master
2023-02-18T17:05:44.891118
2021-01-21T03:04:15
2021-01-21T03:04:15
331,496,660
0
0
null
null
null
null
UTF-8
Java
false
false
3,585
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 com.bl.vendingmachine.controller; import com.bl.vendingmachine.dao.VendingMachineInvalidCodeException; import com.bl.vendingmachine.dao.VendingMachinePersistenceException; import com.bl.vendingmachine.dto.VendingItem; import com.bl.vendingmachine.service.*; import com.bl.vendingmachine.ui.*; import java.util.List; import java.util.Scanner; /** * * @author benth */ public class VendingMachineController { VendingMachineService service; VendingMachineView view; Scanner scanner = new Scanner(System.in); public VendingMachineController(VendingMachineService service, VendingMachineView view){ this.service = service; this.view = view; } public void run(){ boolean exit = false; int choice; loadData(); while (!exit){ displayInventory(); boolean invalidChoice; do { invalidChoice = false; choice = getMenuChoice(); switch(choice){ case 1: addMoney(); break; case 2: makePurchase(); break; case 3: exit = true; break; default: invalidChoice(); invalidChoice = true; break; } } while (invalidChoice); } giveChange(); saveData(); } private void displayInventory(){ List<VendingItem> inventory = service.getInStockVendingItems(); view.displayInventory(inventory, service.getBalance()); } private void loadData(){ try { service.loadInventory(); } catch (VendingMachinePersistenceException ex) { displayException(ex); } } private void saveData(){ try { service.writeInventory(); } catch (VendingMachinePersistenceException ex) { displayException(ex); } } private int getMenuChoice(){ return view.displayMenu(); } private void addMoney(){ boolean error; do { error = false; try{ service.addMoney(view.getAddMoney()); } catch (NumberFormatException e){ error = true; displayInputError(); } } while (error); } private void makePurchase(){ try{ service.checkBalance(); VendingItem vendingItem = service.purchaseVendingItem(view.getCode()); view.getItem(vendingItem); } catch (VendingMachineInsufficientFundsException | VendingMachineNoItemInventoryException | VendingMachineInvalidCodeException | VendingMachinePersistenceException e){ displayException(e); } } private void invalidChoice(){ view.displayInvalidChoice(); } private void displayException(Exception e){ view.displayException(e); } private void displayInputError(){ view.displayInputError(); } private void giveChange(){ view.displayChange(service.getChange()); } }
[ "benlarson_fullstack@yahoo.com" ]
benlarson_fullstack@yahoo.com
afcf8f1c9e7a30b034112d135be49307d6ed656e
5cabdb14f69058b144b2fc194e613c8123481fc3
/src/main/java/by/teplouhova/chef/builder/impl/VegetablesSTAXBuilder.java
f24ca5260093ab6b5a43368dca522c9b3ff6843e
[]
no_license
Katinuta/xmlparsing
a84b8a994dc7bd5a3efd0e843ca0bf37a5a9e6c8
6c709a77f15dbead04751adebb8f1b6da889f7eb
refs/heads/master
2021-08-14T16:54:42.054512
2017-11-16T08:50:14
2017-11-16T08:50:14
110,946,849
0
0
null
null
null
null
UTF-8
Java
false
false
8,462
java
package by.teplouhova.chef.builder.impl; import by.teplouhova.chef.builder.AbstractVegetablesBuilder; import by.teplouhova.chef.builder.SaladEnum; import by.teplouhova.chef.entity.CuttingStyle; import by.teplouhova.chef.entity.Vegetable; import by.teplouhova.chef.entity.WayCooking; import by.teplouhova.chef.entity.FruitVegetable; import by.teplouhova.chef.entity.LeafyVegetable; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class VegetablesSTAXBuilder extends AbstractVegetablesBuilder { private static final Logger LOGGER = LogManager.getLogger(); private Vegetable vegetable; private XMLInputFactory xmlInputFactory; public VegetablesSTAXBuilder() { xmlInputFactory = XMLInputFactory.newInstance(); } public void buildSalad(String fileName) { XMLStreamReader reader; String name; try (FileInputStream inputStream = new FileInputStream(new File(fileName))) { reader = xmlInputFactory.createXMLStreamReader(inputStream); while (reader.hasNext()) { int type = reader.next(); if (type == XMLStreamConstants.START_ELEMENT) { name = reader.getLocalName(); if (SaladEnum.valueOf(name.toUpperCase().replace("-", "_")) == SaladEnum.LEAFY_VEGETABLE) { vegetable = new LeafyVegetable(); vegetable = buildVegetable(reader); salad.add(vegetable); } if (SaladEnum.valueOf(name.toUpperCase().replace("-", "_")) == SaladEnum.FRUIT_VEGETABLE) { vegetable = new FruitVegetable(); vegetable = buildVegetable(reader); salad.add(vegetable); } } } } catch (FileNotFoundException e) { LOGGER.log(Level.FATAL, "File is not found : " + fileName + " " + e); throw new RuntimeException("File is not found : " + fileName + " " + e); } catch (XMLStreamException e) { LOGGER.log(Level.ERROR, "Error STAX-parser " + e); } catch (IOException e) { LOGGER.log(Level.FATAL, "Error file" + fileName + e); throw new RuntimeException("Error file" + fileName + e); } } private Vegetable buildVegetable(XMLStreamReader reader) { String name; if (reader.getAttributeCount() != 0) { int countAttribute = reader.getAttributeCount(); for (int index = 0; index < countAttribute; index++) { name = reader.getAttributeLocalName(index); switch (SaladEnum.valueOf(name.toUpperCase().replace("-", "_"))) { case VEGETABLE_ID: vegetable.setVegetableId(reader.getAttributeValue(null, SaladEnum.VEGETABLE_ID.getValue())); break; case VEGETABLE_NAME: vegetable.setVegetableName(reader.getAttributeValue(null, SaladEnum.VEGETABLE_NAME.getValue())); break; case WAY_COOKING: vegetable.setWayCooking( WayCooking.valueOf(reader.getAttributeValue(null, SaladEnum.WAY_COOKING.getValue()).toUpperCase())); break; } } } try { while (reader.hasNext()) { int type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: { name = reader.getLocalName(); switch (SaladEnum.valueOf(name.toUpperCase().replace("-", "_"))) { case WEIGHT: vegetable.setWeight(Integer.parseInt(getXMLTxt(reader))); break; case CALORICITY: vegetable.setCaloricity(Integer.parseInt(getXMLTxt(reader))); break; case CUTTING_STYLE: vegetable.setCuttingStyle(CuttingStyle.valueOf(getXMLTxt(reader).toUpperCase())); break; case COMPOSITION: vegetable.setComposition(buildComposition(reader)); break; case USING_SEEKS: { if (vegetable instanceof FruitVegetable) { ((FruitVegetable) vegetable).setUsingSeeks(Boolean.valueOf(getXMLTxt(reader))); } break; } case USING_LEAF: { if (vegetable instanceof LeafyVegetable) { ((LeafyVegetable) vegetable).setUsingLeaf(Boolean.valueOf(getXMLTxt(reader))); } break; } case USING_STALK: { if (vegetable instanceof LeafyVegetable) { ((LeafyVegetable) vegetable).setUsingStalk(Boolean.valueOf(getXMLTxt(reader))); } break; } } break; } case XMLStreamConstants.END_ELEMENT: { name = reader.getLocalName().replace("-", "_").toUpperCase(); if (SaladEnum.valueOf(name) == SaladEnum.LEAFY_VEGETABLE || SaladEnum.valueOf(name) == SaladEnum.FRUIT_VEGETABLE) { if (vegetable.getWayCooking() == null) { vegetable.setWayCooking(WayCooking.RAW); } return vegetable; } break; } } } } catch (XMLStreamException e) { LOGGER.log(Level.ERROR, "Error STAX-parser " + e); } return vegetable; } private String getXMLTxt(XMLStreamReader reader) throws XMLStreamException { String text = null; if (reader.hasNext()) { reader.next(); if (!reader.isEndElement()) { text = reader.getText(); } } return text; } private Vegetable.Composition buildComposition(XMLStreamReader reader) throws XMLStreamException { Vegetable.Composition composition = new Vegetable.Composition(); int type; String name; while (reader.hasNext()) { type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: { name = reader.getLocalName(); switch (SaladEnum.valueOf(name.replace("-", "_").toUpperCase())) { case FAT: composition.setFat(Double.parseDouble(getXMLTxt(reader))); break; case CARBOHYDRATE: composition.setCarbohydrate(Double.parseDouble(getXMLTxt(reader))); break; case PROTEIN: composition.setProtein(Double.parseDouble(getXMLTxt(reader))); break; } break; } case XMLStreamConstants.END_ELEMENT: { name = reader.getLocalName(); if (SaladEnum.valueOf(name.replace("-", "_").toUpperCase()) == SaladEnum.COMPOSITION) { return composition; } break; } } } throw new XMLStreamException(); } }
[ "katinuta@gmail.com" ]
katinuta@gmail.com
7f1883e35f6cf2956cb0b30102362692029bc8cb
ee631691814915676e70ef5097910b3304bd23f1
/src/main/java/com/tian/cola/dao/comment/CommentDAO.java
3d5573c83a120d65d1b45183ca055bd4520a45e3
[]
no_license
tiancz/ssm
8342aab056f2326b505c1d0547626ad9a51575d1
bcf2ab017c250baa7a8eea61009d4a3ef6d18728
refs/heads/master
2021-01-19T03:50:52.910335
2017-10-08T07:10:23
2017-10-08T07:10:23
65,386,193
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.tian.cola.dao.comment; import java.util.List; import com.tian.cola.dto.comment.CommentDTO; /** * <p>Title:Comment</p> * <p>Description:</p> * @author tianchaozhe665 * @Email nathanieltian@163.com * @date 2016年11月24日 下午11:03:57 **/ public interface CommentDAO { public List<CommentDTO> queryComments(String articleId); public int countComment(String articleId); }
[ "nathanieltian@163.com" ]
nathanieltian@163.com
1167d356b723f29a52a4b5bf284ae65cd2ced149
a6c2d9177bbca8cb4bab58a4fc1536e82ed7d220
/src/main/java/com/shenke/repository/WuliaoRepository.java
e889b9c89b1dfe7aed518b9f562ae98280914cbb
[]
no_license
chao3373/MES
05eaf1728167e38a2236313818696ff775b49e76
152b2d71e1a7cc8f23883d5fc8d8f535794fbde5
refs/heads/master
2022-07-11T03:49:27.224172
2020-02-11T11:36:13
2020-02-11T11:36:13
193,823,642
0
0
null
2022-06-29T17:28:12
2019-06-26T03:33:37
JavaScript
UTF-8
Java
false
false
1,108
java
package com.shenke.repository; import com.shenke.entity.Wuliao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface WuliaoRepository extends JpaRepository<Wuliao,Integer> , JpaSpecificationExecutor<Wuliao> { /** * 根据大图ID查找 * @param id * @return */ @Query(value = "select * from t_wuliao where big_drawing_id =?1",nativeQuery = true) public List<Wuliao> findByBigDrawingId(Integer id); /** * 根据订单Id查询 * @param saleListId * @return */ @Query(value = "select * from t_wuliao where sale_list_id = ?1",nativeQuery = true) List<Wuliao> findBySaleListId(Integer saleListId); /** * 根据大图id删除 * @param id */ @Modifying @Query(value = "delete from t_wuliao where big_drawing_id = ?1",nativeQuery = true) void deleteByBigDrawingId(Integer id); }
[ "17864308105@163.com" ]
17864308105@163.com
3ed26b251c23efd868951c93539f38d942d130ae
cc8aeb50685b0b7fa46b70a54f25ecf3808adb69
/src/java/dao/PlanDAO.java
fd7fc3b39739b09254dfcc65aead59db39944952
[]
no_license
hanx2307/gyma
b1f1043fd99c62926eed7e0c712241a767795aee
cbd405f9fe8a88b2e2f0c11ea93c5feba94d6f18
refs/heads/master
2020-05-31T21:58:25.338895
2017-06-12T04:10:30
2017-06-12T04:10:30
94,049,885
0
0
null
null
null
null
UTF-8
Java
false
false
4,040
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 dao; import connect.DBConnect; import java.sql.Connection; import static java.sql.JDBCType.NULL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import models.Plan; import models.User; /** * * @author Jack */ public class PlanDAO { public ArrayList<Plan> getListPlan() throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT * FROM plan"; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); ArrayList<Plan> list = new ArrayList<>(); while (rs.next()) { Plan plan = new Plan(); plan.setPlanID(rs.getLong("id")); plan.setPlanDescription(rs.getString("plan_description")); plan.setPlanName(rs.getString("plan_name")); plan.setPlanDay(rs.getLong("plan_day")); plan.setPlanRate(rs.getLong("plan_rate")); list.add(plan); } return list; } public Plan getListPlanFromID(Long id) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT * FROM plan WHERE id = '"+id+"' "; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { Plan plan = new Plan(); plan.setPlanID(rs.getLong("id")); plan.setPlanDescription(rs.getString("plan_description")); plan.setPlanName(rs.getString("plan_name")); plan.setPlanDay(rs.getLong("plan_day")); plan.setPlanRate(rs.getLong("plan_rate")); return plan; } return null; } public Plan getdayPlanFromID(Long id) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "SELECT plan_day FROM plan WHERE id = '"+id+"' "; PreparedStatement ps = conn.prepareCall(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) { Plan plan = new Plan(); plan.setPlanDay(rs.getLong("plan_day")); return plan; } return null; } public boolean insertPlan(Plan p) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "INSERT INTO plan VALUES(?,?,?,?,?)"; try { PreparedStatement ps = conn.prepareCall(sql); ps.setNull(1, java.sql.Types.INTEGER); ps.setString(2, p.getPlanName()); ps.setString(3, p.getPlanDescription()); ps.setLong(4, p.getPlanDay()); ps.setLong(5, p.getPlanRate()); return ps.executeUpdate() == 1; } catch (SQLException ex) { Logger.getLogger(PlanDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean updatePlan(Plan p) throws SQLException { Connection conn = DBConnect.getConnection(); String sql = "UPDATE plan SET plan_name = ? ,plan_description = ?, plan_day = ?, plan_rate = ? WHERE id = ?"; try { PreparedStatement ps = conn.prepareCall(sql); ps.setString(1, p.getPlanName()); ps.setString(2, p.getPlanDescription()); ps.setLong(3, p.getPlanDay()); ps.setLong(4, p.getPlanRate()); ps.setLong(5, p.getPlanID()); return ps.executeUpdate() == 1; } catch (SQLException ex) { Logger.getLogger(PlanDAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public static void main(String[] args) throws SQLException { // PlanDAO dao = new PlanDAO(); // dao.insertPlan(new Plan(1,"VIP","Day la Vip",30,150000)); } }
[ "hanx2307@gmail.com" ]
hanx2307@gmail.com
8a227ce6881664602e6cc9cf2396e221e8ad979d
5707536bdaffe1c0de2abfa838111cabb287c452
/components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth/dto/OAuthIDTokenAlgorithmDTO.java
bfc0e1347e3f018689af84acf749647b0022986e
[ "Apache-2.0" ]
permissive
wso2-extensions/identity-inbound-auth-oauth
1ea5481d0595e56fdf972c1bc6e6bd1c61bd7d82
d153b3dd2ae065df135566cb6e8951ac8c1a8645
refs/heads/master
2023-09-01T08:58:09.127138
2023-09-01T05:37:33
2023-09-01T05:37:33
52,758,721
28
410
Apache-2.0
2023-09-14T12:13:20
2016-02-29T02:41:06
Java
UTF-8
Java
false
false
2,325
java
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.oauth.dto; import java.util.List; /** * Class to transfer ID token encryption related algorithms. */ public class OAuthIDTokenAlgorithmDTO { private String defaultIdTokenEncryptionAlgorithm; private List<String> supportedIdTokenEncryptionAlgorithms; private String defaultIdTokenEncryptionMethod; private List<String> supportedIdTokenEncryptionMethods; public String getDefaultIdTokenEncryptionAlgorithm() { return defaultIdTokenEncryptionAlgorithm; } public String getDefaultIdTokenEncryptionMethod() { return defaultIdTokenEncryptionMethod; } public List<String> getSupportedIdTokenEncryptionAlgorithms() { return supportedIdTokenEncryptionAlgorithms; } public List<String> getSupportedIdTokenEncryptionMethods() { return supportedIdTokenEncryptionMethods; } public void setDefaultIdTokenEncryptionAlgorithm(String defaultIdTokenEncryptionAlgorithm) { this.defaultIdTokenEncryptionAlgorithm = defaultIdTokenEncryptionAlgorithm; } public void setDefaultIdTokenEncryptionMethod(String defaultIdTokenEncryptionMethod) { this.defaultIdTokenEncryptionMethod = defaultIdTokenEncryptionMethod; } public void setSupportedIdTokenEncryptionAlgorithms(List<String> supportedIdTokenEncryptionAlgorithms) { this.supportedIdTokenEncryptionAlgorithms = supportedIdTokenEncryptionAlgorithms; } public void setSupportedIdTokenEncryptionMethods(List<String> supportedIdTokenEncryptionMethods) { this.supportedIdTokenEncryptionMethods = supportedIdTokenEncryptionMethods; } }
[ "vihangaliyanage007@gmail.com" ]
vihangaliyanage007@gmail.com
697c907fbb0426aeec428bc380132b244b902dae
2f4d648198afa52c17f626cc2d4bfb4d7f3e8d5a
/src/uex/durian/Box.java
da6c4529b93c890bca6f9007b424db21ba06a830
[]
no_license
jgarciapft/PracticaLaberintos
bd91bf074140d0d916aa4dfc22f77d7638ef06fa
c1c2a43ec1de609fe3e5269a8f04b2943324d9b1
refs/heads/master
2020-05-03T11:46:52.779898
2019-04-22T16:09:05
2019-04-22T16:09:05
178,608,994
0
0
null
null
null
null
UTF-8
Java
false
false
18,005
java
/* * Copyright 2016 DiffPlug * * 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 uex.durian; import java.util.Objects; import java.util.function.*; /** * Provides get/set access to a mutable non-null value. */ public interface Box<T> extends Supplier<T>, Consumer<T> { /** * Creates a `Box` holding the given value in a `volatile` field. * <p> * Every call to {@link #set(Object)} confirms that the argument * is actually non-null, and the value is stored in a volatile variable. */ public static <T> Box<T> ofVolatile(T value) { return new Volatile<>(value); } /** * Creates a `Box` holding the given value in a non-`volatile` field. * <p> * The value is stored in standard non-volatile * field, and non-null-ness is not checked on * every call to set. */ public static <T> Box<T> of(T value) { return new Default<>(value); } /** * Creates a `Box` from a `Supplier` and a `Consumer`. */ public static <T> Box<T> from(Supplier<T> getter, Consumer<T> setter) { Objects.requireNonNull(getter); Objects.requireNonNull(setter); return new Box<T>() { @Override public T get() { return Objects.requireNonNull(getter.get()); } @Override public void set(T value) { setter.accept(Objects.requireNonNull(value)); } @Override public String toString() { return "Box.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(T value); /** * Delegates to set(). * * @deprecated Provided to satisfy the {@link Consumer} interface; use {@link #set} instead. */ @Deprecated default void accept(T value) { set(value); } /** * Performs a set() on the result of a get(). * <p> * Some implementations may provide atomic semantics, * but it's not required. */ default T modify(Function<? super T, ? extends T> mutator) { T modified = mutator.apply(get()); set(modified); return modified; } /** * Maps one {@code Box} to another {@code Box}, preserving any * {@link #modify(Function)} guarantees of the underlying Box. */ default <R> Box<R> map(Converter<T, R> converter) { return new Mapped<>(this, converter); } /** * Provides get/set access to a mutable nullable value. */ public interface Nullable<T> extends Supplier<T>, Consumer<T> { /** * Creates a `Box.Nullable` holding the given possibly-null value in a `volatile` field. */ public static <T> Nullable<T> ofVolatile(T init) { return new Volatile<>(init); } /** * Creates a `Box.Nullable` holding a null value in a `volatile` field. */ public static <T> Nullable<T> ofVolatileNull() { return ofVolatile(null); } /** * Creates a `Box.Nullable` holding the given possibly-null value in a non-`volatile` field. */ public static <T> Nullable<T> of(T init) { return new Default<>(init); } /** * Creates a `Box.Nullable` holding null value in a non-`volatile` field. */ public static <T> Nullable<T> ofNull() { return of(null); } /** * Creates a `Box.Nullable` from a `Supplier` and a `Consumer`. */ public static <T> Nullable<T> from(Supplier<T> getter, Consumer<T> setter) { Objects.requireNonNull(getter); Objects.requireNonNull(setter); return new Nullable<T>() { @Override public T get() { return getter.get(); } @Override public void set(T value) { setter.accept(value); } @Override public String toString() { return "Box.Nullable.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(T value); /** * Delegates to set(). * * @deprecated Provided to satisfy the {@code Function} interface; use {@link #set} instead. */ @Deprecated default void accept(T value) { set(value); } /** * Shortcut for doing a set() on the result of a get(). */ default T modify(Function<? super T, ? extends T> mutator) { T modified = mutator.apply(get()); set(modified); return modified; } /** * Maps one {@code Box} to another {@code Box}, preserving any * {@link #modify(Function)} guarantees of the underlying Box. */ default <R> Nullable<R> map(ConverterNullable<T, R> converter) { return new Nullable.Mapped<>(this, converter); } static final class Mapped<T, R> implements Nullable<R> { private final Nullable<T> delegate; private final ConverterNullable<T, R> converter; public Mapped(Nullable<T> delegate, ConverterNullable<T, R> converter) { this.delegate = delegate; this.converter = converter; } @Override public R get() { return converter.convert(delegate.get()); } @Override public void set(R value) { delegate.set(converter.revert(value)); } /** * Shortcut for doing a set() on the result of a get(). */ @Override public R modify(Function<? super R, ? extends R> mutator) { Box.Nullable<R> result = Box.Nullable.of(null); delegate.modify(input -> { R unmappedResult = mutator.apply(converter.convert(input)); result.set(unmappedResult); return converter.revert(unmappedResult); }); return result.get(); } @Override public String toString() { return "[" + delegate + " mapped to " + get() + " by " + converter + "]"; } } static class Volatile<T> implements Box.Nullable<T> { private volatile T obj; private Volatile(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = obj; } @Override public String toString() { return "Box.Nullable.ofVolatile[" + get() + "]"; } } static class Default<T> implements Box.Nullable<T> { private T obj; private Default(T init) { this.obj = init; } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = obj; } @Override public String toString() { return "Box.Nullable.of[" + get() + "]"; } } } /** * A `Box` for primitive doubles. */ public interface Dbl extends DoubleSupplier, DoubleConsumer, Box<Double> { /** * Creates a `Box.Dbl` holding the given value in a non-`volatile` field. */ public static Dbl of(double value) { return new Default(value); } /** * Creates a `Box.Dbl` from a `DoubleSupplier` and a `DoubleConsumer`. */ public static Dbl from(DoubleSupplier getter, DoubleConsumer setter) { return new Dbl() { @Override public double getAsDouble() { return getter.getAsDouble(); } @Override public void set(double value) { setter.accept(value); } @Override public String toString() { return "Box.Dbl.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by get(). */ void set(double value); @Override double getAsDouble(); /** * Delegates to {@link #getAsDouble()}. * * @deprecated Provided to satisfy {@code Box<Double>}; use {@link #getAsDouble()} instead. */ @Override @Deprecated default Double get() { return getAsDouble(); } /** * Delegates to {@link #set(double)}. * * @deprecated Provided to satisfy {@code Box<Double>}; use {@link #set(double)} instead. */ @Override @Deprecated default void set(Double value) { set(value.doubleValue()); } /** * Delegates to {@link #set(double)}. * * @deprecated Provided to satisfy the {@link DoubleConsumer}; use {@link #set(double)} instead. */ @Deprecated @Override default void accept(double value) { set(value); } static class Default implements Box.Dbl { private double obj; private Default(double init) { set(init); } @Override public double getAsDouble() { return obj; } @Override public void set(double obj) { this.obj = obj; } @Override public String toString() { return "Box.Dbl.of[" + getAsDouble() + "]"; } } } /** * A `Box` for primitive ints. */ public interface Int extends IntSupplier, IntConsumer, Box<Integer> { /** * Creates a `Box.Int` holding the given value in a non-`volatile` field. */ public static Int of(int value) { return new Default(value); } /** * Creates a `Box.Int` from a `IntSupplier` and a `IntConsumer`. */ public static Int from(IntSupplier getter, IntConsumer setter) { return new Int() { @Override public int getAsInt() { return getter.getAsInt(); } @Override public void set(int value) { setter.accept(value); } @Override public String toString() { return "Box.Int.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by {@link #getAsInt()}. */ void set(int value); @Override int getAsInt(); /** * Delegates to {@link #getAsInt()}. * * @deprecated Provided to satisfy {@code Box<Integer>}; use {@link #getAsInt()} instead. */ @Override @Deprecated default Integer get() { return getAsInt(); } /** * Delegates to {@link #set(int)}. * * @deprecated Provided to satisfy {@code Box<Integer>}; use {@link #set(int)} instead. */ @Override @Deprecated default void set(Integer value) { set(value.intValue()); } /** * Delegates to {@link #set}. * * @deprecated Provided to satisfy the {@link IntConsumer} interface; use {@link #set(int)} instead. */ @Deprecated @Override default void accept(int value) { set(value); } static class Default implements Box.Int { private int obj; private Default(int init) { set(init); } @Override public int getAsInt() { return obj; } @Override public void set(int obj) { this.obj = obj; } @Override public String toString() { return "Box.Int.of[" + get() + "]"; } } } /** * A `Box` for primitive longs. */ public interface Lng extends LongSupplier, LongConsumer, Box<Long> { /** * Creates a `Box.Long` holding the given value in a non-`volatile` field. */ public static Lng of(long value) { return new Default(value); } /** * Creates a `Box.Long` from a `LongSupplier` and a `LongConsumer`. */ public static Lng from(LongSupplier getter, LongConsumer setter) { return new Lng() { @Override public long getAsLong() { return getter.getAsLong(); } @Override public void set(long value) { setter.accept(value); } @Override public String toString() { return "Box.Long.from[" + get() + "]"; } }; } /** * Sets the value which will later be returned by {@link #getAsLong()}. */ void set(long value); @Override long getAsLong(); /** * Auto-boxed getter. * * @deprecated Provided to satisfy {@code Box<Long>} interface; use {@link #getAsLong()} instead. */ @Override @Deprecated default Long get() { return getAsLong(); } /** * Delegates to {@link #set(long)}. * * @deprecated Provided to satisfy {@code Box<Long>} interface; use {@link #set(long)} instead. */ @Override @Deprecated default void set(Long value) { set(value.longValue()); } /** * Delegates to {@link #set(long)}. * * @deprecated Provided to satisfy {@link LongConsumer} interface; use {@link #set(long)} instead. */ @Deprecated @Override default void accept(long value) { set(value); } static class Default implements Box.Lng { private long obj; private Default(long init) { set(init); } @Override public long getAsLong() { return obj; } @Override public void set(long obj) { this.obj = obj; } @Override public String toString() { return "Box.Long.of[" + get() + "]"; } } } static final class Mapped<T, R> implements Box<R> { private final Box<T> delegate; private final Converter<T, R> converter; public Mapped(Box<T> delegate, Converter<T, R> converter) { this.delegate = delegate; this.converter = converter; } @Override public R get() { return converter.convertNonNull(delegate.get()); } @Override public void set(R value) { delegate.set(converter.revertNonNull(value)); } /** * Shortcut for doing a set() on the result of a get(). */ @Override public R modify(Function<? super R, ? extends R> mutator) { Box.Nullable<R> result = Box.Nullable.of(null); delegate.modify(input -> { R unmappedResult = mutator.apply(converter.convertNonNull(input)); result.set(unmappedResult); return converter.revertNonNull(unmappedResult); }); return result.get(); } @Override public String toString() { return "[" + delegate + " mapped to " + get() + " by " + converter + "]"; } } static final class Volatile<T> implements Box<T> { private volatile T obj; private Volatile(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = Objects.requireNonNull(obj); } @Override public String toString() { return "Box.ofVolatile[" + get() + "]"; } } static final class Default<T> implements Box<T> { private T obj; private Default(T init) { set(init); } @Override public T get() { return obj; } @Override public void set(T obj) { this.obj = Objects.requireNonNull(obj); } @Override public String toString() { return "Box.of[" + get() + "]"; } } }
[ "jgarciapft@alumnos.unex.es" ]
jgarciapft@alumnos.unex.es