code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/** Copyright 2008, 2009 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença. Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. **/ package br.ufpe.cin.amadeus.amadeus_mobile.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll; public class Conversor { /** * Method that converts AMADeUs Course object into Mobile Course object * @param curso - AMADeUs Course to be converted * @return - Converted Mobile Course object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile converterCurso(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course curso){ br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile(); retorno.setId(curso.getId()); retorno.setName(curso.getName()); retorno.setContent(curso.getContent()); retorno.setObjectives(curso.getObjectives()); retorno.setModules(converterModulos(curso.getModules())); retorno.setKeywords(converterKeywords(curso.getKeywords())); ArrayList<String> nomes = new ArrayList<String>(); nomes.add(curso.getProfessor().getName()); retorno.setTeachers(nomes); retorno.setCount(0); retorno.setMaxAmountStudents(curso.getMaxAmountStudents()); retorno.setFinalCourseDate(curso.getFinalCourseDate()); retorno.setInitialCourseDate(curso.getInitialCourseDate()); return retorno; } /** * Method that converts a AMADeUs Course object list into Mobile Course object list * @param cursos - AMADeUs Course object list to be converted * @return - Converted Mobile Course object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> converterCursos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course> cursos){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course c : cursos){ retorno.add(Conversor.converterCurso(c)); } return retorno; } /** * Method that converts AMADeUs Module object into Mobile Module object * @param modulo - AMADeUs Module object to be converted * @return - Converted Mobile Module object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile converterModulo(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module modulo){ br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile mod = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile(modulo.getId(), modulo.getName()); List<HomeworkMobile> listHomeworks = new ArrayList<HomeworkMobile>(); for (Poll poll : modulo.getPolls()) { listHomeworks.add( Conversor.converterPollToHomework(poll) ); } for (Forum forum : modulo.getForums()) { listHomeworks.add( Conversor.converterForumToHomework(forum) ); } for(Game game : modulo.getGames()){ listHomeworks.add( Conversor.converterGameToHomework(game) ); } for(LearningObject learning : modulo.getLearningObjects()){ listHomeworks.add( Conversor.converterLearningObjectToHomework(learning) ); } mod.setHomeworks(listHomeworks); mod.setMaterials(converterMaterials(modulo.getMaterials())); return mod; } /** * Mothod that converts a AMADeUs Module object list into Mobile Module object list * @param modulos - AMADeUs Module object list to be converted * @return - Converted Mobile Module object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> converterModulos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module> modulos){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module m : modulos){ retorno.add(Conversor.converterModulo(m)); } return retorno; } /** * Method that converts AMADeUs Homework object into Mobile Homework object * @param home - AMADeUs Homework object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework home){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(home.getId()); retorno.setName(home.getName()); retorno.setDescription(home.getDescription()); retorno.setInitDate(home.getInitDate()); retorno.setDeadline(home.getDeadline()); retorno.setAlowPostponing(home.getAllowPostponing()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.HOMEWORK); return retorno; } /** * Method that converts AMADeUs Game object into Mobile Homework object * @param game - AMADeUs Game object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterGameToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game game){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(game.getId()); retorno.setName(game.getName()); retorno.setDescription(game.getDescription()); retorno.setInfoExtra(game.getUrl()); retorno.setTypeActivity(HomeworkMobile.GAME); return retorno; } /** * Method that converts AMADeUs Forum object into Mobile Homework object * @param forum - AMADeUs Forum object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterForumToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum forum){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(forum.getId()); retorno.setName(forum.getName()); retorno.setDescription(forum.getDescription()); retorno.setInitDate(forum.getCreationDate()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.FORUM); return retorno; } /** * Method that converts AMADeUs Poll object into Mobile Homework object * @param poll - AMADeUs Poll object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterPollToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll poll){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(poll.getId()); retorno.setName(poll.getName()); retorno.setDescription(poll.getQuestion()); retorno.setInitDate(poll.getCreationDate()); retorno.setDeadline(poll.getFinishDate()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.POLL); return retorno; } /** * Method that converts AMADeUs Multimedia object into Mobile Homework object * @param media - AMADeUs Multimedia object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterMultimediaToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Multimedia media){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(media.getId()); retorno.setName(media.getName()); retorno.setDescription(media.getDescription()); retorno.setInfoExtra(media.getUrl()); retorno.setTypeActivity(HomeworkMobile.MULTIMEDIA); return retorno; } /** * Method that converts AMADeUs Video object into Mobile Homework object * @param video - AMADeUs Video object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterVideoToHomework(br.ufpe.cin.amadeus.amadeus_sdmm.dao.Video video){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(video.getId()); retorno.setName(video.getName()); retorno.setDescription(video.getDescription()); retorno.setInitDate(video.getDateinsertion()); retorno.setInfoExtra(video.getTags()); retorno.setTypeActivity(HomeworkMobile.VIDEO); return retorno; } public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterLearningObjectToHomework( br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning) { br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(learning.getId()); retorno.setName(learning.getName()); retorno.setUrl(learning.getUrl()); retorno.setDescription(learning.getDescription()); retorno.setDeadline(learning.getCreationDate()); retorno.setTypeActivity(HomeworkMobile.LEARNING_OBJECT); return retorno; } /** * Method that converts AMADeUs Homework object list into Mobile Homework object list * @param homes - AMADeUs Homework object list to be converted * @return - Converted Mobile Homework object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> converterHomeworks(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework> homes){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework h : homes){ retorno.add(Conversor.converterHomework(h)); } return retorno; } /** * Method that converts AMADeUs Material object into Mobile Material object * @param mat - AMADeUs Material object to be converted * @return - Mobile Material object converted */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile converterMaterial(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat){ br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile(); retorno.setId(mat.getId()); retorno.setName(mat.getArchiveName()); retorno.setAuthor(converterPerson(mat.getAuthor())); retorno.setPostDate(mat.getCreationDate()); return retorno; } /** * Method that converts AMADeUs Mobile Material object list into Mobile Material object list * @param mats - AMADeUs Material object list * @return - Mobile Material object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> converterMaterials(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material> mats){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat : mats){ retorno.add(Conversor.converterMaterial(mat)); } return retorno; } /** * Method that converts AMADeUs Keyword object into Mobile Keyword object * @param key - AMADeUs Keyword object to be converted * @return - Converted Keywork object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile converterKeyword(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword key){ br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile(); retorno.setId(key.getId()); retorno.setName(key.getName()); retorno.setPopularity(key.getPopularity()); return retorno; } /** * Method that converts AMADeUs Keyword object list into a Mobile Keyword HashSet object * @param keys - AMADeUs Keyword object list to be converted * @return - Mobile Keywork HashSet object list */ public static HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> converterKeywords(Set<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword> keys){ HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> retorno = new HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword k : keys){ retorno.add(Conversor.converterKeyword(k)); } return retorno; } /** * Method that converts AMADeUs Choice object into Mobile Choice object * @param ch - AMADeUs Choice object to be converted * @return - Converted Mobile Choice object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile converterChoice(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice ch){ br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile(); retorno.setId(ch.getId()); retorno.setAlternative(ch.getAlternative()); retorno.setVotes(ch.getVotes()); retorno.setPercentage(ch.getPercentage()); return retorno; } /** * Method that converts AMADeUs Choice object list into Mobile Choice object list * @param chs - AMADeUs Choice object list to be converted * @return - Converted Mobile Choice object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> converterChoices(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> chs){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice c : chs){ retorno.add(Conversor.converterChoice(c)); } return retorno; } /** * Method that converts AMADeUs Poll object into Mobile Poll Object * @param p - AMADeUs Poll object to be converted * @return - Converted Mobile Poll object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile converterPool(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p){ br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile(); retorno.setId(p.getId()); retorno.setName(p.getName()); retorno.setQuestion(p.getQuestion()); retorno.setInitDate(p.getCreationDate()); retorno.setFinishDate(p.getFinishDate()); retorno.setAnswered(false); retorno.setChoices(converterChoices(p.getChoices())); retorno.setAnsewered(converterAnswers(p.getAnswers())); return retorno; } public static br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile converterLearningObject (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning){ br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile(); retorno.setId(learning.getId()); retorno.setName(learning.getName()); retorno.setDescription(learning.getDescription()); retorno.setDatePublication(learning.getCreationDate()); retorno.setUrl(learning.getUrl()); return retorno; } /** * Method that converts AMADeUs Poll object list into Mobile Poll object list * @param pls - AMADeUs Poll object list * @return - Converted Mobile object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> converterPools(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll> pls){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p : pls){ retorno.add(Conversor.converterPool(p)); } return retorno; } /** * Method that converts AMADeUs Answer object into Mobile Answer object * @param ans - AMADeUs Answer object to be converted * @return - Converted Mobile Answer object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile converterAnswer(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer ans){ br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile(); retorno.setId(ans.getId()); retorno.setAnswerDate(ans.getAnswerDate()); retorno.setPerson(converterPerson(ans.getPerson())); return retorno; } /** * Method that converts AMADeUs Answer object list into Mobile Answer object list * @param anss - AMADeUs Answer object list * @return - Converted Mobile object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> converterAnswers(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> anss){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer an : anss){ retorno.add(Conversor.converterAnswer(an)); } return retorno; } /** * Method that converts AMADeUs Person object into Mobile Person object * @param p - AMADeUs Person object to be converted * @return - Converted Mobile Person object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile converterPerson(br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p){ return new br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile(p.getId(), p.getAccessInfo().getLogin(), p.getPhoneNumber()); } /** * Method that converts AMADeUs Person object list into Mobile Person object list * @param persons - AMADeUs Person object list to be converted * @return - Converted Mobile Person object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> converterPersons(List<br.ufpe.cin.amadeus.amadeus_web.domain.register.Person> persons){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p : persons){ retorno.add(Conversor.converterPerson(p)); } return retorno; } /** * Method that converts Mobile Poll object into AMADeUs Poll Object * @param p - Mobile Poll object to be converted * @return - Converted AMADeUs Poll object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll converterPool(br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile p){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll(); retorno.setId(p.getId()); retorno.setName(p.getName()); retorno.setQuestion(p.getQuestion()); retorno.setCreationDate(p.getInitDate()); retorno.setFinishDate(p.getFinishDate()); retorno.setChoices(converterChoices2(p.getChoices())); retorno.setAnswers(converterAnswers2(p.getAnsewered())); return retorno; } /** * Method that converts Mobile Choice object into AMADeUs Choice object * @param ch - Mobile Choice object to be converted * @return - Converted AMADeUs Choice object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice converterChoice(br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile ch){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice(); retorno.setId(ch.getId()); retorno.setAlternative(ch.getAlternative()); retorno.setVotes(ch.getVotes()); retorno.setPercentage(ch.getPercentage()); return retorno; } /** * Method that converts Mobile Choiceobject list into AMADeUs Choice object list * @param chs - Mobile Choice object list to be converted * @return - Converted AMADeUs Choice object list */ public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> converterChoices2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> chs){ List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice>(); for (br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile c : chs){ retorno.add(Conversor.converterChoice(c)); } return retorno; } /** * Method that converts Mobile Answer object into AMADeUs Answer object * @param ans - Mobile Answer object to be converted * @return - Converted AMADeUs Answer object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer converterAnswer(br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile ans){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer(); retorno.setId(ans.getId()); retorno.setAnswerDate(ans.getAnswerDate()); retorno.setPerson(converterPerson(ans.getPerson())); return retorno; } /** * Method that converts Mobile Answer object list into AMADeUs Answer object list * @param anss - Mobile Answer object list * @return - Converted AMADeUs Answer object list */ public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> converterAnswers2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> anss){ List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer>(); for (br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile an : anss){ retorno.add(Conversor.converterAnswer(an)); } return retorno; } /** * Method that converts Mobile Person object into AMADeUs Person object * @param p - Mobile Person object to be converted * @return - Converted AMADeUs Person object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.register.Person converterPerson(br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile p){ br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p1 = new br.ufpe.cin.amadeus.amadeus_web.domain.register.Person(); p1.setId(p.getId()); p1.setName(p.getName()); p1.setPhoneNumber(p.getPhoneNumber()); return p1; } }
phcp/AmadeusLMS
src/br/ufpe/cin/amadeus/amadeus_mobile/util/Conversor.java
Java
gpl-2.0
24,368
package net.sf.memoranda.ui.htmleditor; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import net.sf.memoranda.ui.htmleditor.util.Local; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author unascribed * @version 1.0 */ public class ImageDialog extends JDialog implements WindowListener { /** * */ private static final long serialVersionUID = 5326851249529076804L; JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel header = new JLabel(); JPanel areaPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc; JLabel jLabel1 = new JLabel(); public JTextField fileField = new JTextField(); JButton browseB = new JButton(); JLabel jLabel2 = new JLabel(); public JTextField altField = new JTextField(); JLabel jLabel3 = new JLabel(); public JTextField widthField = new JTextField(); JLabel jLabel4 = new JLabel(); public JTextField heightField = new JTextField(); JLabel jLabel5 = new JLabel(); public JTextField hspaceField = new JTextField(); JLabel jLabel6 = new JLabel(); public JTextField vspaceField = new JTextField(); JLabel jLabel7 = new JLabel(); public JTextField borderField = new JTextField(); JLabel jLabel8 = new JLabel(); String[] aligns = {"left", "right", "top", "middle", "bottom", "absmiddle", "texttop", "baseline"}; // Note: align values are not localized because they are HTML keywords public JComboBox<String> alignCB = new JComboBox<String>(aligns); JLabel jLabel9 = new JLabel(); public JTextField urlField = new JTextField(); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10)); JButton okB = new JButton(); JButton cancelB = new JButton(); public boolean CANCELLED = false; public ImageDialog(Frame frame) { super(frame, Local.getString("Image"), true); try { jbInit(); pack(); } catch (Exception ex) { ex.printStackTrace(); } super.addWindowListener(this); } public ImageDialog() { this(null); } void jbInit() throws Exception { this.setResizable(false); // three Panels, so used BorderLayout for this dialog. headerPanel.setBorder(new EmptyBorder(new Insets(0, 5, 0, 5))); headerPanel.setBackground(Color.WHITE); header.setFont(new java.awt.Font("Dialog", 0, 20)); header.setForeground(new Color(0, 0, 124)); header.setText(Local.getString("Image")); header.setIcon(new ImageIcon( net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource( "resources/icons/imgbig.png"))); headerPanel.add(header); this.getContentPane().add(headerPanel, BorderLayout.NORTH); areaPanel.setBorder(new EtchedBorder(Color.white, new Color(142, 142, 142))); jLabel1.setText(Local.getString("Image file")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(10, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel1, gbc); fileField.setMinimumSize(new Dimension(200, 25)); fileField.setPreferredSize(new Dimension(285, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 5; gbc.insets = new Insets(10, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; areaPanel.add(fileField, gbc); browseB.setMinimumSize(new Dimension(25, 25)); browseB.setPreferredSize(new Dimension(25, 25)); browseB.setIcon(new ImageIcon( net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource( "resources/icons/fileopen16.png"))); browseB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { browseB_actionPerformed(e); } }); gbc = new GridBagConstraints(); gbc.gridx = 6; gbc.gridy = 0; gbc.insets = new Insets(10, 5, 5, 10); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(browseB, gbc); jLabel2.setText(Local.getString("ALT text")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel2, gbc); altField.setPreferredSize(new Dimension(315, 25)); altField.setMinimumSize(new Dimension(200, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 6; gbc.insets = new Insets(5, 5, 5, 10); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; areaPanel.add(altField, gbc); jLabel3.setText(Local.getString("Width")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel3, gbc); widthField.setPreferredSize(new Dimension(30, 25)); widthField.setMinimumSize(new Dimension(30, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(widthField, gbc); jLabel4.setText(Local.getString("Height")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 2; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel4, gbc); heightField.setMinimumSize(new Dimension(30, 25)); heightField.setPreferredSize(new Dimension(30, 25)); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(heightField, gbc); jLabel5.setText(Local.getString("H. space")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 3; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel5, gbc); hspaceField.setMinimumSize(new Dimension(30, 25)); hspaceField.setPreferredSize(new Dimension(30, 25)); hspaceField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 3; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(hspaceField, gbc); jLabel6.setText(Local.getString("V. space")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 3; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel6, gbc); vspaceField.setMinimumSize(new Dimension(30, 25)); vspaceField.setPreferredSize(new Dimension(30, 25)); vspaceField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 3; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(vspaceField, gbc); jLabel7.setText(Local.getString("Border")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel7, gbc); borderField.setMinimumSize(new Dimension(30, 25)); borderField.setPreferredSize(new Dimension(30, 25)); borderField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 4; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(borderField, gbc); jLabel8.setText(Local.getString("Align")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 4; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel8, gbc); alignCB.setBackground(new Color(230, 230, 230)); alignCB.setFont(new java.awt.Font("Dialog", 1, 10)); alignCB.setPreferredSize(new Dimension(100, 25)); alignCB.setSelectedIndex(0); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 4; gbc.gridwidth = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(alignCB, gbc); jLabel9.setText(Local.getString("Hyperlink")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 5; gbc.insets = new Insets(5, 10, 10, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel9, gbc); urlField.setPreferredSize(new Dimension(315, 25)); urlField.setMinimumSize(new Dimension(200, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 5; gbc.gridwidth = 6; gbc.insets = new Insets(5, 5, 10, 10); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.WEST; areaPanel.add(urlField, gbc); this.getContentPane().add(areaPanel, BorderLayout.CENTER); okB.setMaximumSize(new Dimension(100, 26)); okB.setMinimumSize(new Dimension(100, 26)); okB.setPreferredSize(new Dimension(100, 26)); okB.setText(Local.getString("Ok")); okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { okB_actionPerformed(e); } }); this.getRootPane().setDefaultButton(okB); cancelB.setMaximumSize(new Dimension(100, 26)); cancelB.setMinimumSize(new Dimension(100, 26)); cancelB.setPreferredSize(new Dimension(100, 26)); cancelB.setText(Local.getString("Cancel")); cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); buttonsPanel.add(okB, null); buttonsPanel.add(cancelB, null); this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); } void okB_actionPerformed(ActionEvent e) { this.dispose(); } void cancelB_actionPerformed(ActionEvent e) { CANCELLED = true; this.dispose(); } private ImageIcon getPreviewIcon(java.io.File file) { ImageIcon tmpIcon = new ImageIcon(file.getPath()); ImageIcon thmb = null; if (tmpIcon.getIconHeight() > 48) { thmb = new ImageIcon(tmpIcon.getImage() .getScaledInstance( -1, 48, Image.SCALE_DEFAULT)); } else { thmb = tmpIcon; } if (thmb.getIconWidth() > 350) { return new ImageIcon(thmb.getImage() .getScaledInstance(350, -1, Image.SCALE_DEFAULT)); } else { return thmb; } } public void updatePreview() { try { if (!(new java.net.URL(fileField.getText()).getPath()).equals("")) header.setIcon(getPreviewIcon(new java.io.File( new java.net.URL(fileField.getText()).getPath()))); } catch (Exception ex) { ex.printStackTrace(); } } public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { CANCELLED = true; this.dispose(); } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } void browseB_actionPerformed(ActionEvent e) { // Fix until Sun's JVM supports more locales... UIManager.put("FileChooser.lookInLabelText", Local .getString("Look in:")); UIManager.put("FileChooser.upFolderToolTipText", Local.getString( "Up One Level")); UIManager.put("FileChooser.newFolderToolTipText", Local.getString( "Create New Folder")); UIManager.put("FileChooser.listViewButtonToolTipText", Local .getString("List")); UIManager.put("FileChooser.detailsViewButtonToolTipText", Local .getString("Details")); UIManager.put("FileChooser.fileNameLabelText", Local.getString( "File Name:")); UIManager.put("FileChooser.filesOfTypeLabelText", Local.getString( "Files of Type:")); UIManager.put("FileChooser.openButtonText", Local.getString("Open")); UIManager.put("FileChooser.openButtonToolTipText", Local.getString( "Open selected file")); UIManager .put("FileChooser.cancelButtonText", Local.getString("Cancel")); UIManager.put("FileChooser.cancelButtonToolTipText", Local.getString( "Cancel")); JFileChooser chooser = new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setDialogTitle(Local.getString("Choose an image file")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.addChoosableFileFilter( new net.sf.memoranda.ui.htmleditor.filechooser.ImageFilter()); chooser.setAccessory( new net.sf.memoranda.ui.htmleditor.filechooser.ImagePreview( chooser)); chooser.setPreferredSize(new Dimension(550, 375)); java.io.File lastSel = (java.io.File) Context.get( "LAST_SELECTED_IMG_FILE"); if (lastSel != null) chooser.setCurrentDirectory(lastSel); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { fileField.setText(chooser.getSelectedFile().toURI().toURL().toString()); header.setIcon(getPreviewIcon(chooser.getSelectedFile())); Context .put("LAST_SELECTED_IMG_FILE", chooser .getSelectedFile()); } catch (Exception ex) { fileField.setText(chooser.getSelectedFile().getPath()); } try { ImageIcon img = new ImageIcon(chooser.getSelectedFile() .getPath()); widthField.setText(new Integer(img.getIconWidth()).toString()); heightField .setText(new Integer(img.getIconHeight()).toString()); } catch (Exception ex) { ex.printStackTrace(); } } } }
jzalden/SER316-Karlsruhe
src/net/sf/memoranda/ui/htmleditor/ImageDialog.java
Java
gpl-2.0
13,558
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OUTDOOR_PVP_TF_ #define OUTDOOR_PVP_TF_ #include "OutdoorPvP.h" const uint8 OutdoorPvPTFBuffZonesNum = 5; const uint32 OutdoorPvPTFBuffZones[OutdoorPvPTFBuffZonesNum] = { 3519 /*Terokkar Forest*/, 3791 /*Sethekk Halls*/, 3789 /*Shadow Labyrinth*/, 3792 /*Mana-Tombs*/, 3790 /*Auchenai Crypts*/ }; // locked for 6 hours after capture const uint32 TF_LOCK_TIME = 3600 * 6 * 1000; // update lock timer every 1/4 minute (overkill, but this way it's sure the timer won't "jump" 2 minutes at once.) const uint32 TF_LOCK_TIME_UPDATE = 15000; // blessing of auchindoun #define TF_CAPTURE_BUFF 33377 const uint32 TF_ALLY_QUEST = 11505; const uint32 TF_HORDE_QUEST = 11506; enum OutdoorPvPTF_TowerType { TF_TOWER_NW = 0, TF_TOWER_N, TF_TOWER_NE, TF_TOWER_SE, TF_TOWER_S, TF_TOWER_NUM }; const go_type TFCapturePoints[TF_TOWER_NUM] = { {183104, 530, -3081.65f, 5335.03f, 17.1853f, -2.14675f, 0.0f, 0.0f, 0.878817f, -0.477159f}, {183411, 530, -2939.9f, 4788.73f, 18.987f, 2.77507f, 0.0f, 0.0f, 0.983255f, 0.182236f}, {183412, 530, -3174.94f, 4440.97f, 16.2281f, 1.86750f, 0.0f, 0.0f, 0.803857f, 0.594823f}, {183413, 530, -3603.31f, 4529.15f, 20.9077f, 0.994838f, 0.0f, 0.0f, 0.477159f, 0.878817f}, {183414, 530, -3812.37f, 4899.3f, 17.7249f, 0.087266f, 0.0f, 0.0f, 0.043619f, 0.999048f} }; struct tf_tower_world_state { uint32 n; uint32 h; uint32 a; }; const tf_tower_world_state TFTowerWorldStates[TF_TOWER_NUM] = { {0xa79, 0xa7a, 0xa7b}, {0xa7e, 0xa7d, 0xa7c}, {0xa82, 0xa81, 0xa80}, {0xa88, 0xa87, 0xa86}, {0xa85, 0xa84, 0xa83} }; const uint32 TFTowerPlayerEnterEvents[TF_TOWER_NUM] = { 12226, 12497, 12486, 12499, 12501 }; const uint32 TFTowerPlayerLeaveEvents[TF_TOWER_NUM] = { 12225, 12496, 12487, 12498, 12500 }; enum TFWorldStates { TF_UI_TOWER_SLIDER_POS = 0xa41, TF_UI_TOWER_SLIDER_N = 0xa40, TF_UI_TOWER_SLIDER_DISPLAY = 0xa3f, TF_UI_TOWER_COUNT_H = 0xa3e, TF_UI_TOWER_COUNT_A = 0xa3d, TF_UI_TOWERS_CONTROLLED_DISPLAY = 0xa3c, TF_UI_LOCKED_TIME_MINUTES_FIRST_DIGIT = 0x9d0, TF_UI_LOCKED_TIME_MINUTES_SECOND_DIGIT = 0x9ce, TF_UI_LOCKED_TIME_HOURS = 0x9cd, TF_UI_LOCKED_DISPLAY_NEUTRAL = 0x9cc, TF_UI_LOCKED_DISPLAY_HORDE = 0xad0, TF_UI_LOCKED_DISPLAY_ALLIANCE = 0xacf }; enum TFTowerStates { TF_TOWERSTATE_N = 1, TF_TOWERSTATE_H = 2, TF_TOWERSTATE_A = 4 }; class OPvPCapturePointTF : public OPvPCapturePoint { public: OPvPCapturePointTF(OutdoorPvP* pvp, OutdoorPvPTF_TowerType type); bool Update(uint32 diff); void ChangeState(); void SendChangePhase(); void FillInitialWorldStates(WorldPacket & data); // used when player is activated/inactivated in the area bool HandlePlayerEnter(Player* player); void HandlePlayerLeave(Player* player); void UpdateTowerState(); protected: OutdoorPvPTF_TowerType m_TowerType; uint32 m_TowerState; }; class OutdoorPvPTF : public OutdoorPvP { public: OutdoorPvPTF(); bool SetupOutdoorPvP(); void HandlePlayerEnterZone(Player* player, uint32 zone); void HandlePlayerLeaveZone(Player* player, uint32 zone); bool Update(uint32 diff); void FillInitialWorldStates(WorldPacket &data); void SendRemoveWorldStates(Player* player); uint32 GetAllianceTowersControlled() const; void SetAllianceTowersControlled(uint32 count); uint32 GetHordeTowersControlled() const; void SetHordeTowersControlled(uint32 count); bool IsLocked() const; private: bool m_IsLocked; uint32 m_LockTimer; uint32 m_LockTimerUpdate; uint32 m_AllianceTowersControlled; uint32 m_HordeTowersControlled; uint32 hours_left, second_digit, first_digit; }; #endif
Macavity/SkyFireEMU
src/server/scripts/OutdoorPvP/OutdoorPvPTF.h
C
gpl-2.0
4,669
/* * QEMU Audio subsystem header * * Copyright (c) 2003-2005 Vassili Karpov (malc) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef QEMU_AUDIO_H #define QEMU_AUDIO_H #include "qemu/queue.h" #include "qapi/qapi-types-audio.h" typedef void (*audio_callback_fn) (void *opaque, int avail); #ifdef HOST_WORDS_BIGENDIAN #define AUDIO_HOST_ENDIANNESS 1 #else #define AUDIO_HOST_ENDIANNESS 0 #endif typedef struct audsettings { int freq; int nchannels; AudioFormat fmt; int endianness; } audsettings; audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo); int audioformat_bytes_per_sample(AudioFormat fmt); int audio_buffer_frames(AudiodevPerDirectionOptions *pdo, audsettings *as, int def_usecs); int audio_buffer_samples(AudiodevPerDirectionOptions *pdo, audsettings *as, int def_usecs); int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo, audsettings *as, int def_usecs); typedef enum { AUD_CNOTIFY_ENABLE, AUD_CNOTIFY_DISABLE } audcnotification_e; struct audio_capture_ops { void (*notify) (void *opaque, audcnotification_e cmd); void (*capture) (void *opaque, void *buf, int size); void (*destroy) (void *opaque); }; struct capture_ops { void (*info) (void *opaque); void (*destroy) (void *opaque); }; typedef struct CaptureState { void *opaque; struct capture_ops ops; QLIST_ENTRY (CaptureState) entries; } CaptureState; typedef struct SWVoiceOut SWVoiceOut; typedef struct CaptureVoiceOut CaptureVoiceOut; typedef struct SWVoiceIn SWVoiceIn; typedef struct QEMUSoundCard { char *name; QLIST_ENTRY (QEMUSoundCard) entries; } QEMUSoundCard; typedef struct QEMUAudioTimeStamp { uint64_t old_ts; } QEMUAudioTimeStamp; void AUD_vlog (const char *cap, const char *fmt, va_list ap) GCC_FMT_ATTR(2, 0); void AUD_log (const char *cap, const char *fmt, ...) GCC_FMT_ATTR(2, 3); void AUD_register_card (const char *name, QEMUSoundCard *card); void AUD_remove_card (QEMUSoundCard *card); CaptureVoiceOut *AUD_add_capture ( struct audsettings *as, struct audio_capture_ops *ops, void *opaque ); void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque); SWVoiceOut *AUD_open_out ( QEMUSoundCard *card, SWVoiceOut *sw, const char *name, void *callback_opaque, audio_callback_fn callback_fn, struct audsettings *settings ); void AUD_close_out (QEMUSoundCard *card, SWVoiceOut *sw); int AUD_write (SWVoiceOut *sw, void *pcm_buf, int size); int AUD_get_buffer_size_out (SWVoiceOut *sw); void AUD_set_active_out (SWVoiceOut *sw, int on); int AUD_is_active_out (SWVoiceOut *sw); void AUD_init_time_stamp_out (SWVoiceOut *sw, QEMUAudioTimeStamp *ts); uint64_t AUD_get_elapsed_usec_out (SWVoiceOut *sw, QEMUAudioTimeStamp *ts); void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol); void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol); SWVoiceIn *AUD_open_in ( QEMUSoundCard *card, SWVoiceIn *sw, const char *name, void *callback_opaque, audio_callback_fn callback_fn, struct audsettings *settings ); void AUD_close_in (QEMUSoundCard *card, SWVoiceIn *sw); int AUD_read (SWVoiceIn *sw, void *pcm_buf, int size); void AUD_set_active_in (SWVoiceIn *sw, int on); int AUD_is_active_in (SWVoiceIn *sw); void AUD_init_time_stamp_in (SWVoiceIn *sw, QEMUAudioTimeStamp *ts); uint64_t AUD_get_elapsed_usec_in (SWVoiceIn *sw, QEMUAudioTimeStamp *ts); static inline void *advance (void *p, int incr) { uint8_t *d = p; return (d + incr); } #ifdef __GNUC__ #define audio_MIN(a, b) ( __extension__ ({ \ __typeof (a) ta = a; \ __typeof (b) tb = b; \ ((ta)>(tb)?(tb):(ta)); \ })) #define audio_MAX(a, b) ( __extension__ ({ \ __typeof (a) ta = a; \ __typeof (b) tb = b; \ ((ta)<(tb)?(tb):(ta)); \ })) #else #define audio_MIN(a, b) ((a)>(b)?(b):(a)) #define audio_MAX(a, b) ((a)<(b)?(b):(a)) #endif int wav_start_capture (CaptureState *s, const char *path, int freq, int bits, int nchannels); bool audio_is_cleaning_up(void); void audio_cleanup(void); void audio_sample_to_uint64(void *samples, int pos, uint64_t *left, uint64_t *right); void audio_sample_from_uint64(void *samples, int pos, uint64_t left, uint64_t right); void audio_parse_option(const char *opt); void audio_init_audiodevs(void); void audio_legacy_help(void); #endif /* QEMU_AUDIO_H */
Cisco-Talos/pyrebox
qemu/audio/audio.h
C
gpl-2.0
5,740
/* Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "party.hpp" #include "channel_server/channel_server.hpp" #include "channel_server/instance.hpp" #include "channel_server/map_packet.hpp" #include "channel_server/maps.hpp" #include "channel_server/party_packet.hpp" #include "channel_server/player.hpp" #include "channel_server/player_data_provider.hpp" #include "channel_server/player_packet.hpp" #include "channel_server/player_skills.hpp" #include "channel_server/world_server_packet.hpp" namespace vana { namespace channel_server { party::party(game_party_id party_id) : m_party_id{party_id} { } auto party::set_leader(game_player_id player_id, bool show_packet) -> void { m_leader_id = player_id; if (show_packet) { run_function([this, player_id](ref_ptr<player> player) { player->send(packets::party::set_leader(this, player_id)); }); } } namespace functors { struct join_party_update { auto operator()(ref_ptr<player> target) -> void { target->send(packets::party::join_party(target->get_map_id(), party, player)); } party *party; string player; }; } auto party::add_member(ref_ptr<player> player_value, bool first) -> void { m_members[player_value->get_id()] = player_value; player_value->set_party(this); show_hp_bar(player_value); receive_hp_bar(player_value); if (!first) { // This must be executed first in case the player has an open door already // The town position will need to change upon joining player_value->get_skills()->on_join_party(this, player_value); run_function([&](ref_ptr<player> party_member) { if (party_member != player_value) { party_member->get_skills()->on_join_party(this, player_value); } }); functors::join_party_update func = {this, player_value->get_name()}; run_function(func); } } auto party::add_member(game_player_id id, const string &name, bool first) -> void { m_members[id] = nullptr; if (!first) { functors::join_party_update func = {this, name}; run_function(func); } } auto party::set_member(game_player_id player_id, ref_ptr<player> player) -> void { m_members[player_id] = player; } namespace functors { struct leave_party_update { auto operator()(ref_ptr<player> target) -> void { target->send(packets::party::leave_party(target->get_map_id(), party, player_id, player, kicked)); } party *party; game_player_id player_id; string player; bool kicked; }; } auto party::delete_member(ref_ptr<player> player_value, bool kicked) -> void { player_value->get_skills()->on_leave_party(this, player_value, kicked); m_members.erase(player_value->get_id()); player_value->set_party(nullptr); if (instance *inst = get_instance()) { inst->remove_party_member(get_id(), player_value->get_id()); } run_function([&](ref_ptr<player> party_member) { if (party_member != player_value) { party_member->get_skills()->on_leave_party(this, player_value, kicked); } }); functors::leave_party_update func = {this, player_value->get_id(), player_value->get_name(), kicked}; func(player_value); run_function(func); } auto party::delete_member(game_player_id id, const string &name, bool kicked) -> void { if (instance *inst = get_instance()) { inst->remove_party_member(get_id(), id); } m_members.erase(id); functors::leave_party_update func = {this, id, name, kicked}; run_function(func); } auto party::disband() -> void { if (instance *inst = get_instance()) { inst->party_disband(get_id()); set_instance(nullptr); } run_function([&](ref_ptr<player> party_member) { party_member->get_skills()->on_party_disband(this); }); auto temp = m_members; for (const auto &kvp : temp) { if (auto player = kvp.second) { player->set_party(nullptr); player->send(packets::party::disband_party(this)); } m_members.erase(kvp.first); } } auto party::silent_update() -> void { run_function([this](ref_ptr<player> player) { player->send(packets::party::silent_update(player->get_map_id(), this)); }); } auto party::get_member_by_index(uint8_t one_based_index) -> ref_ptr<player> { ref_ptr<player> member = nullptr; if (one_based_index <= m_members.size()) { uint8_t f = 0; for (const auto &kvp : m_members) { f++; if (f == one_based_index) { member = kvp.second; break; } } } return member; } auto party::get_zero_based_index_by_member(ref_ptr<player> player) -> int8_t { int8_t index = 0; for (const auto &kvp : m_members) { if (kvp.second == player) { return index; } index++; } return -1; } auto party::run_function(function<void(ref_ptr<player>)> func) -> void { for (const auto &kvp : m_members) { if (auto player = kvp.second) { func(player); } } } auto party::get_all_player_ids() -> vector<game_player_id> { vector<game_player_id> player_ids; for (const auto &kvp : m_members) { player_ids.push_back(kvp.first); } return player_ids; } auto party::get_party_members(game_map_id map_id) -> vector<ref_ptr<player>> { vector<ref_ptr<player>> players; run_function([&players, &map_id](ref_ptr<player> player) { if (map_id == -1 || player->get_map_id() == map_id) { players.push_back(player); } }); return players; } auto party::show_hp_bar(ref_ptr<player> player_value) -> void { run_function([&player_value](ref_ptr<player> test_player) { if (test_player != player_value && test_player->get_map_id() == player_value->get_map_id()) { test_player->send(packets::player::show_hp_bar(player_value->get_id(), player_value->get_stats()->get_hp(), player_value->get_stats()->get_max_hp())); } }); } auto party::receive_hp_bar(ref_ptr<player> player_value) -> void { run_function([&player_value](ref_ptr<player> test_player) { if (test_player != player_value && test_player->get_map_id() == player_value->get_map_id()) { player_value->send(packets::player::show_hp_bar(test_player->get_id(), test_player->get_stats()->get_hp(), test_player->get_stats()->get_max_hp())); } }); } auto party::get_member_count_on_map(game_map_id map_id) -> int8_t { int8_t count = 0; for (const auto &kvp : m_members) { if (auto test = kvp.second) { if (test->get_map_id() == map_id) { count++; } } } return count; } auto party::is_within_level_range(game_player_level low_bound, game_player_level high_bound) -> bool { bool ret = true; for (const auto &kvp : m_members) { if (auto test = kvp.second) { if (test->get_stats()->get_level() < low_bound || test->get_stats()->get_level() > high_bound) { ret = false; break; } } } return ret; } auto party::warp_all_members(game_map_id map_id, const string &portal_name) -> void { if (map *destination = maps::get_map(map_id)) { const data::type::portal_info * const destination_portal = destination->query_portal_name(portal_name); run_function([&](ref_ptr<player> test) { test->set_map(map_id, destination_portal); }); } } auto party::check_footholds(int8_t member_count, const vector<vector<game_foothold_id>> &footholds) -> result { // Determines if the players are properly arranged (i.e. 5 people on 5 barrels in Kerning PQ) result winner = result::success; int8_t members_on_footholds = 0; hash_set<size_t> foothold_groups_used; for (size_t group = 0; group < footholds.size(); group++) { const auto &group_footholds = footholds[group]; for (const auto &kvp : m_members) { if (auto test = kvp.second) { for (const auto &foothold : group_footholds) { if (test->get_foothold() == foothold) { if (foothold_groups_used.find(group) != std::end(foothold_groups_used)) { winner = result::failure; } else { foothold_groups_used.insert(group); members_on_footholds++; } break; } } } if (winner == result::failure) { break; } } if (winner == result::failure) { break; } } if (winner == result::success && members_on_footholds != member_count) { // Not all the foothold groups were indexed winner = result::failure; } return winner; } auto party::verify_footholds(const vector<vector<game_foothold_id>> &footholds) -> result { // Determines if the players match your selected footholds result winner = result::success; hash_set<size_t> foothold_groups_used; for (size_t group = 0; group < footholds.size(); group++) { const auto &group_footholds = footholds[group]; for (const auto &kvp : m_members) { if (auto test = kvp.second) { for (const auto &foothold : group_footholds) { if (test->get_foothold() == foothold) { if (foothold_groups_used.find(group) != std::end(foothold_groups_used)) { winner = result::failure; } else { foothold_groups_used.insert(group); } break; } } if (winner == result::failure) { break; } } } if (winner == result::failure) { break; } } if (winner == result::success) { winner = foothold_groups_used.size() == footholds.size() ? result::success : result::failure; } return winner; } } }
diamondo25/Vana
src/channel_server/party.cpp
C++
gpl-2.0
9,610
/* * Copyright (C) 2013-2014 * Sebastian Schmitz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CHANNEL_H #define CHANNEL_H #include <eq/eq.h> #include "pipe.h" #include <OgreMatrix4.h> namespace vr{ /* * Channel */ class Channel : public eq::Channel { public: Channel(eq::Window *parent); protected: virtual bool configInit(const eq::uint128_t &init_id); virtual void frameDraw(const eq::uint128_t &frame_id); Ogre::Matrix4 calcViewMatrix( Ogre::Vector3 eye, Ogre::Vector3 target, Ogre::Vector3 up ) const; }; } #endif // CHANNEL_H
kepakiano/eqOgre
equalizer/headers/channel.h
C
gpl-2.0
1,239
<?php /** * @package angifw * @copyright Copyright (C) 2009-2013 Nicholas K. Dionysopoulos. All rights reserved. * @author Nicholas K. Dionysopoulos - http://www.dionysopoulos.me * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL v3 or later * * Akeeba Next Generation Installer Framework */ defined('_AKEEBA') or die(); class AModel { /** * Input variables, passed on from the controller, in an associative array * @var array */ protected $input = array(); /** * Should I save the model's state in the session? * @var bool */ protected $_savestate = true; /** * The model (base) name * * @var string */ protected $name; /** * The URL option for the component. * * @var string */ protected $option = null; /** * A state object * * @var string */ protected $state; /** * Are the state variables already set? * * @var bool */ protected $_state_set = false; /** * Returns a new model object. Unless overriden by the $config array, it will * try to automatically populate its state from the request variables. * * @param string $type * @param string $prefix * @param array $config * @return AModel */ public static function &getAnInstance( $type, $prefix = '', $config = array() ) { $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $modelClass = $prefix.ucfirst($type); $result = false; // Guess the component name and include path if (!empty($prefix)) { preg_match('/(.*)Model$/', $prefix, $m); $component = strtolower($m[1]); } else { $component = ''; } if (array_key_exists('input', $config)) { if (!($config['input'] instanceof AInput)) { if (!is_array($config['input'])) { $config['input'] = (array)$config['input']; } $config['input'] = array_merge($_REQUEST, $config['input']); $config['input'] = new AInput($config['input']); } } else { $config['input'] = new AInput(); } if (empty($component)) { $defaultApp = AApplication::getInstance()->getName(); $component = $config['input']->get('option', $defaultApp); } $config['option'] = $component; $needsAView = true; if(array_key_exists('view', $config)) { if (!empty($config['view'])) { $needsAView = false; } } if ($needsAView) { $config['view'] = strtolower($type); } $config['input']->set('option', $config['option']); $config['input']->set('view', $config['view']); // Try to load the requested model class if (!class_exists( $modelClass )) { $include_paths = array( APATH_INSTALLATION . '/' . $component . '/models', ); // Try to load the model file $path = AUtilsPath::find( $include_paths, self::createFileName( 'model', array( 'name' => $type)) ); if ($path) { require_once $path; } } // Fallback to the generic AModel model class if (!class_exists( $modelClass )) { $modelClass = 'AModel'; } $result = new $modelClass($config); return $result; } /** * Returns a new instance of a model, with the state reset to defaults * * @param string $type * @param string $prefix * @param array $config * * @return AModel */ public static function &getTmpInstance($type, $prefix = '', $config = array()) { $ret = self::getAnInstance($type, $prefix, $config) ->getClone() ->clearState() ->clearInput() ->savestate(0); return $ret; } /** * Public class constructor * * @param type $config */ public function __construct($config = array()) { // Get the input if (array_key_exists('input', $config)) { if($config['input'] instanceof AInput) { $this->input = $config['input']; } else { $this->input = new AInput($config['input']); } } else { $this->input = new AInput(); } // Set the $name variable $component = $this->input->getCmd('option','com_foobar'); if (array_key_exists('option', $config)) { $component = $config['option']; } $name = strtolower($component); if(array_key_exists('name', $config)) { $name = $config['name']; } $this->input->set('option', $component); $this->name = $name; $this->option = $component; // Get the view name $className = get_class($this); if ($className == 'AModel') { if (array_key_exists('view', $config)) { $view = $config['view']; } if (empty($view)) { $view = $this->input->getCmd('view', 'cpanel'); } } else { $eliminatePart = ucfirst($name).'Model'; $view = strtolower(str_replace($eliminatePart, '', $className)); } // Set the model state if (array_key_exists('state', $config)) { $this->state = $config['state']; } else { $this->state = new AObject; } // Set the internal state marker - used to ignore setting state from the request if (!empty($config['ignore_request'])) { $this->_state_set = true; } } /** * Create the filename for a resource * * @param string $type The resource type to create the filename for. * @param array $parts An associative array of filename information. * * @return string The filename */ protected static function createFileName($type, $parts = array()) { $filename = ''; switch ($type) { case 'model': $filename = strtolower($parts['name']) . '.php'; break; } return $filename; } /** * Method to get the model name * * The model name. By default parsed using the classname or it can be set * by passing a $config['name'] in the class constructor * * @return string The name of the model */ public function getName() { if (empty($this->name)) { $r = null; if (!preg_match('/Model(.*)/i', get_class($this), $r)) { JError::raiseError(500, AText::_('ANGI_APPLICATION_ERROR_MODEL_GET_NAME')); } $this->name = strtolower($r[1]); } return $this->name; } /** * Get a filtered state variable * @param string $key * @param mixed $default * @param string $filter_type * @return mixed */ public function getState($key = null, $default = null, $filter_type = 'raw') { if(empty($key)) { return $this->internal_getState(); } // Get the savestate status $value = $this->internal_getState($key); if(is_null($value)) { $value = $this->getUserStateFromRequest($key, $key, $value, 'none', $this->_savestate); if(is_null($value)) { return $default; } } if( strtoupper($filter_type) == 'RAW' ) { return $value; } else { $filter = new AFilterInput(); return $filter->clean($value, $filter_type); } } public function getHash() { static $hash = null; if(is_null($hash)) { $defaultApp = AApplication::getInstance()->getName(); $option = $this->input->getCmd('option', $defaultApp); $view = $this->input->getCmd('view', 'cpanel'); $hash = "$option.$view."; } return $hash; } /** * Gets the value of a user state variable. * * @access public * @param string The key of the user state variable. * @param string The name of the variable passed in a request. * @param string The default value for the variable if not found. Optional. * @param string Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional. * @param bool Should I save the variable in the user state? Default: true. Optional. * @return The request user state. */ protected function getUserStateFromRequest( $key, $request, $default = null, $type = 'none', $setUserState = true ) { $session = ASession::getInstance(); $hash = $this->getHash(); $old_state = $session->get($hash.$key, null); $cur_state = (!is_null($old_state)) ? $old_state : $default; $new_state = $this->input->get($request, null, $type); // Save the new value only if it was set in this request if($setUserState) { if ($new_state !== null) { $session->set($hash.$key, $new_state); } else { $new_state = $cur_state; } } elseif (is_null($new_state)) { $new_state = $cur_state; } return $new_state; } /** * Method to get model state variables * * @param string $property Optional parameter name * @param mixed $default Optional default value * * @return object The property where specified, the state object where omitted */ private function internal_getState($property = null, $default = null) { if (!$this->_state_set) { // Protected method to auto-populate the model state. $this->populateState(); // Set the model state set flag to true. $this->_state_set = true; } return $property === null ? $this->state : $this->state->get($property, $default); } /** * Method to auto-populate the model state. * * This method should only be called once per instantiation and is designed * to be called on the first call to the getState() method unless the model * configuration flag to ignore the request is set. * * @return void * * @note Calling getState in this method will result in recursion. */ protected function populateState() { } /** * Method to set model state variables * * @param string $property The name of the property. * @param mixed $value The value of the property to set or null. * * @return mixed The previous value of the property or null if not set. */ public function setState($property, $value = null) { return $this->state->set($property, $value); } /** * Clears the model state, but doesn't touch the internal lists of records, * record tables or record id variables. To clear these values, please use * reset(). * * @return AModel */ public function clearState() { $this->state = new AObject(); return $this; } /** * Clears the input array. * * @return AModel */ public function clearInput() { $this->input = new AInput(array()); return $this; } /** * Clones the model object and returns the clone * @return AModel */ public function &getClone() { $clone = clone($this); return $clone; } /** * Magic getter; allows to use the name of model state keys as properties * @param string $name * @return mixed */ public function __get($name) { return $this->getState($name); } /** * Magic setter; allows to use the name of model state keys as properties * @param string $name * @return mixed */ public function __set($name, $value) { return $this->setState($name, $value); } /** * Magic caller; allows to use the name of model state keys as methods to * set their values. * * @param string $name * @param mixed $arguments * @return AModel */ public function __call($name, $arguments) { $arg1 = array_shift($arguments); $this->setState($name, $arg1); return $this; } /** * Sets the model state auto-save status. By default the model is set up to * save its state to the session. * * @param bool $newState True to save the state, false to not save it. */ public function &savestate($newState) { $this->_savestate = $newState ? true : false; return $this; } public function populateSavesate() { if(is_null($this->_savestate)) { $savestate = $this->input->getInt('savestate', -999); if($savestate == -999) { $savestate = true; } $this->savestate($savestate); } } }
chr1x2/linux.org.ph
installation/framework/model/model.php
PHP
gpl-2.0
11,299
// SPDX-License-Identifier: GPL-2.0 #include "color.h" #include <QMap> #include <array> // Note that std::array<QColor, 2> is in every respect equivalent to QColor[2], // but allows assignment, comparison, can be returned from functions, etc. static QMap<color_index_t, std::array<QColor, 2>> profile_color = { { SAC_1, {{ FUNGREEN1, BLACK1_LOW_TRANS }} }, { SAC_2, {{ APPLE1, BLACK1_LOW_TRANS }} }, { SAC_3, {{ ATLANTIS1, BLACK1_LOW_TRANS }} }, { SAC_4, {{ ATLANTIS2, BLACK1_LOW_TRANS }} }, { SAC_5, {{ EARLSGREEN1, BLACK1_LOW_TRANS }} }, { SAC_6, {{ HOKEYPOKEY1, BLACK1_LOW_TRANS }} }, { SAC_7, {{ TUSCANY1, BLACK1_LOW_TRANS }} }, { SAC_8, {{ CINNABAR1, BLACK1_LOW_TRANS }} }, { SAC_9, {{ REDORANGE1, BLACK1_LOW_TRANS }} }, { VELO_STABLE, {{ CAMARONE1, BLACK1_LOW_TRANS }} }, { VELO_SLOW, {{ LIMENADE1, BLACK1_LOW_TRANS }} }, { VELO_MODERATE, {{ RIOGRANDE1, BLACK1_LOW_TRANS }} }, { VELO_FAST, {{ PIRATEGOLD1, BLACK1_LOW_TRANS }} }, { VELO_CRAZY, {{ RED1, BLACK1_LOW_TRANS }} }, { PO2, {{ APPLE1, BLACK1_LOW_TRANS }} }, { PO2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} }, { PN2, {{ BLACK1_LOW_TRANS, BLACK1_LOW_TRANS }} }, { PN2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} }, { PHE, {{ PEANUT, BLACK1_LOW_TRANS }} }, { PHE_ALERT, {{ RED1, BLACK1_LOW_TRANS }} }, { O2SETPOINT, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} }, { CCRSENSOR1, {{ TUNDORA1_MED_TRANS, BLACK1_LOW_TRANS }} }, { CCRSENSOR2, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} }, { CCRSENSOR3, {{ PEANUT, BLACK1_LOW_TRANS }} }, { SCR_OCPO2, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} }, { PP_LINES, {{ BLACK1_HIGH_TRANS, BLACK1_LOW_TRANS }} }, { TEXT_BACKGROUND, {{ CONCRETE1_LOWER_TRANS, WHITE1 }} }, { ALERT_BG, {{ BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS }} }, { ALERT_FG, {{ BLACK1_LOW_TRANS, WHITE1 }} }, { EVENTS, {{ REDORANGE1, BLACK1_LOW_TRANS }} }, { SAMPLE_DEEP, {{ QColor(Qt::red).darker(), BLACK1 }} }, { SAMPLE_SHALLOW, {{ QColor(Qt::red).lighter(), BLACK1_LOW_TRANS }} }, { SMOOTHED, {{ REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS }} }, { MINUTE, {{ MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS }} }, { TIME_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} }, { TIME_TEXT, {{ FORESTGREEN1, BLACK1 }} }, { DEPTH_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} }, { MEAN_DEPTH, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} }, { HR_PLOT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} }, { HR_TEXT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} }, { HR_AXIS, {{ MED_GRAY_HIGH_TRANS, MED_GRAY_HIGH_TRANS }} }, { DEPTH_BOTTOM, {{ GOVERNORBAY1_MED_TRANS, BLACK1_HIGH_TRANS }} }, { DEPTH_TOP, {{ MERCURY1_MED_TRANS, WHITE1_MED_TRANS }} }, { TEMP_TEXT, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} }, { TEMP_PLOT, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} }, { SAC_DEFAULT, {{ WHITE1, BLACK1_LOW_TRANS }} }, { BOUNDING_BOX, {{ WHITE1, BLACK1_LOW_TRANS }} }, { PRESSURE_TEXT, {{ KILLARNEY1, BLACK1_LOW_TRANS }} }, { BACKGROUND, {{ SPRINGWOOD1, WHITE1 }} }, { BACKGROUND_TRANS, {{ SPRINGWOOD1_MED_TRANS, WHITE1_MED_TRANS }} }, { CEILING_SHALLOW, {{ REDORANGE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} }, { CEILING_DEEP, {{ RED1_MED_TRANS, BLACK1_HIGH_TRANS }} }, { CALC_CEILING_SHALLOW, {{ FUNGREEN1_HIGH_TRANS, BLACK1_HIGH_TRANS }} }, { CALC_CEILING_DEEP, {{ APPLE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} }, { TISSUE_PERCENTAGE, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} }, { DURATION_LINE, {{ BLACK1, BLACK1_LOW_TRANS }} } }; QColor getColor(const color_index_t i, bool isGrayscale) { if (profile_color.count() > i && i >= 0) return profile_color[i][isGrayscale ? 1 : 0]; return QColor(Qt::black); } QColor getSacColor(int sac, int avg_sac) { int sac_index = 0; int delta = sac - avg_sac + 7000; sac_index = delta / 2000; if (sac_index < 0) sac_index = 0; if (sac_index > SAC_COLORS - 1) sac_index = SAC_COLORS - 1; return getColor((color_index_t)(SAC_COLORS_START_IDX + sac_index), false); } QColor getPressureColor(double density) { QColor color; int h = ((int) (180.0 - 180.0 * density / 8.0)); while (h < 0) h += 360; color.setHsv(h , 255, 255); return color; }
janmulder/subsurface
core/color.cpp
C++
gpl-2.0
4,063
/* Operating system support for run-time dynamic linker. Hurd version. Copyright (C) 1995-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* In the static library, this is all handled by dl-support.c or by the vanilla definitions in the rest of the C library. */ #ifdef SHARED #include <hurd.h> #include <link.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <sys/mman.h> #include <ldsodefs.h> #include <sys/wait.h> #include <assert.h> #include <sysdep.h> #include <mach/mig_support.h> #include "hurdstartup.h" #include <hurd/lookup.h> #include <hurd/auth.h> #include <hurd/term.h> #include <stdarg.h> #include <ctype.h> #include <sys/stat.h> #include <sys/uio.h> #include <entry.h> #include <dl-machine.h> #include <dl-procinfo.h> extern void __mach_init (void); extern int _dl_argc; extern char **_dl_argv; extern char **_environ; int __libc_enable_secure = 0; INTVARDEF(__libc_enable_secure) int __libc_multiple_libcs = 0; /* Defining this here avoids the inclusion of init-first. */ /* This variable contains the lowest stack address ever used. */ void *__libc_stack_end; #if HP_TIMING_AVAIL hp_timing_t _dl_cpuclock_offset; #endif /* TODO: this is never properly initialized in here. */ void *_dl_random attribute_relro = NULL; struct hurd_startup_data *_dl_hurd_data; #define FMH defined(__i386__) #if ! FMH # define fmh() ((void)0) # define unfmh() ((void)0) #else /* XXX loser kludge for vm_map kernel bug */ #undef ELF_MACHINE_USER_ADDRESS_MASK #define ELF_MACHINE_USER_ADDRESS_MASK 0 static vm_address_t fmha; static vm_size_t fmhs; static void unfmh(void){ __vm_deallocate(__mach_task_self(),fmha,fmhs);} static void fmh(void) { error_t err;int x;mach_port_t p; vm_address_t a=0x08000000U,max=VM_MAX_ADDRESS; while (!(err=__vm_region(__mach_task_self(),&a,&fmhs,&x,&x,&x,&x,&p,&x))){ __mach_port_deallocate(__mach_task_self(),p); if (a+fmhs>=0x80000000U){ max=a; break;} fmha=a+=fmhs;} if (err) assert(err==KERN_NO_SPACE); if (!fmha) fmhs=0; else while (1) { fmhs=max-fmha; if (fmhs == 0) break; err = __vm_map (__mach_task_self (), &fmha, fmhs, 0, 0, MACH_PORT_NULL, 0, 1, VM_PROT_NONE, VM_PROT_NONE, VM_INHERIT_COPY); if (!err) break; if (err != KERN_INVALID_ADDRESS && err != KERN_NO_SPACE) assert_perror(err); vm_address_t new_max = (max - 1) & 0xf0000000U; if (new_max >= max) { fmhs = 0; fmha = 0; break; } max = new_max; } } /* XXX loser kludge for vm_map kernel bug */ #endif ElfW(Addr) _dl_sysdep_start (void **start_argptr, void (*dl_main) (const ElfW(Phdr) *phdr, ElfW(Word) phent, ElfW(Addr) *user_entry, ElfW(auxv_t) *auxv)) { void go (intptr_t *argdata) { char **p; /* Cache the information in various global variables. */ _dl_argc = *argdata; _dl_argv = 1 + (char **) argdata; _environ = &_dl_argv[_dl_argc + 1]; for (p = _environ; *p++;); /* Skip environ pointers and terminator. */ if ((void *) p == _dl_argv[0]) { static struct hurd_startup_data nodata; _dl_hurd_data = &nodata; nodata.user_entry = (vm_address_t) ENTRY_POINT; } else _dl_hurd_data = (void *) p; INTUSE(__libc_enable_secure) = _dl_hurd_data->flags & EXEC_SECURE; if (_dl_hurd_data->flags & EXEC_STACK_ARGS && _dl_hurd_data->user_entry == 0) _dl_hurd_data->user_entry = (vm_address_t) ENTRY_POINT; unfmh(); /* XXX */ #if 0 /* XXX make this work for real someday... */ if (_dl_hurd_data->user_entry == (vm_address_t) ENTRY_POINT) /* We were invoked as a command, not as the program interpreter. The generic ld.so code supports this: it will parse the args as "ld.so PROGRAM [ARGS...]". For booting the Hurd, we support an additional special syntax: ld.so [-LIBS...] PROGRAM [ARGS...] Each LIBS word consists of "FILENAME=MEMOBJ"; for example "-/lib/libc.so=123" says that the contents of /lib/libc.so are found in a memory object whose port name in our task is 123. */ while (_dl_argc > 2 && _dl_argv[1][0] == '-' && _dl_argv[1][1] != '-') { char *lastslash, *memobjname, *p; struct link_map *l; mach_port_t memobj; error_t err; ++_dl_skip_args; --_dl_argc; p = _dl_argv++[1] + 1; memobjname = strchr (p, '='); if (! memobjname) _dl_sysdep_fatal ("Bogus library spec: ", p, "\n", NULL); *memobjname++ = '\0'; memobj = 0; while (*memobjname != '\0') memobj = (memobj * 10) + (*memobjname++ - '0'); /* Add a user reference on the memory object port, so we will still have one after _dl_map_object_from_fd calls our `close'. */ err = __mach_port_mod_refs (__mach_task_self (), memobj, MACH_PORT_RIGHT_SEND, +1); assert_perror (err); lastslash = strrchr (p, '/'); l = _dl_map_object_from_fd (lastslash ? lastslash + 1 : p, memobj, strdup (p), 0); /* Squirrel away the memory object port where it can be retrieved by the program later. */ l->l_info[DT_NULL] = (void *) memobj; } #endif /* Call elf/rtld.c's main program. It will set everything up and leave us to transfer control to USER_ENTRY. */ (*dl_main) ((const ElfW(Phdr) *) _dl_hurd_data->phdr, _dl_hurd_data->phdrsz / sizeof (ElfW(Phdr)), &_dl_hurd_data->user_entry, NULL); /* The call above might screw a few things up. First of all, if _dl_skip_args is nonzero, we are ignoring the first few arguments. However, if we have no Hurd startup data, it is the magical convention that ARGV[0] == P. The startup code in init-first.c will get confused if this is not the case, so we must rearrange things to make it so. We'll overwrite the origional ARGV[0] at P with ARGV[_dl_skip_args]. Secondly, if we need to be secure, it removes some dangerous environment variables. If we have no Hurd startup date this changes P (since that's the location after the terminating NULL in the list of environment variables). We do the same thing as in the first case but make sure we recalculate P. If we do have Hurd startup data, we have to move the data such that it starts just after the terminating NULL in the environment list. We use memmove, since the locations might overlap. */ if (INTUSE(__libc_enable_secure) || _dl_skip_args) { char **newp; for (newp = _environ; *newp++;); if (_dl_argv[-_dl_skip_args] == (char *) p) { if ((char *) newp != _dl_argv[0]) { assert ((char *) newp < _dl_argv[0]); _dl_argv[0] = memmove ((char *) newp, _dl_argv[0], strlen (_dl_argv[0]) + 1); } } else { if ((void *) newp != _dl_hurd_data) memmove (newp, _dl_hurd_data, sizeof (*_dl_hurd_data)); } } { extern void _dl_start_user (void); /* Unwind the stack to ARGDATA and simulate a return from _dl_start to the RTLD_START code which will run the user's entry point. */ RETURN_TO (argdata, &_dl_start_user, _dl_hurd_data->user_entry); } } /* Set up so we can do RPCs. */ __mach_init (); /* Initialize frequently used global variable. */ GLRO(dl_pagesize) = __getpagesize (); #if HP_TIMING_AVAIL HP_TIMING_NOW (_dl_cpuclock_offset); #endif fmh(); /* XXX */ /* See hurd/hurdstartup.c; this deals with getting information from the exec server and slicing up the arguments. Then it will call `go', above. */ _hurd_startup (start_argptr, &go); LOSE; abort (); } void internal_function _dl_sysdep_start_cleanup (void) { /* Deallocate the reply port and task port rights acquired by __mach_init. We are done with them now, and the user will reacquire them for himself when he wants them. */ __mig_dealloc_reply_port (MACH_PORT_NULL); __mach_port_deallocate (__mach_task_self (), __mach_task_self_); } /* Minimal open/close/mmap implementation sufficient for initial loading of shared libraries. These are weak definitions so that when the dynamic linker re-relocates itself to be user-visible (for -ldl), it will get the user's definition (i.e. usually libc's). */ /* Open FILE_NAME and return a Hurd I/O for it in *PORT, or return an error. If STAT is non-zero, stat the file into that stat buffer. */ static error_t open_file (const char *file_name, int flags, mach_port_t *port, struct stat64 *stat) { enum retry_type doretry; char retryname[1024]; /* XXX string_t LOSES! */ file_t startdir; error_t err; error_t use_init_port (int which, error_t (*operate) (file_t)) { return (which < _dl_hurd_data->portarraysize ? ((*operate) (_dl_hurd_data->portarray[which])) : EGRATUITOUS); } file_t get_dtable_port (int fd) { if ((unsigned int) fd < _dl_hurd_data->dtablesize && _dl_hurd_data->dtable[fd] != MACH_PORT_NULL) { __mach_port_mod_refs (__mach_task_self (), _dl_hurd_data->dtable[fd], MACH_PORT_RIGHT_SEND, +1); return _dl_hurd_data->dtable[fd]; } errno = EBADF; return MACH_PORT_NULL; } assert (!(flags & ~(O_READ | O_CLOEXEC))); startdir = _dl_hurd_data->portarray[file_name[0] == '/' ? INIT_PORT_CRDIR : INIT_PORT_CWDIR]; while (file_name[0] == '/') file_name++; err = __dir_lookup (startdir, (char *)file_name, O_RDONLY, 0, &doretry, retryname, port); if (!err) err = __hurd_file_name_lookup_retry (use_init_port, get_dtable_port, __dir_lookup, doretry, retryname, O_RDONLY, 0, port); if (!err && stat) { err = __io_stat (*port, stat); if (err) __mach_port_deallocate (__mach_task_self (), *port); } return err; } int weak_function __open (const char *file_name, int mode, ...) { mach_port_t port; error_t err = open_file (file_name, mode, &port, 0); if (err) return __hurd_fail (err); else return (int)port; } int weak_function __close (int fd) { if (fd != (int) MACH_PORT_NULL) __mach_port_deallocate (__mach_task_self (), (mach_port_t) fd); return 0; } __ssize_t weak_function __libc_read (int fd, void *buf, size_t nbytes) { error_t err; char *data; mach_msg_type_number_t nread; data = buf; nread = nbytes; err = __io_read ((mach_port_t) fd, &data, &nread, -1, nbytes); if (err) return __hurd_fail (err); if (data != buf) { memcpy (buf, data, nread); __vm_deallocate (__mach_task_self (), (vm_address_t) data, nread); } return nread; } libc_hidden_weak (__libc_read) __ssize_t weak_function __libc_write (int fd, const void *buf, size_t nbytes) { error_t err; mach_msg_type_number_t nwrote; assert (fd < _hurd_init_dtablesize); err = __io_write (_hurd_init_dtable[fd], buf, nbytes, -1, &nwrote); if (err) return __hurd_fail (err); return nwrote; } libc_hidden_weak (__libc_write) /* This is only used for printing messages (see dl-misc.c). */ __ssize_t weak_function __writev (int fd, const struct iovec *iov, int niov) { if (fd >= _hurd_init_dtablesize) { errno = EBADF; return -1; } int i; size_t total = 0; for (i = 0; i < niov; ++i) total += iov[i].iov_len; if (total != 0) { char buf[total], *bufp = buf; error_t err; mach_msg_type_number_t nwrote; for (i = 0; i < niov; ++i) bufp = (memcpy (bufp, iov[i].iov_base, iov[i].iov_len) + iov[i].iov_len); err = __io_write (_hurd_init_dtable[fd], buf, total, -1, &nwrote); if (err) return __hurd_fail (err); return nwrote; } return 0; } off64_t weak_function __libc_lseek64 (int fd, off64_t offset, int whence) { error_t err; err = __io_seek ((mach_port_t) fd, offset, whence, &offset); if (err) return __hurd_fail (err); return offset; } __ptr_t weak_function __mmap (__ptr_t addr, size_t len, int prot, int flags, int fd, off_t offset) { error_t err; vm_prot_t vmprot; vm_address_t mapaddr; mach_port_t memobj_rd, memobj_wr; vmprot = VM_PROT_NONE; if (prot & PROT_READ) vmprot |= VM_PROT_READ; if (prot & PROT_WRITE) vmprot |= VM_PROT_WRITE; if (prot & PROT_EXEC) vmprot |= VM_PROT_EXECUTE; if (flags & MAP_ANON) memobj_rd = MACH_PORT_NULL; else { assert (!(flags & MAP_SHARED)); err = __io_map ((mach_port_t) fd, &memobj_rd, &memobj_wr); if (err) return __hurd_fail (err), MAP_FAILED; __mach_port_deallocate (__mach_task_self (), memobj_wr); } mapaddr = (vm_address_t) addr; err = __vm_map (__mach_task_self (), &mapaddr, (vm_size_t) len, ELF_MACHINE_USER_ADDRESS_MASK, !(flags & MAP_FIXED), memobj_rd, (vm_offset_t) offset, flags & (MAP_COPY|MAP_PRIVATE), vmprot, VM_PROT_ALL, (flags & MAP_SHARED) ? VM_INHERIT_SHARE : VM_INHERIT_COPY); if (err == KERN_NO_SPACE && (flags & MAP_FIXED)) { /* XXX this is not atomic as it is in unix! */ /* The region is already allocated; deallocate it first. */ err = __vm_deallocate (__mach_task_self (), mapaddr, len); if (! err) err = __vm_map (__mach_task_self (), &mapaddr, (vm_size_t) len, ELF_MACHINE_USER_ADDRESS_MASK, !(flags & MAP_FIXED), memobj_rd, (vm_offset_t) offset, flags & (MAP_COPY|MAP_PRIVATE), vmprot, VM_PROT_ALL, (flags & MAP_SHARED) ? VM_INHERIT_SHARE : VM_INHERIT_COPY); } if ((flags & MAP_ANON) == 0) __mach_port_deallocate (__mach_task_self (), memobj_rd); if (err) return __hurd_fail (err), MAP_FAILED; return (__ptr_t) mapaddr; } int weak_function __fxstat64 (int vers, int fd, struct stat64 *buf) { error_t err; assert (vers == _STAT_VER); err = __io_stat ((mach_port_t) fd, buf); if (err) return __hurd_fail (err); return 0; } libc_hidden_def (__fxstat64) int weak_function __xstat64 (int vers, const char *file, struct stat64 *buf) { error_t err; mach_port_t port; assert (vers == _STAT_VER); err = open_file (file, 0, &port, buf); if (err) return __hurd_fail (err); __mach_port_deallocate (__mach_task_self (), port); return 0; } libc_hidden_def (__xstat64) /* This function is called by the dynamic linker (rtld.c) to check whether debugging malloc is allowed even for SUID binaries. This stub will always fail, which means that malloc-debugging is always disabled for SUID binaries. */ int weak_function __access (const char *file, int type) { errno = ENOSYS; return -1; } pid_t weak_function __getpid (void) { pid_t pid, ppid; int orphaned; if (__proc_getpids (_dl_hurd_data->portarray[INIT_PORT_PROC], &pid, &ppid, &orphaned)) return -1; return pid; } /* This is called only in some strange cases trying to guess a value for $ORIGIN for the executable. The dynamic linker copes with getcwd failing (dl-object.c), and it's too much hassle to include the functionality here. (We could, it just requires duplicating or reusing getcwd.c's code but using our special lookup function as in `open', above.) */ char * weak_function __getcwd (char *buf, size_t size) { errno = ENOSYS; return NULL; } void weak_function attribute_hidden _exit (int status) { __proc_mark_exit (_dl_hurd_data->portarray[INIT_PORT_PROC], W_EXITCODE (status, 0), 0); while (__task_terminate (__mach_task_self ())) __mach_task_self_ = (__mach_task_self) (); } /* We need this alias to satisfy references from libc_pic.a objects that were affected by the libc_hidden_proto declaration for _exit. */ strong_alias (_exit, __GI__exit) /* Try to get a machine dependent instruction which will make the program crash. This is used in case everything else fails. */ #include <abort-instr.h> #ifndef ABORT_INSTRUCTION /* No such instruction is available. */ # define ABORT_INSTRUCTION #endif void weak_function abort (void) { /* Try to abort using the system specific command. */ ABORT_INSTRUCTION; /* If the abort instruction failed, exit. */ _exit (127); /* If even this fails, make sure we never return. */ while (1) /* Try for ever and ever. */ ABORT_INSTRUCTION; } /* We need this alias to satisfy references from libc_pic.a objects that were affected by the libc_hidden_proto declaration for abort. */ strong_alias (abort, __GI_abort) /* This function is called by interruptible RPC stubs. For initial dynamic linking, just use the normal mach_msg. Since this defn is weak, the real defn in libc.so will override it if we are linked into the user program (-ldl). */ error_t weak_function _hurd_intr_rpc_mach_msg (mach_msg_header_t *msg, mach_msg_option_t option, mach_msg_size_t send_size, mach_msg_size_t rcv_size, mach_port_t rcv_name, mach_msg_timeout_t timeout, mach_port_t notify) { return __mach_msg (msg, option, send_size, rcv_size, rcv_name, timeout, notify); } void internal_function _dl_show_auxv (void) { /* There is nothing to print. Hurd has no auxiliary vector. */ } void weak_function _dl_init_first (int argc, ...) { /* This no-op definition only gets used if libc is not linked in. */ } #endif /* SHARED */
Phant0mas/glibc-hurd
sysdeps/mach/hurd/dl-sysdep.c
C
gpl-2.0
17,842
/*************************************************************************** * (C) Copyright 2003-2015 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.actions.chat; import static org.junit.Assert.assertEquals; import games.stendhal.server.entity.player.Player; import marauroa.common.game.RPAction; import org.junit.Test; import utilities.PlayerTestHelper; public class AwayActionTest { /** * Tests for playerIsNull. */ @Test(expected = NullPointerException.class) public void testPlayerIsNull() { final RPAction action = new RPAction(); action.put("type", "away"); final AwayAction aa = new AwayAction(); aa.onAction(null, action); } /** * Tests for onAction. */ @Test public void testOnAction() { final Player bob = PlayerTestHelper.createPlayer("bob"); final RPAction action = new RPAction(); action.put("type", "away"); final AwayAction aa = new AwayAction(); aa.onAction(bob, action); assertEquals(null, bob.getAwayMessage()); action.put("message", "bla"); aa.onAction(bob, action); assertEquals("\"bla\"", bob.getAwayMessage()); } /** * Tests for onInvalidAction. */ @Test public void testOnInvalidAction() { final Player bob = PlayerTestHelper.createPlayer("bob"); bob.clearEvents(); final RPAction action = new RPAction(); action.put("type", "bla"); action.put("message", "bla"); final AwayAction aa = new AwayAction(); aa.onAction(bob, action); assertEquals(null, bob.getAwayMessage()); } }
acsid/stendhal
tests/games/stendhal/server/actions/chat/AwayActionTest.java
Java
gpl-2.0
2,201
# Mustang Lite * **Theme URI:** http://www.webmandesign.eu/mustang-lite/ * **Author:** WebMan * **Author URI:** http://www.webmandesign.eu/ * **License:** GNU General Public License v3 * **License URI:** http://www.gnu.org/licenses/gpl-3.0.html ## Description Mustang Lite WordPress Theme lets you create beautiful, professional responsive and HiDPI (Retina) ready websites. With this theme you can create also a single one-page websites with ease! Mustang Lite is suitable for creative portfolio, business and corporate website projects, personal presentations and much more. You can set a custom design with background images and colors for every section of the theme. As the theme is translation ready and supports right-to-left languages as well, you can localize it for your multilingual website. By default you get the basic blog design which can be extended to full power of the theme with WebMan Amplifier plugin activation. This theme is a free, lite version of premium Mustang Multipurpose WordPress Theme by WebMan. The differences from paid version can be found at http://www.webmandesign.eu/mustan-lite/. Check out themes by WebMan at www.webmandesign.eu. Thank you for using one of WebMan's themes! Follow WebMan on Twitter [https://twitter.com/webmandesigneu] or become a fan on Facebook [https://www.facebook.com/webmandesigneu]. Full theme demo website at [http://themedemos.webmandesign.eu/mustang/]. Theme user manual with demo data at [http://www.webmandesign.eu/manual/mustang/]. ## Demo http://themedemos.webmandesign.eu/mustang/ ## Changelog *See the `changelog.md` file.* ## Documentation User manual available at http://www.webmandesign.eu/manual/mustang/ ## Copyright **Mustang Lite WordPress Theme** Copyright 2014 WebMan [http://www.webmandesign.eu/] Distributed under the terms of the GNU GPL **Animate.css** Copyright (c) 2014 Daniel Eden Licensed under the MIT license - http://opensource.org/licenses/MIT http://daneden.me/animate **Normalize.css** Copyright (c) Nicolas Gallagher and Jonathan Neal Licensed under the MIT license - http://opensource.org/licenses/MIT git.io/normalize **imagesLoaded** Copyright (c) 2014 Tomas Sardyha (@Darsain) and David DeSandro (@desandro) Licensed under the MIT license - http://opensource.org/licenses/MIT https://github.com/desandro/imagesloaded **jquery.appear.js** Copyright (c) 2012 Andrey Sidorov Licensed under MIT https://github.com/morr/jquery.appear/ **jquery.prettyPhoto.js** Copyright, Stephane Caron Licensed under Creative Commons 2.5 [http://creativecommons.org/licenses/by/2.5/] or GPLV2 license [http://www.gnu.org/licenses/gpl-2.0.html] Please see assets/js/prettyphoto/README file for more info. http://www.no-margin-for-errors.com **jquery.viewport.js** Copyright (c) 2008-2009 Mika Tuupola Licensed under the MIT license http://www.appelsiini.net/projects/viewport **Fontello font icons** Please see assets/font/basic-icons/LICENCE.txt file for more info.
KJaddoe/CSCMRA-Project
wp-content/themes/mustang-lite/readme.md
Markdown
gpl-2.0
2,966
/* SPDX-License-Identifier: GPL-2.0+ */ /* * Configuation settings for the Renesas Technology R0P7785LC0011RL board * * Copyright (C) 2008 Yoshihiro Shimoda <[email protected]> */ #ifndef __SH7785LCR_H #define __SH7785LCR_H #define CONFIG_CPU_SH7785 1 #define CONFIG_EXTRA_ENV_SETTINGS \ "bootdevice=0:1\0" \ "usbload=usb reset;usbboot;usb stop;bootm\0" #define CONFIG_DISPLAY_BOARDINFO #undef CONFIG_SHOW_BOOT_PROGRESS /* MEMORY */ #if defined(CONFIG_SH_32BIT) /* 0x40000000 - 0x47FFFFFF does not use */ #define CONFIG_SH_SDRAM_OFFSET (0x8000000) #define SH7785LCR_SDRAM_PHYS_BASE (0x40000000 + CONFIG_SH_SDRAM_OFFSET) #define SH7785LCR_SDRAM_BASE (0x80000000 + CONFIG_SH_SDRAM_OFFSET) #define SH7785LCR_SDRAM_SIZE (384 * 1024 * 1024) #define SH7785LCR_FLASH_BASE_1 (0xa0000000) #define SH7785LCR_FLASH_BANK_SIZE (64 * 1024 * 1024) #define SH7785LCR_USB_BASE (0xa6000000) #else #define SH7785LCR_SDRAM_BASE (0x08000000) #define SH7785LCR_SDRAM_SIZE (128 * 1024 * 1024) #define SH7785LCR_FLASH_BASE_1 (0xa0000000) #define SH7785LCR_FLASH_BANK_SIZE (64 * 1024 * 1024) #define SH7785LCR_USB_BASE (0xb4000000) #endif #define CONFIG_SYS_PBSIZE 256 #define CONFIG_SYS_BAUDRATE_TABLE { 115200 } /* SCIF */ #define CONFIG_CONS_SCIF1 1 #define CONFIG_SCIF_EXT_CLOCK 1 #define CONFIG_SYS_MEMTEST_START (SH7785LCR_SDRAM_BASE) #define CONFIG_SYS_MEMTEST_END (CONFIG_SYS_MEMTEST_START + \ (SH7785LCR_SDRAM_SIZE) - \ 4 * 1024 * 1024) #undef CONFIG_SYS_MEMTEST_SCRATCH #undef CONFIG_SYS_LOADS_BAUD_CHANGE #define CONFIG_SYS_SDRAM_BASE (SH7785LCR_SDRAM_BASE) #define CONFIG_SYS_SDRAM_SIZE (SH7785LCR_SDRAM_SIZE) #define CONFIG_SYS_LOAD_ADDR (CONFIG_SYS_SDRAM_BASE + 16 * 1024 * 1024) #define CONFIG_SYS_MONITOR_BASE (SH7785LCR_FLASH_BASE_1) #define CONFIG_SYS_MONITOR_LEN (512 * 1024) #define CONFIG_SYS_MALLOC_LEN (512 * 1024) #define CONFIG_SYS_BOOTMAPSZ (8 * 1024 * 1024) /* FLASH */ #define CONFIG_FLASH_CFI_DRIVER #define CONFIG_SYS_FLASH_CFI #undef CONFIG_SYS_FLASH_QUIET_TEST #define CONFIG_SYS_FLASH_EMPTY_INFO #define CONFIG_SYS_FLASH_BASE (SH7785LCR_FLASH_BASE_1) #define CONFIG_SYS_MAX_FLASH_SECT 512 #define CONFIG_SYS_MAX_FLASH_BANKS 1 #define CONFIG_SYS_FLASH_BANKS_LIST { CONFIG_SYS_FLASH_BASE + \ (0 * SH7785LCR_FLASH_BANK_SIZE) } #define CONFIG_SYS_FLASH_ERASE_TOUT (3 * 1000) #define CONFIG_SYS_FLASH_WRITE_TOUT (3 * 1000) #define CONFIG_SYS_FLASH_LOCK_TOUT (3 * 1000) #define CONFIG_SYS_FLASH_UNLOCK_TOUT (3 * 1000) #undef CONFIG_SYS_FLASH_PROTECTION #undef CONFIG_SYS_DIRECT_FLASH_TFTP /* R8A66597 */ #define CONFIG_USB_R8A66597_HCD #define CONFIG_R8A66597_BASE_ADDR SH7785LCR_USB_BASE #define CONFIG_R8A66597_XTAL 0x0000 /* 12MHz */ #define CONFIG_R8A66597_LDRV 0x8000 /* 3.3V */ #define CONFIG_R8A66597_ENDIAN 0x0000 /* little */ /* PCI Controller */ #define CONFIG_SH4_PCI #define CONFIG_SH7780_PCI #if defined(CONFIG_SH_32BIT) #define CONFIG_SH7780_PCI_LSR 0x1ff00001 #define CONFIG_SH7780_PCI_LAR 0x5f000000 #define CONFIG_SH7780_PCI_BAR 0x5f000000 #else #define CONFIG_SH7780_PCI_LSR 0x07f00001 #define CONFIG_SH7780_PCI_LAR CONFIG_SYS_SDRAM_SIZE #define CONFIG_SH7780_PCI_BAR CONFIG_SYS_SDRAM_SIZE #endif #define CONFIG_PCI_SCAN_SHOW 1 #define CONFIG_PCI_MEM_BUS 0xFD000000 /* Memory space base addr */ #define CONFIG_PCI_MEM_PHYS CONFIG_PCI_MEM_BUS #define CONFIG_PCI_MEM_SIZE 0x01000000 /* Size of Memory window */ #define CONFIG_PCI_IO_BUS 0xFE200000 /* IO space base address */ #define CONFIG_PCI_IO_PHYS CONFIG_PCI_IO_BUS #define CONFIG_PCI_IO_SIZE 0x00200000 /* Size of IO window */ #if defined(CONFIG_SH_32BIT) #define CONFIG_PCI_SYS_PHYS SH7785LCR_SDRAM_PHYS_BASE #else #define CONFIG_PCI_SYS_PHYS CONFIG_SYS_SDRAM_BASE #endif #define CONFIG_PCI_SYS_BUS CONFIG_SYS_SDRAM_BASE #define CONFIG_PCI_SYS_SIZE CONFIG_SYS_SDRAM_SIZE /* ENV setting */ #define CONFIG_ENV_OVERWRITE 1 #define CONFIG_ENV_SECT_SIZE (256 * 1024) #define CONFIG_ENV_SIZE (CONFIG_ENV_SECT_SIZE) #define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE + CONFIG_SYS_MONITOR_LEN) #define CONFIG_ENV_OFFSET (CONFIG_ENV_ADDR - CONFIG_SYS_FLASH_BASE) #define CONFIG_ENV_SIZE_REDUND (CONFIG_ENV_SECT_SIZE) /* Board Clock */ /* The SCIF used external clock. system clock only used timer. */ #define CONFIG_SYS_CLK_FREQ 50000000 #define CONFIG_SH_TMU_CLK_FREQ CONFIG_SYS_CLK_FREQ #define CONFIG_SH_SCIF_CLK_FREQ CONFIG_SYS_CLK_FREQ #define CONFIG_SYS_TMU_CLK_DIV 4 #endif /* __SH7785LCR_H */
ev3dev/u-boot
include/configs/sh7785lcr.h
C
gpl-2.0
4,450
//============================================================================= // MuseScore // Music Composition & Notation // $Id: keyfinder.h 4515 2011-07-13 09:56:53Z wschweer $ // // Copyright (C) 2002-2011 Werner Schweer // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation and appearing in // the file LICENCE.GPL //============================================================================= #ifndef __KEYFINDER_H__ #define __KEYFINDER_H__ class MidiTrack; namespace AL { class TimeSigMap; }; // extern int findKey(MidiTrack*, AL::TimeSigMap*); #endif
wschweer/mscoreserver
libmscore/keyfinder.h
C
gpl-2.0
722
select#newfesti_docs_versions_parent, label[for='parent'], select#parent.postform { display: none; } body table.wp-list-table.tags { table-layout: auto; } .festi-user-role-prices .festi-user-role-prices-section { margin: 0; } .festi-user-role-prices-message#message { margin-left:0; } .festi-user-role-prices .festi-user-role-prices-form-table { width: 100%; } .festi-user-role-prices-form-table tr.festi-user-role-prices-top-border td, .festi-user-role-prices-form-table tr.festi-user-role-prices-top-border th { border-top: 1px solid #eee; } .festi-user-role-prices .festi-user-role-prices-form-table td, .festi-user-role-prices .festi-user-role-prices-form-table th { padding: 5px; padding-bottom: 20px; padding-top: 20px; line-height: 20px; vertical-align: top; text-align: left; font-size: 15px; } .festi-user-role-prices .festi-user-role-prices-help-tip { cursor: help; vertical-align: middle; } .festi-user-role-prices .festi-user-role-prices-form-table th { width: 280px; } .festi-user-role-prices .festi-user-role-prices-lable { } input[type="text"], .festi-user-role-prices input[type="number"], .festi-user-role-prices select { height: 30px; } .festi-user-role-prices input[type="text"], .festi-user-role-prices input[type="number"], .festi-user-role-prices input[type="checkbox"], .festi-user-role-prices select { background-color: #ffffff; border: 1px solid #cccccc; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear 0.2s, box-shadow linear 0.2s; -moz-transition: border linear 0.2s, box-shadow linear 0.2s; -o-transition: border linear 0.2s, box-shadow linear 0.2s; transition: border linear 0.2s, box-shadow linear 0.2s; } input[type="text"]:focus, .festi-user-role-prices input[type="number"]:focus, .festi-user-role-prices input[type="checkbox"]:focus, .festi-user-role-prices select:focus { border-color: rgba(82, 168, 236, 0.8); outline: 0; outline: thin dotted \9; /* IE6-9 */ -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6); } .festi-user-role-prices .festi-user-role-prices-add-on { display: inline-block; width: 26px; height: 24px !important; min-width: 16px; font-size: 14px; font-weight: normal; line-height: 22px; position:relative; right: 8px; padding:2px; top: 1px; text-align: center; text-shadow: 0 1px 0 #ffffff; background-color: #eeeeee; border: 1px solid #ccc; -webkit-border-top-right-radius: 5px; -moz-border-top-right-radius: 5px; border-top-right-radius: 5px; -webkit-border-bottom-right-radius: 5px; -moz-border-bottom-right-radius: 5px; border-bottom-right-radius: 5px; vertical-align: top; } .festi-user-role-prices tr.festi-user-role-prices-divider th { text-align:left; background-color: #789bb3; padding: 10px; text-transform: uppercase; color: #ffffff; } a.festi-user-role-prices-delete-role { text-decoration: none; font-size: 26px; font-weight: bold; margin-left: 5px; vertical-align: middle; color: #ff5c5c; } a.festi-user-role-prices-delete-role:hover { color: #ff0000; } .festi-user-role-prices .festi-user-role-prices-hidden { display:none; } fieldset.festi-user-role-prices-grouped-roles table th { font-weight: normal; } .festi-user-role-prices-save-button-block { } .festi-user-role-prices .festi-user-role-prices-save-button { float: right; } fieldset.festi-user-role-prices-options { display: inline-block; border: 1px solid #eeeeee; padding: 20px; margin-bottom: 30px; margin-top:20px; min-width: 820px; padding-top: 25px; padding-bottom: 10px; background-color: #ffffff; } .festi-user-role-prices h2 { font-size: 22px; font-weight: 400; padding: 9px 15px 4px 0; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles tr, fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles th, fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles td { border: 0; padding: 5px; margin: 0; vertical-align: middle; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles th { width:40%; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles td label { margin-left: 20px; margin-right: 5px; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles span { font-size: 15px; font-weight: normal; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles td input { width: 75px; text-align: left; vertical-align: middle; } .festi-user-role-prices { } .festi-content { display: inline-block; } fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles td input, fieldset.festi-user-role-prices-options #festi-user-role-prices-discount-roles td select { height: 28px; } div#festi-import-report .festi-import-report-title { text-transform: uppercase; } .festi-user-role-prices { } div#festi-import-report p.festi-import-report-text { font-weight: normal; } div#festi-import-report p.festi-import-report-text { margin-left: 20px; } .festi-color-selector { position: relative; top: 0; left: -3px; width: 36px; height: 36px; } .festi-color-selector div { position: relative; top: 4px; left: 4px; width: 28px; height: 28px; background: url(../../images/color_picker/select2.png) center; } div.colorpicker input { height: 15px !important; border: 0 !important; } body div.colorpicker { z-index: 10; } /*Import Page*/ .festi-user-role-prices-import-url { width: 400px; }
hrishiko/gavkiwp
wp-content/plugins/woocommerce-prices-by-user-role/static/styles/backend/style.css
CSS
gpl-2.0
6,195
#ifndef RBKIT_APPSTATE_H #define RBKIT_APPSTATE_H #include <QObject> #include <QMutex> #include <QHash> #include <QVariant> namespace RBKit { class AppState { QMutex mutex; QHash<QString, QVariant> appState; QHash<int, QString> snapshotNames; AppState(); static AppState *singleton; QString protocolVersion; public: const QVariant getState(const QString& ket); void setAppState(const QString key, const QVariant value); void setSnapshotName(int key, QString snapShotName); QString getSnapshotName(int key) const; void removeSnapshotName(int key); static AppState* getInstance(); QString getProtocolVersion() const; void setProtocolVersion(const QString &value); }; } // namespace RBKit #endif // RBKIT_APPSTATE_H
duleorlovic/rbkit-client
rbkit-lib/model/appstate.h
C
gpl-2.0
774
// Copyright 2013 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <sstream> #include <unordered_map> #include "Common/GL/GLInterfaceBase.h" #include "Common/GL/GLExtensions/GLExtensions.h" #include "Common/Logging/Log.h" #if defined(__linux__) || defined(__APPLE__) #include <dlfcn.h> #endif // gl_1_1 PFNDOLCLEARINDEXPROC dolClearIndex; PFNDOLCLEARCOLORPROC dolClearColor; PFNDOLCLEARPROC dolClear; PFNDOLINDEXMASKPROC dolIndexMask; PFNDOLCOLORMASKPROC dolColorMask; PFNDOLALPHAFUNCPROC dolAlphaFunc; PFNDOLBLENDFUNCPROC dolBlendFunc; PFNDOLLOGICOPPROC dolLogicOp; PFNDOLCULLFACEPROC dolCullFace; PFNDOLFRONTFACEPROC dolFrontFace; PFNDOLPOINTSIZEPROC dolPointSize; PFNDOLLINEWIDTHPROC dolLineWidth; PFNDOLLINESTIPPLEPROC dolLineStipple; PFNDOLPOLYGONMODEPROC dolPolygonMode; PFNDOLPOLYGONOFFSETPROC dolPolygonOffset; PFNDOLPOLYGONSTIPPLEPROC dolPolygonStipple; PFNDOLGETPOLYGONSTIPPLEPROC dolGetPolygonStipple; PFNDOLEDGEFLAGPROC dolEdgeFlag; PFNDOLEDGEFLAGVPROC dolEdgeFlagv; PFNDOLSCISSORPROC dolScissor; PFNDOLCLIPPLANEPROC dolClipPlane; PFNDOLGETCLIPPLANEPROC dolGetClipPlane; PFNDOLDRAWBUFFERPROC dolDrawBuffer; PFNDOLREADBUFFERPROC dolReadBuffer; PFNDOLENABLEPROC dolEnable; PFNDOLDISABLEPROC dolDisable; PFNDOLISENABLEDPROC dolIsEnabled; PFNDOLENABLECLIENTSTATEPROC dolEnableClientState; PFNDOLDISABLECLIENTSTATEPROC dolDisableClientState; PFNDOLGETBOOLEANVPROC dolGetBooleanv; PFNDOLGETDOUBLEVPROC dolGetDoublev; PFNDOLGETFLOATVPROC dolGetFloatv; PFNDOLGETINTEGERVPROC dolGetIntegerv; PFNDOLPUSHATTRIBPROC dolPushAttrib; PFNDOLPOPATTRIBPROC dolPopAttrib; PFNDOLPUSHCLIENTATTRIBPROC dolPushClientAttrib; PFNDOLPOPCLIENTATTRIBPROC dolPopClientAttrib; PFNDOLRENDERMODEPROC dolRenderMode; PFNDOLGETERRORPROC dolGetError; PFNDOLGETSTRINGPROC dolGetString; PFNDOLFINISHPROC dolFinish; PFNDOLFLUSHPROC dolFlush; PFNDOLHINTPROC dolHint; PFNDOLCLEARDEPTHPROC dolClearDepth; PFNDOLDEPTHFUNCPROC dolDepthFunc; PFNDOLDEPTHMASKPROC dolDepthMask; PFNDOLDEPTHRANGEPROC dolDepthRange; PFNDOLCLEARACCUMPROC dolClearAccum; PFNDOLACCUMPROC dolAccum; PFNDOLMATRIXMODEPROC dolMatrixMode; PFNDOLORTHOPROC dolOrtho; PFNDOLFRUSTUMPROC dolFrustum; PFNDOLVIEWPORTPROC dolViewport; PFNDOLPUSHMATRIXPROC dolPushMatrix; PFNDOLPOPMATRIXPROC dolPopMatrix; PFNDOLLOADIDENTITYPROC dolLoadIdentity; PFNDOLLOADMATRIXDPROC dolLoadMatrixd; PFNDOLLOADMATRIXFPROC dolLoadMatrixf; PFNDOLMULTMATRIXDPROC dolMultMatrixd; PFNDOLMULTMATRIXFPROC dolMultMatrixf; PFNDOLROTATEDPROC dolRotated; PFNDOLROTATEFPROC dolRotatef; PFNDOLSCALEDPROC dolScaled; PFNDOLSCALEFPROC dolScalef; PFNDOLTRANSLATEDPROC dolTranslated; PFNDOLTRANSLATEFPROC dolTranslatef; PFNDOLISLISTPROC dolIsList; PFNDOLDELETELISTSPROC dolDeleteLists; PFNDOLGENLISTSPROC dolGenLists; PFNDOLNEWLISTPROC dolNewList; PFNDOLENDLISTPROC dolEndList; PFNDOLCALLLISTPROC dolCallList; PFNDOLCALLLISTSPROC dolCallLists; PFNDOLLISTBASEPROC dolListBase; PFNDOLBEGINPROC dolBegin; PFNDOLENDPROC dolEnd; PFNDOLVERTEX2DPROC dolVertex2d; PFNDOLVERTEX2FPROC dolVertex2f; PFNDOLVERTEX2IPROC dolVertex2i; PFNDOLVERTEX2SPROC dolVertex2s; PFNDOLVERTEX3DPROC dolVertex3d; PFNDOLVERTEX3FPROC dolVertex3f; PFNDOLVERTEX3IPROC dolVertex3i; PFNDOLVERTEX3SPROC dolVertex3s; PFNDOLVERTEX4DPROC dolVertex4d; PFNDOLVERTEX4FPROC dolVertex4f; PFNDOLVERTEX4IPROC dolVertex4i; PFNDOLVERTEX4SPROC dolVertex4s; PFNDOLVERTEX2DVPROC dolVertex2dv; PFNDOLVERTEX2FVPROC dolVertex2fv; PFNDOLVERTEX2IVPROC dolVertex2iv; PFNDOLVERTEX2SVPROC dolVertex2sv; PFNDOLVERTEX3DVPROC dolVertex3dv; PFNDOLVERTEX3FVPROC dolVertex3fv; PFNDOLVERTEX3IVPROC dolVertex3iv; PFNDOLVERTEX3SVPROC dolVertex3sv; PFNDOLVERTEX4DVPROC dolVertex4dv; PFNDOLVERTEX4FVPROC dolVertex4fv; PFNDOLVERTEX4IVPROC dolVertex4iv; PFNDOLVERTEX4SVPROC dolVertex4sv; PFNDOLNORMAL3BPROC dolNormal3b; PFNDOLNORMAL3DPROC dolNormal3d; PFNDOLNORMAL3FPROC dolNormal3f; PFNDOLNORMAL3IPROC dolNormal3i; PFNDOLNORMAL3SPROC dolNormal3s; PFNDOLNORMAL3BVPROC dolNormal3bv; PFNDOLNORMAL3DVPROC dolNormal3dv; PFNDOLNORMAL3FVPROC dolNormal3fv; PFNDOLNORMAL3IVPROC dolNormal3iv; PFNDOLNORMAL3SVPROC dolNormal3sv; PFNDOLINDEXDPROC dolIndexd; PFNDOLINDEXFPROC dolIndexf; PFNDOLINDEXIPROC dolIndexi; PFNDOLINDEXSPROC dolIndexs; PFNDOLINDEXUBPROC dolIndexub; PFNDOLINDEXDVPROC dolIndexdv; PFNDOLINDEXFVPROC dolIndexfv; PFNDOLINDEXIVPROC dolIndexiv; PFNDOLINDEXSVPROC dolIndexsv; PFNDOLINDEXUBVPROC dolIndexubv; PFNDOLCOLOR3BPROC dolColor3b; PFNDOLCOLOR3DPROC dolColor3d; PFNDOLCOLOR3FPROC dolColor3f; PFNDOLCOLOR3IPROC dolColor3i; PFNDOLCOLOR3SPROC dolColor3s; PFNDOLCOLOR3UBPROC dolColor3ub; PFNDOLCOLOR3UIPROC dolColor3ui; PFNDOLCOLOR3USPROC dolColor3us; PFNDOLCOLOR4BPROC dolColor4b; PFNDOLCOLOR4DPROC dolColor4d; PFNDOLCOLOR4FPROC dolColor4f; PFNDOLCOLOR4IPROC dolColor4i; PFNDOLCOLOR4SPROC dolColor4s; PFNDOLCOLOR4UBPROC dolColor4ub; PFNDOLCOLOR4UIPROC dolColor4ui; PFNDOLCOLOR4USPROC dolColor4us; PFNDOLCOLOR3BVPROC dolColor3bv; PFNDOLCOLOR3DVPROC dolColor3dv; PFNDOLCOLOR3FVPROC dolColor3fv; PFNDOLCOLOR3IVPROC dolColor3iv; PFNDOLCOLOR3SVPROC dolColor3sv; PFNDOLCOLOR3UBVPROC dolColor3ubv; PFNDOLCOLOR3UIVPROC dolColor3uiv; PFNDOLCOLOR3USVPROC dolColor3usv; PFNDOLCOLOR4BVPROC dolColor4bv; PFNDOLCOLOR4DVPROC dolColor4dv; PFNDOLCOLOR4FVPROC dolColor4fv; PFNDOLCOLOR4IVPROC dolColor4iv; PFNDOLCOLOR4SVPROC dolColor4sv; PFNDOLCOLOR4UBVPROC dolColor4ubv; PFNDOLCOLOR4UIVPROC dolColor4uiv; PFNDOLCOLOR4USVPROC dolColor4usv; PFNDOLTEXCOORD1DPROC dolTexCoord1d; PFNDOLTEXCOORD1FPROC dolTexCoord1f; PFNDOLTEXCOORD1IPROC dolTexCoord1i; PFNDOLTEXCOORD1SPROC dolTexCoord1s; PFNDOLTEXCOORD2DPROC dolTexCoord2d; PFNDOLTEXCOORD2FPROC dolTexCoord2f; PFNDOLTEXCOORD2IPROC dolTexCoord2i; PFNDOLTEXCOORD2SPROC dolTexCoord2s; PFNDOLTEXCOORD3DPROC dolTexCoord3d; PFNDOLTEXCOORD3FPROC dolTexCoord3f; PFNDOLTEXCOORD3IPROC dolTexCoord3i; PFNDOLTEXCOORD3SPROC dolTexCoord3s; PFNDOLTEXCOORD4DPROC dolTexCoord4d; PFNDOLTEXCOORD4FPROC dolTexCoord4f; PFNDOLTEXCOORD4IPROC dolTexCoord4i; PFNDOLTEXCOORD4SPROC dolTexCoord4s; PFNDOLTEXCOORD1DVPROC dolTexCoord1dv; PFNDOLTEXCOORD1FVPROC dolTexCoord1fv; PFNDOLTEXCOORD1IVPROC dolTexCoord1iv; PFNDOLTEXCOORD1SVPROC dolTexCoord1sv; PFNDOLTEXCOORD2DVPROC dolTexCoord2dv; PFNDOLTEXCOORD2FVPROC dolTexCoord2fv; PFNDOLTEXCOORD2IVPROC dolTexCoord2iv; PFNDOLTEXCOORD2SVPROC dolTexCoord2sv; PFNDOLTEXCOORD3DVPROC dolTexCoord3dv; PFNDOLTEXCOORD3FVPROC dolTexCoord3fv; PFNDOLTEXCOORD3IVPROC dolTexCoord3iv; PFNDOLTEXCOORD3SVPROC dolTexCoord3sv; PFNDOLTEXCOORD4DVPROC dolTexCoord4dv; PFNDOLTEXCOORD4FVPROC dolTexCoord4fv; PFNDOLTEXCOORD4IVPROC dolTexCoord4iv; PFNDOLTEXCOORD4SVPROC dolTexCoord4sv; PFNDOLRASTERPOS2DPROC dolRasterPos2d; PFNDOLRASTERPOS2FPROC dolRasterPos2f; PFNDOLRASTERPOS2IPROC dolRasterPos2i; PFNDOLRASTERPOS2SPROC dolRasterPos2s; PFNDOLRASTERPOS3DPROC dolRasterPos3d; PFNDOLRASTERPOS3FPROC dolRasterPos3f; PFNDOLRASTERPOS3IPROC dolRasterPos3i; PFNDOLRASTERPOS3SPROC dolRasterPos3s; PFNDOLRASTERPOS4DPROC dolRasterPos4d; PFNDOLRASTERPOS4FPROC dolRasterPos4f; PFNDOLRASTERPOS4IPROC dolRasterPos4i; PFNDOLRASTERPOS4SPROC dolRasterPos4s; PFNDOLRASTERPOS2DVPROC dolRasterPos2dv; PFNDOLRASTERPOS2FVPROC dolRasterPos2fv; PFNDOLRASTERPOS2IVPROC dolRasterPos2iv; PFNDOLRASTERPOS2SVPROC dolRasterPos2sv; PFNDOLRASTERPOS3DVPROC dolRasterPos3dv; PFNDOLRASTERPOS3FVPROC dolRasterPos3fv; PFNDOLRASTERPOS3IVPROC dolRasterPos3iv; PFNDOLRASTERPOS3SVPROC dolRasterPos3sv; PFNDOLRASTERPOS4DVPROC dolRasterPos4dv; PFNDOLRASTERPOS4FVPROC dolRasterPos4fv; PFNDOLRASTERPOS4IVPROC dolRasterPos4iv; PFNDOLRASTERPOS4SVPROC dolRasterPos4sv; PFNDOLRECTDPROC dolRectd; PFNDOLRECTFPROC dolRectf; PFNDOLRECTIPROC dolRecti; PFNDOLRECTSPROC dolRects; PFNDOLRECTDVPROC dolRectdv; PFNDOLRECTFVPROC dolRectfv; PFNDOLRECTIVPROC dolRectiv; PFNDOLRECTSVPROC dolRectsv; PFNDOLVERTEXPOINTERPROC dolVertexPointer; PFNDOLNORMALPOINTERPROC dolNormalPointer; PFNDOLCOLORPOINTERPROC dolColorPointer; PFNDOLINDEXPOINTERPROC dolIndexPointer; PFNDOLTEXCOORDPOINTERPROC dolTexCoordPointer; PFNDOLEDGEFLAGPOINTERPROC dolEdgeFlagPointer; PFNDOLGETPOINTERVPROC dolGetPointerv; PFNDOLARRAYELEMENTPROC dolArrayElement; PFNDOLDRAWARRAYSPROC dolDrawArrays; PFNDOLDRAWELEMENTSPROC dolDrawElements; PFNDOLINTERLEAVEDARRAYSPROC dolInterleavedArrays; PFNDOLSHADEMODELPROC dolShadeModel; PFNDOLLIGHTFPROC dolLightf; PFNDOLLIGHTIPROC dolLighti; PFNDOLLIGHTFVPROC dolLightfv; PFNDOLLIGHTIVPROC dolLightiv; PFNDOLGETLIGHTFVPROC dolGetLightfv; PFNDOLGETLIGHTIVPROC dolGetLightiv; PFNDOLLIGHTMODELFPROC dolLightModelf; PFNDOLLIGHTMODELIPROC dolLightModeli; PFNDOLLIGHTMODELFVPROC dolLightModelfv; PFNDOLLIGHTMODELIVPROC dolLightModeliv; PFNDOLMATERIALFPROC dolMaterialf; PFNDOLMATERIALIPROC dolMateriali; PFNDOLMATERIALFVPROC dolMaterialfv; PFNDOLMATERIALIVPROC dolMaterialiv; PFNDOLGETMATERIALFVPROC dolGetMaterialfv; PFNDOLGETMATERIALIVPROC dolGetMaterialiv; PFNDOLCOLORMATERIALPROC dolColorMaterial; PFNDOLPIXELZOOMPROC dolPixelZoom; PFNDOLPIXELSTOREFPROC dolPixelStoref; PFNDOLPIXELSTOREIPROC dolPixelStorei; PFNDOLPIXELTRANSFERFPROC dolPixelTransferf; PFNDOLPIXELTRANSFERIPROC dolPixelTransferi; PFNDOLPIXELMAPFVPROC dolPixelMapfv; PFNDOLPIXELMAPUIVPROC dolPixelMapuiv; PFNDOLPIXELMAPUSVPROC dolPixelMapusv; PFNDOLGETPIXELMAPFVPROC dolGetPixelMapfv; PFNDOLGETPIXELMAPUIVPROC dolGetPixelMapuiv; PFNDOLGETPIXELMAPUSVPROC dolGetPixelMapusv; PFNDOLBITMAPPROC dolBitmap; PFNDOLREADPIXELSPROC dolReadPixels; PFNDOLDRAWPIXELSPROC dolDrawPixels; PFNDOLCOPYPIXELSPROC dolCopyPixels; PFNDOLSTENCILFUNCPROC dolStencilFunc; PFNDOLSTENCILMASKPROC dolStencilMask; PFNDOLSTENCILOPPROC dolStencilOp; PFNDOLCLEARSTENCILPROC dolClearStencil; PFNDOLTEXGENDPROC dolTexGend; PFNDOLTEXGENFPROC dolTexGenf; PFNDOLTEXGENIPROC dolTexGeni; PFNDOLTEXGENDVPROC dolTexGendv; PFNDOLTEXGENFVPROC dolTexGenfv; PFNDOLTEXGENIVPROC dolTexGeniv; PFNDOLGETTEXGENDVPROC dolGetTexGendv; PFNDOLGETTEXGENFVPROC dolGetTexGenfv; PFNDOLGETTEXGENIVPROC dolGetTexGeniv; PFNDOLTEXENVFPROC dolTexEnvf; PFNDOLTEXENVIPROC dolTexEnvi; PFNDOLTEXENVFVPROC dolTexEnvfv; PFNDOLTEXENVIVPROC dolTexEnviv; PFNDOLGETTEXENVFVPROC dolGetTexEnvfv; PFNDOLGETTEXENVIVPROC dolGetTexEnviv; PFNDOLTEXPARAMETERFPROC dolTexParameterf; PFNDOLTEXPARAMETERIPROC dolTexParameteri; PFNDOLTEXPARAMETERFVPROC dolTexParameterfv; PFNDOLTEXPARAMETERIVPROC dolTexParameteriv; PFNDOLGETTEXPARAMETERFVPROC dolGetTexParameterfv; PFNDOLGETTEXPARAMETERIVPROC dolGetTexParameteriv; PFNDOLGETTEXLEVELPARAMETERFVPROC dolGetTexLevelParameterfv; PFNDOLGETTEXLEVELPARAMETERIVPROC dolGetTexLevelParameteriv; PFNDOLTEXIMAGE1DPROC dolTexImage1D; PFNDOLTEXIMAGE2DPROC dolTexImage2D; PFNDOLGETTEXIMAGEPROC dolGetTexImage; PFNDOLGENTEXTURESPROC dolGenTextures; PFNDOLDELETETEXTURESPROC dolDeleteTextures; PFNDOLBINDTEXTUREPROC dolBindTexture; PFNDOLPRIORITIZETEXTURESPROC dolPrioritizeTextures; PFNDOLARETEXTURESRESIDENTPROC dolAreTexturesResident; PFNDOLISTEXTUREPROC dolIsTexture; PFNDOLTEXSUBIMAGE1DPROC dolTexSubImage1D; PFNDOLTEXSUBIMAGE2DPROC dolTexSubImage2D; PFNDOLCOPYTEXIMAGE1DPROC dolCopyTexImage1D; PFNDOLCOPYTEXIMAGE2DPROC dolCopyTexImage2D; PFNDOLCOPYTEXSUBIMAGE1DPROC dolCopyTexSubImage1D; PFNDOLCOPYTEXSUBIMAGE2DPROC dolCopyTexSubImage2D; PFNDOLMAP1DPROC dolMap1d; PFNDOLMAP1FPROC dolMap1f; PFNDOLMAP2DPROC dolMap2d; PFNDOLMAP2FPROC dolMap2f; PFNDOLGETMAPDVPROC dolGetMapdv; PFNDOLGETMAPFVPROC dolGetMapfv; PFNDOLGETMAPIVPROC dolGetMapiv; PFNDOLEVALCOORD1DPROC dolEvalCoord1d; PFNDOLEVALCOORD1FPROC dolEvalCoord1f; PFNDOLEVALCOORD1DVPROC dolEvalCoord1dv; PFNDOLEVALCOORD1FVPROC dolEvalCoord1fv; PFNDOLEVALCOORD2DPROC dolEvalCoord2d; PFNDOLEVALCOORD2FPROC dolEvalCoord2f; PFNDOLEVALCOORD2DVPROC dolEvalCoord2dv; PFNDOLEVALCOORD2FVPROC dolEvalCoord2fv; PFNDOLMAPGRID1DPROC dolMapGrid1d; PFNDOLMAPGRID1FPROC dolMapGrid1f; PFNDOLMAPGRID2DPROC dolMapGrid2d; PFNDOLMAPGRID2FPROC dolMapGrid2f; PFNDOLEVALPOINT1PROC dolEvalPoint1; PFNDOLEVALPOINT2PROC dolEvalPoint2; PFNDOLEVALMESH1PROC dolEvalMesh1; PFNDOLEVALMESH2PROC dolEvalMesh2; PFNDOLFOGFPROC dolFogf; PFNDOLFOGIPROC dolFogi; PFNDOLFOGFVPROC dolFogfv; PFNDOLFOGIVPROC dolFogiv; PFNDOLFEEDBACKBUFFERPROC dolFeedbackBuffer; PFNDOLPASSTHROUGHPROC dolPassThrough; PFNDOLSELECTBUFFERPROC dolSelectBuffer; PFNDOLINITNAMESPROC dolInitNames; PFNDOLLOADNAMEPROC dolLoadName; PFNDOLPUSHNAMEPROC dolPushName; PFNDOLPOPNAMEPROC dolPopName; // gl_1_2 PFNDOLCOPYTEXSUBIMAGE3DPROC dolCopyTexSubImage3D; PFNDOLDRAWRANGEELEMENTSPROC dolDrawRangeElements; PFNDOLTEXIMAGE3DPROC dolTexImage3D; PFNDOLTEXSUBIMAGE3DPROC dolTexSubImage3D; // gl_1_3 PFNDOLACTIVETEXTUREARBPROC dolActiveTexture; PFNDOLCLIENTACTIVETEXTUREARBPROC dolClientActiveTexture; PFNDOLCOMPRESSEDTEXIMAGE1DPROC dolCompressedTexImage1D; PFNDOLCOMPRESSEDTEXIMAGE2DPROC dolCompressedTexImage2D; PFNDOLCOMPRESSEDTEXIMAGE3DPROC dolCompressedTexImage3D; PFNDOLCOMPRESSEDTEXSUBIMAGE1DPROC dolCompressedTexSubImage1D; PFNDOLCOMPRESSEDTEXSUBIMAGE2DPROC dolCompressedTexSubImage2D; PFNDOLCOMPRESSEDTEXSUBIMAGE3DPROC dolCompressedTexSubImage3D; PFNDOLGETCOMPRESSEDTEXIMAGEPROC dolGetCompressedTexImage; PFNDOLLOADTRANSPOSEMATRIXDARBPROC dolLoadTransposeMatrixd; PFNDOLLOADTRANSPOSEMATRIXFARBPROC dolLoadTransposeMatrixf; PFNDOLMULTTRANSPOSEMATRIXDARBPROC dolMultTransposeMatrixd; PFNDOLMULTTRANSPOSEMATRIXFARBPROC dolMultTransposeMatrixf; PFNDOLMULTITEXCOORD1DARBPROC dolMultiTexCoord1d; PFNDOLMULTITEXCOORD1DVARBPROC dolMultiTexCoord1dv; PFNDOLMULTITEXCOORD1FARBPROC dolMultiTexCoord1f; PFNDOLMULTITEXCOORD1FVARBPROC dolMultiTexCoord1fv; PFNDOLMULTITEXCOORD1IARBPROC dolMultiTexCoord1i; PFNDOLMULTITEXCOORD1IVARBPROC dolMultiTexCoord1iv; PFNDOLMULTITEXCOORD1SARBPROC dolMultiTexCoord1s; PFNDOLMULTITEXCOORD1SVARBPROC dolMultiTexCoord1sv; PFNDOLMULTITEXCOORD2DARBPROC dolMultiTexCoord2d; PFNDOLMULTITEXCOORD2DVARBPROC dolMultiTexCoord2dv; PFNDOLMULTITEXCOORD2FARBPROC dolMultiTexCoord2f; PFNDOLMULTITEXCOORD2FVARBPROC dolMultiTexCoord2fv; PFNDOLMULTITEXCOORD2IARBPROC dolMultiTexCoord2i; PFNDOLMULTITEXCOORD2IVARBPROC dolMultiTexCoord2iv; PFNDOLMULTITEXCOORD2SARBPROC dolMultiTexCoord2s; PFNDOLMULTITEXCOORD2SVARBPROC dolMultiTexCoord2sv; PFNDOLMULTITEXCOORD3DARBPROC dolMultiTexCoord3d; PFNDOLMULTITEXCOORD3DVARBPROC dolMultiTexCoord3dv; PFNDOLMULTITEXCOORD3FARBPROC dolMultiTexCoord3f; PFNDOLMULTITEXCOORD3FVARBPROC dolMultiTexCoord3fv; PFNDOLMULTITEXCOORD3IARBPROC dolMultiTexCoord3i; PFNDOLMULTITEXCOORD3IVARBPROC dolMultiTexCoord3iv; PFNDOLMULTITEXCOORD3SARBPROC dolMultiTexCoord3s; PFNDOLMULTITEXCOORD3SVARBPROC dolMultiTexCoord3sv; PFNDOLMULTITEXCOORD4DARBPROC dolMultiTexCoord4d; PFNDOLMULTITEXCOORD4DVARBPROC dolMultiTexCoord4dv; PFNDOLMULTITEXCOORD4FARBPROC dolMultiTexCoord4f; PFNDOLMULTITEXCOORD4FVARBPROC dolMultiTexCoord4fv; PFNDOLMULTITEXCOORD4IARBPROC dolMultiTexCoord4i; PFNDOLMULTITEXCOORD4IVARBPROC dolMultiTexCoord4iv; PFNDOLMULTITEXCOORD4SARBPROC dolMultiTexCoord4s; PFNDOLMULTITEXCOORD4SVARBPROC dolMultiTexCoord4sv; PFNDOLSAMPLECOVERAGEARBPROC dolSampleCoverage; // gl_1_4 PFNDOLBLENDCOLORPROC dolBlendColor; PFNDOLBLENDEQUATIONPROC dolBlendEquation; PFNDOLBLENDFUNCSEPARATEPROC dolBlendFuncSeparate; PFNDOLFOGCOORDPOINTERPROC dolFogCoordPointer; PFNDOLFOGCOORDDPROC dolFogCoordd; PFNDOLFOGCOORDDVPROC dolFogCoorddv; PFNDOLFOGCOORDFPROC dolFogCoordf; PFNDOLFOGCOORDFVPROC dolFogCoordfv; PFNDOLMULTIDRAWARRAYSPROC dolMultiDrawArrays; PFNDOLMULTIDRAWELEMENTSPROC dolMultiDrawElements; PFNDOLPOINTPARAMETERFPROC dolPointParameterf; PFNDOLPOINTPARAMETERFVPROC dolPointParameterfv; PFNDOLPOINTPARAMETERIPROC dolPointParameteri; PFNDOLPOINTPARAMETERIVPROC dolPointParameteriv; PFNDOLSECONDARYCOLOR3BPROC dolSecondaryColor3b; PFNDOLSECONDARYCOLOR3BVPROC dolSecondaryColor3bv; PFNDOLSECONDARYCOLOR3DPROC dolSecondaryColor3d; PFNDOLSECONDARYCOLOR3DVPROC dolSecondaryColor3dv; PFNDOLSECONDARYCOLOR3FPROC dolSecondaryColor3f; PFNDOLSECONDARYCOLOR3FVPROC dolSecondaryColor3fv; PFNDOLSECONDARYCOLOR3IPROC dolSecondaryColor3i; PFNDOLSECONDARYCOLOR3IVPROC dolSecondaryColor3iv; PFNDOLSECONDARYCOLOR3SPROC dolSecondaryColor3s; PFNDOLSECONDARYCOLOR3SVPROC dolSecondaryColor3sv; PFNDOLSECONDARYCOLOR3UBPROC dolSecondaryColor3ub; PFNDOLSECONDARYCOLOR3UBVPROC dolSecondaryColor3ubv; PFNDOLSECONDARYCOLOR3UIPROC dolSecondaryColor3ui; PFNDOLSECONDARYCOLOR3UIVPROC dolSecondaryColor3uiv; PFNDOLSECONDARYCOLOR3USPROC dolSecondaryColor3us; PFNDOLSECONDARYCOLOR3USVPROC dolSecondaryColor3usv; PFNDOLSECONDARYCOLORPOINTERPROC dolSecondaryColorPointer; PFNDOLWINDOWPOS2DPROC dolWindowPos2d; PFNDOLWINDOWPOS2DVPROC dolWindowPos2dv; PFNDOLWINDOWPOS2FPROC dolWindowPos2f; PFNDOLWINDOWPOS2FVPROC dolWindowPos2fv; PFNDOLWINDOWPOS2IPROC dolWindowPos2i; PFNDOLWINDOWPOS2IVPROC dolWindowPos2iv; PFNDOLWINDOWPOS2SPROC dolWindowPos2s; PFNDOLWINDOWPOS2SVPROC dolWindowPos2sv; PFNDOLWINDOWPOS3DPROC dolWindowPos3d; PFNDOLWINDOWPOS3DVPROC dolWindowPos3dv; PFNDOLWINDOWPOS3FPROC dolWindowPos3f; PFNDOLWINDOWPOS3FVPROC dolWindowPos3fv; PFNDOLWINDOWPOS3IPROC dolWindowPos3i; PFNDOLWINDOWPOS3IVPROC dolWindowPos3iv; PFNDOLWINDOWPOS3SPROC dolWindowPos3s; PFNDOLWINDOWPOS3SVPROC dolWindowPos3sv; // gl_1_5 PFNDOLBEGINQUERYPROC dolBeginQuery; PFNDOLBINDBUFFERPROC dolBindBuffer; PFNDOLBUFFERDATAPROC dolBufferData; PFNDOLBUFFERSUBDATAPROC dolBufferSubData; PFNDOLDELETEBUFFERSPROC dolDeleteBuffers; PFNDOLDELETEQUERIESPROC dolDeleteQueries; PFNDOLENDQUERYPROC dolEndQuery; PFNDOLGENBUFFERSPROC dolGenBuffers; PFNDOLGENQUERIESPROC dolGenQueries; PFNDOLGETBUFFERPARAMETERIVPROC dolGetBufferParameteriv; PFNDOLGETBUFFERPOINTERVPROC dolGetBufferPointerv; PFNDOLGETBUFFERSUBDATAPROC dolGetBufferSubData; PFNDOLGETQUERYOBJECTIVPROC dolGetQueryObjectiv; PFNDOLGETQUERYOBJECTUIVPROC dolGetQueryObjectuiv; PFNDOLGETQUERYIVPROC dolGetQueryiv; PFNDOLISBUFFERPROC dolIsBuffer; PFNDOLISQUERYPROC dolIsQuery; PFNDOLMAPBUFFERPROC dolMapBuffer; PFNDOLUNMAPBUFFERPROC dolUnmapBuffer; // gl_2_0 PFNDOLATTACHSHADERPROC dolAttachShader; PFNDOLBINDATTRIBLOCATIONPROC dolBindAttribLocation; PFNDOLBLENDEQUATIONSEPARATEPROC dolBlendEquationSeparate; PFNDOLCOMPILESHADERPROC dolCompileShader; PFNDOLCREATEPROGRAMPROC dolCreateProgram; PFNDOLCREATESHADERPROC dolCreateShader; PFNDOLDELETEPROGRAMPROC dolDeleteProgram; PFNDOLDELETESHADERPROC dolDeleteShader; PFNDOLDETACHSHADERPROC dolDetachShader; PFNDOLDISABLEVERTEXATTRIBARRAYPROC dolDisableVertexAttribArray; PFNDOLDRAWBUFFERSPROC dolDrawBuffers; PFNDOLENABLEVERTEXATTRIBARRAYPROC dolEnableVertexAttribArray; PFNDOLGETACTIVEATTRIBPROC dolGetActiveAttrib; PFNDOLGETACTIVEUNIFORMPROC dolGetActiveUniform; PFNDOLGETATTACHEDSHADERSPROC dolGetAttachedShaders; PFNDOLGETATTRIBLOCATIONPROC dolGetAttribLocation; PFNDOLGETPROGRAMINFOLOGPROC dolGetProgramInfoLog; PFNDOLGETPROGRAMIVPROC dolGetProgramiv; PFNDOLGETSHADERINFOLOGPROC dolGetShaderInfoLog; PFNDOLGETSHADERSOURCEPROC dolGetShaderSource; PFNDOLGETSHADERIVPROC dolGetShaderiv; PFNDOLGETUNIFORMLOCATIONPROC dolGetUniformLocation; PFNDOLGETUNIFORMFVPROC dolGetUniformfv; PFNDOLGETUNIFORMIVPROC dolGetUniformiv; PFNDOLGETVERTEXATTRIBPOINTERVPROC dolGetVertexAttribPointerv; PFNDOLGETVERTEXATTRIBDVPROC dolGetVertexAttribdv; PFNDOLGETVERTEXATTRIBFVPROC dolGetVertexAttribfv; PFNDOLGETVERTEXATTRIBIVPROC dolGetVertexAttribiv; PFNDOLISPROGRAMPROC dolIsProgram; PFNDOLISSHADERPROC dolIsShader; PFNDOLLINKPROGRAMPROC dolLinkProgram; PFNDOLSHADERSOURCEPROC dolShaderSource; PFNDOLSTENCILFUNCSEPARATEPROC dolStencilFuncSeparate; PFNDOLSTENCILMASKSEPARATEPROC dolStencilMaskSeparate; PFNDOLSTENCILOPSEPARATEPROC dolStencilOpSeparate; PFNDOLUNIFORM1FPROC dolUniform1f; PFNDOLUNIFORM1FVPROC dolUniform1fv; PFNDOLUNIFORM1IPROC dolUniform1i; PFNDOLUNIFORM1IVPROC dolUniform1iv; PFNDOLUNIFORM2FPROC dolUniform2f; PFNDOLUNIFORM2FVPROC dolUniform2fv; PFNDOLUNIFORM2IPROC dolUniform2i; PFNDOLUNIFORM2IVPROC dolUniform2iv; PFNDOLUNIFORM3FPROC dolUniform3f; PFNDOLUNIFORM3FVPROC dolUniform3fv; PFNDOLUNIFORM3IPROC dolUniform3i; PFNDOLUNIFORM3IVPROC dolUniform3iv; PFNDOLUNIFORM4FPROC dolUniform4f; PFNDOLUNIFORM4FVPROC dolUniform4fv; PFNDOLUNIFORM4IPROC dolUniform4i; PFNDOLUNIFORM4IVPROC dolUniform4iv; PFNDOLUNIFORMMATRIX2FVPROC dolUniformMatrix2fv; PFNDOLUNIFORMMATRIX3FVPROC dolUniformMatrix3fv; PFNDOLUNIFORMMATRIX4FVPROC dolUniformMatrix4fv; PFNDOLUSEPROGRAMPROC dolUseProgram; PFNDOLVALIDATEPROGRAMPROC dolValidateProgram; PFNDOLVERTEXATTRIB1DPROC dolVertexAttrib1d; PFNDOLVERTEXATTRIB1DVPROC dolVertexAttrib1dv; PFNDOLVERTEXATTRIB1FPROC dolVertexAttrib1f; PFNDOLVERTEXATTRIB1FVPROC dolVertexAttrib1fv; PFNDOLVERTEXATTRIB1SPROC dolVertexAttrib1s; PFNDOLVERTEXATTRIB1SVPROC dolVertexAttrib1sv; PFNDOLVERTEXATTRIB2DPROC dolVertexAttrib2d; PFNDOLVERTEXATTRIB2DVPROC dolVertexAttrib2dv; PFNDOLVERTEXATTRIB2FPROC dolVertexAttrib2f; PFNDOLVERTEXATTRIB2FVPROC dolVertexAttrib2fv; PFNDOLVERTEXATTRIB2SPROC dolVertexAttrib2s; PFNDOLVERTEXATTRIB2SVPROC dolVertexAttrib2sv; PFNDOLVERTEXATTRIB3DPROC dolVertexAttrib3d; PFNDOLVERTEXATTRIB3DVPROC dolVertexAttrib3dv; PFNDOLVERTEXATTRIB3FPROC dolVertexAttrib3f; PFNDOLVERTEXATTRIB3FVPROC dolVertexAttrib3fv; PFNDOLVERTEXATTRIB3SPROC dolVertexAttrib3s; PFNDOLVERTEXATTRIB3SVPROC dolVertexAttrib3sv; PFNDOLVERTEXATTRIB4NBVPROC dolVertexAttrib4Nbv; PFNDOLVERTEXATTRIB4NIVPROC dolVertexAttrib4Niv; PFNDOLVERTEXATTRIB4NSVPROC dolVertexAttrib4Nsv; PFNDOLVERTEXATTRIB4NUBPROC dolVertexAttrib4Nub; PFNDOLVERTEXATTRIB4NUBVPROC dolVertexAttrib4Nubv; PFNDOLVERTEXATTRIB4NUIVPROC dolVertexAttrib4Nuiv; PFNDOLVERTEXATTRIB4NUSVPROC dolVertexAttrib4Nusv; PFNDOLVERTEXATTRIB4BVPROC dolVertexAttrib4bv; PFNDOLVERTEXATTRIB4DPROC dolVertexAttrib4d; PFNDOLVERTEXATTRIB4DVPROC dolVertexAttrib4dv; PFNDOLVERTEXATTRIB4FPROC dolVertexAttrib4f; PFNDOLVERTEXATTRIB4FVPROC dolVertexAttrib4fv; PFNDOLVERTEXATTRIB4IVPROC dolVertexAttrib4iv; PFNDOLVERTEXATTRIB4SPROC dolVertexAttrib4s; PFNDOLVERTEXATTRIB4SVPROC dolVertexAttrib4sv; PFNDOLVERTEXATTRIB4UBVPROC dolVertexAttrib4ubv; PFNDOLVERTEXATTRIB4UIVPROC dolVertexAttrib4uiv; PFNDOLVERTEXATTRIB4USVPROC dolVertexAttrib4usv; PFNDOLVERTEXATTRIBPOINTERPROC dolVertexAttribPointer; // gl_2_1 PFNDOLUNIFORMMATRIX2X3FVPROC dolUniformMatrix2x3fv; PFNDOLUNIFORMMATRIX2X4FVPROC dolUniformMatrix2x4fv; PFNDOLUNIFORMMATRIX3X2FVPROC dolUniformMatrix3x2fv; PFNDOLUNIFORMMATRIX3X4FVPROC dolUniformMatrix3x4fv; PFNDOLUNIFORMMATRIX4X2FVPROC dolUniformMatrix4x2fv; PFNDOLUNIFORMMATRIX4X3FVPROC dolUniformMatrix4x3fv; // gl_3_0 PFNDOLBEGINCONDITIONALRENDERPROC dolBeginConditionalRender; PFNDOLBEGINTRANSFORMFEEDBACKPROC dolBeginTransformFeedback; PFNDOLBINDFRAGDATALOCATIONPROC dolBindFragDataLocation; PFNDOLCLAMPCOLORPROC dolClampColor; PFNDOLCLEARBUFFERFIPROC dolClearBufferfi; PFNDOLCLEARBUFFERFVPROC dolClearBufferfv; PFNDOLCLEARBUFFERIVPROC dolClearBufferiv; PFNDOLCLEARBUFFERUIVPROC dolClearBufferuiv; PFNDOLCOLORMASKIPROC dolColorMaski; PFNDOLDISABLEIPROC dolDisablei; PFNDOLENABLEIPROC dolEnablei; PFNDOLENDCONDITIONALRENDERPROC dolEndConditionalRender; PFNDOLENDTRANSFORMFEEDBACKPROC dolEndTransformFeedback; PFNDOLGETBOOLEANI_VPROC dolGetBooleani_v; PFNDOLGETFRAGDATALOCATIONPROC dolGetFragDataLocation; PFNDOLGETSTRINGIPROC dolGetStringi; PFNDOLGETTEXPARAMETERIIVPROC dolGetTexParameterIiv; PFNDOLGETTEXPARAMETERIUIVPROC dolGetTexParameterIuiv; PFNDOLGETTRANSFORMFEEDBACKVARYINGPROC dolGetTransformFeedbackVarying; PFNDOLGETUNIFORMUIVPROC dolGetUniformuiv; PFNDOLGETVERTEXATTRIBIIVPROC dolGetVertexAttribIiv; PFNDOLGETVERTEXATTRIBIUIVPROC dolGetVertexAttribIuiv; PFNDOLISENABLEDIPROC dolIsEnabledi; PFNDOLTEXPARAMETERIIVPROC dolTexParameterIiv; PFNDOLTEXPARAMETERIUIVPROC dolTexParameterIuiv; PFNDOLTRANSFORMFEEDBACKVARYINGSPROC dolTransformFeedbackVaryings; PFNDOLUNIFORM1UIPROC dolUniform1ui; PFNDOLUNIFORM1UIVPROC dolUniform1uiv; PFNDOLUNIFORM2UIPROC dolUniform2ui; PFNDOLUNIFORM2UIVPROC dolUniform2uiv; PFNDOLUNIFORM3UIPROC dolUniform3ui; PFNDOLUNIFORM3UIVPROC dolUniform3uiv; PFNDOLUNIFORM4UIPROC dolUniform4ui; PFNDOLUNIFORM4UIVPROC dolUniform4uiv; PFNDOLVERTEXATTRIBI1IPROC dolVertexAttribI1i; PFNDOLVERTEXATTRIBI1IVPROC dolVertexAttribI1iv; PFNDOLVERTEXATTRIBI1UIPROC dolVertexAttribI1ui; PFNDOLVERTEXATTRIBI1UIVPROC dolVertexAttribI1uiv; PFNDOLVERTEXATTRIBI2IPROC dolVertexAttribI2i; PFNDOLVERTEXATTRIBI2IVPROC dolVertexAttribI2iv; PFNDOLVERTEXATTRIBI2UIPROC dolVertexAttribI2ui; PFNDOLVERTEXATTRIBI2UIVPROC dolVertexAttribI2uiv; PFNDOLVERTEXATTRIBI3IPROC dolVertexAttribI3i; PFNDOLVERTEXATTRIBI3IVPROC dolVertexAttribI3iv; PFNDOLVERTEXATTRIBI3UIPROC dolVertexAttribI3ui; PFNDOLVERTEXATTRIBI3UIVPROC dolVertexAttribI3uiv; PFNDOLVERTEXATTRIBI4BVPROC dolVertexAttribI4bv; PFNDOLVERTEXATTRIBI4IPROC dolVertexAttribI4i; PFNDOLVERTEXATTRIBI4IVPROC dolVertexAttribI4iv; PFNDOLVERTEXATTRIBI4SVPROC dolVertexAttribI4sv; PFNDOLVERTEXATTRIBI4UBVPROC dolVertexAttribI4ubv; PFNDOLVERTEXATTRIBI4UIPROC dolVertexAttribI4ui; PFNDOLVERTEXATTRIBI4UIVPROC dolVertexAttribI4uiv; PFNDOLVERTEXATTRIBI4USVPROC dolVertexAttribI4usv; PFNDOLVERTEXATTRIBIPOINTERPROC dolVertexAttribIPointer; // gl_3_1 PFNDOLDRAWARRAYSINSTANCEDPROC dolDrawArraysInstanced; PFNDOLDRAWELEMENTSINSTANCEDPROC dolDrawElementsInstanced; PFNDOLPRIMITIVERESTARTINDEXPROC dolPrimitiveRestartIndex; PFNDOLTEXBUFFERPROC dolTexBuffer; // gl_3_2 PFNDOLFRAMEBUFFERTEXTUREPROC dolFramebufferTexture; PFNDOLGETBUFFERPARAMETERI64VPROC dolGetBufferParameteri64v; PFNDOLGETINTEGER64I_VPROC dolGetInteger64i_v; // gl 4_2 PFNDOLDRAWARRAYSINSTANCEDBASEINSTANCEPROC dolDrawArraysInstancedBaseInstance; PFNDOLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC dolDrawElementsInstancedBaseInstance; PFNDOLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC dolDrawElementsInstancedBaseVertexBaseInstance; PFNDOLGETINTERNALFORMATIVPROC dolGetInternalformativ; PFNDOLGETACTIVEATOMICCOUNTERBUFFERIVPROC dolGetActiveAtomicCounterBufferiv; PFNDOLBINDIMAGETEXTUREPROC dolBindImageTexture; PFNDOLMEMORYBARRIERPROC dolMemoryBarrier; PFNDOLTEXSTORAGE1DPROC dolTexStorage1D; PFNDOLTEXSTORAGE2DPROC dolTexStorage2D; PFNDOLTEXSTORAGE3DPROC dolTexStorage3D; PFNDOLDRAWTRANSFORMFEEDBACKINSTANCEDPROC dolDrawTransformFeedbackInstanced; PFNDOLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC dolDrawTransformFeedbackStreamInstanced; // gl_4_3 PFNDOLCLEARBUFFERDATAPROC dolClearBufferData; PFNDOLCLEARBUFFERSUBDATAPROC dolClearBufferSubData; PFNDOLDISPATCHCOMPUTEPROC dolDispatchCompute; PFNDOLDISPATCHCOMPUTEINDIRECTPROC dolDispatchComputeIndirect; PFNDOLFRAMEBUFFERPARAMETERIPROC dolFramebufferParameteri; PFNDOLGETFRAMEBUFFERPARAMETERIVPROC dolGetFramebufferParameteriv; PFNDOLGETINTERNALFORMATI64VPROC dolGetInternalformati64v; PFNDOLINVALIDATETEXSUBIMAGEPROC dolInvalidateTexSubImage; PFNDOLINVALIDATETEXIMAGEPROC dolInvalidateTexImage; PFNDOLINVALIDATEBUFFERSUBDATAPROC dolInvalidateBufferSubData; PFNDOLINVALIDATEBUFFERDATAPROC dolInvalidateBufferData; PFNDOLINVALIDATEFRAMEBUFFERPROC dolInvalidateFramebuffer; PFNDOLINVALIDATESUBFRAMEBUFFERPROC dolInvalidateSubFramebuffer; PFNDOLMULTIDRAWARRAYSINDIRECTPROC dolMultiDrawArraysIndirect; PFNDOLMULTIDRAWELEMENTSINDIRECTPROC dolMultiDrawElementsIndirect; PFNDOLGETPROGRAMINTERFACEIVPROC dolGetProgramInterfaceiv; PFNDOLGETPROGRAMRESOURCEINDEXPROC dolGetProgramResourceIndex; PFNDOLGETPROGRAMRESOURCENAMEPROC dolGetProgramResourceName; PFNDOLGETPROGRAMRESOURCEIVPROC dolGetProgramResourceiv; PFNDOLGETPROGRAMRESOURCELOCATIONPROC dolGetProgramResourceLocation; PFNDOLGETPROGRAMRESOURCELOCATIONINDEXPROC dolGetProgramResourceLocationIndex; PFNDOLTEXBUFFERRANGEPROC dolTexBufferRange; PFNDOLTEXTUREVIEWPROC dolTextureView; PFNDOLBINDVERTEXBUFFERPROC dolBindVertexBuffer; PFNDOLVERTEXATTRIBFORMATPROC dolVertexAttribFormat; PFNDOLVERTEXATTRIBIFORMATPROC dolVertexAttribIFormat; PFNDOLVERTEXATTRIBLFORMATPROC dolVertexAttribLFormat; PFNDOLVERTEXATTRIBBINDINGPROC dolVertexAttribBinding; PFNDOLVERTEXBINDINGDIVISORPROC dolVertexBindingDivisor; // gl_4_4 PFNDOLCLEARTEXIMAGEPROC dolClearTexImage; PFNDOLCLEARTEXSUBIMAGEPROC dolClearTexSubImage; PFNDOLBINDBUFFERSBASEPROC dolBindBuffersBase; PFNDOLBINDBUFFERSRANGEPROC dolBindBuffersRange; PFNDOLBINDTEXTURESPROC dolBindTextures; PFNDOLBINDSAMPLERSPROC dolBindSamplers; PFNDOLBINDIMAGETEXTURESPROC dolBindImageTextures; PFNDOLBINDVERTEXBUFFERSPROC dolBindVertexBuffers; // gl_4_5 PFNDOLCREATETRANSFORMFEEDBACKSPROC dolCreateTransformFeedbacks; PFNDOLTRANSFORMFEEDBACKBUFFERBASEPROC dolTransformFeedbackBufferBase; PFNDOLTRANSFORMFEEDBACKBUFFERRANGEPROC dolTransformFeedbackBufferRange; PFNDOLGETTRANSFORMFEEDBACKIVPROC dolGetTransformFeedbackiv; PFNDOLGETTRANSFORMFEEDBACKI_VPROC dolGetTransformFeedbacki_v; PFNDOLGETTRANSFORMFEEDBACKI64_VPROC dolGetTransformFeedbacki64_v; PFNDOLCREATEBUFFERSPROC dolCreateBuffers; PFNDOLNAMEDBUFFERSTORAGEPROC dolNamedBufferStorage; PFNDOLNAMEDBUFFERDATAPROC dolNamedBufferData; PFNDOLNAMEDBUFFERSUBDATAPROC dolNamedBufferSubData; PFNDOLCOPYNAMEDBUFFERSUBDATAPROC dolCopyNamedBufferSubData; PFNDOLCLEARNAMEDBUFFERDATAPROC dolClearNamedBufferData; PFNDOLCLEARNAMEDBUFFERSUBDATAPROC dolClearNamedBufferSubData; PFNDOLMAPNAMEDBUFFERPROC dolMapNamedBuffer; PFNDOLMAPNAMEDBUFFERRANGEPROC dolMapNamedBufferRange; PFNDOLUNMAPNAMEDBUFFERPROC dolUnmapNamedBuffer; PFNDOLFLUSHMAPPEDNAMEDBUFFERRANGEPROC dolFlushMappedNamedBufferRange; PFNDOLGETNAMEDBUFFERPARAMETERIVPROC dolGetNamedBufferParameteriv; PFNDOLGETNAMEDBUFFERPARAMETERI64VPROC dolGetNamedBufferParameteri64v; PFNDOLGETNAMEDBUFFERPOINTERVPROC dolGetNamedBufferPointerv; PFNDOLGETNAMEDBUFFERSUBDATAPROC dolGetNamedBufferSubData; PFNDOLCREATEFRAMEBUFFERSPROC dolCreateFramebuffers; PFNDOLNAMEDFRAMEBUFFERRENDERBUFFERPROC dolNamedFramebufferRenderbuffer; PFNDOLNAMEDFRAMEBUFFERPARAMETERIPROC dolNamedFramebufferParameteri; PFNDOLNAMEDFRAMEBUFFERTEXTUREPROC dolNamedFramebufferTexture; PFNDOLNAMEDFRAMEBUFFERTEXTURELAYERPROC dolNamedFramebufferTextureLayer; PFNDOLNAMEDFRAMEBUFFERDRAWBUFFERPROC dolNamedFramebufferDrawBuffer; PFNDOLNAMEDFRAMEBUFFERDRAWBUFFERSPROC dolNamedFramebufferDrawBuffers; PFNDOLNAMEDFRAMEBUFFERREADBUFFERPROC dolNamedFramebufferReadBuffer; PFNDOLINVALIDATENAMEDFRAMEBUFFERDATAPROC dolInvalidateNamedFramebufferData; PFNDOLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC dolInvalidateNamedFramebufferSubData; PFNDOLCLEARNAMEDFRAMEBUFFERIVPROC dolClearNamedFramebufferiv; PFNDOLCLEARNAMEDFRAMEBUFFERUIVPROC dolClearNamedFramebufferuiv; PFNDOLCLEARNAMEDFRAMEBUFFERFVPROC dolClearNamedFramebufferfv; PFNDOLCLEARNAMEDFRAMEBUFFERFIPROC dolClearNamedFramebufferfi; PFNDOLBLITNAMEDFRAMEBUFFERPROC dolBlitNamedFramebuffer; PFNDOLCHECKNAMEDFRAMEBUFFERSTATUSPROC dolCheckNamedFramebufferStatus; PFNDOLGETNAMEDFRAMEBUFFERPARAMETERIVPROC dolGetNamedFramebufferParameteriv; PFNDOLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC dolGetNamedFramebufferAttachmentParameteriv; PFNDOLCREATERENDERBUFFERSPROC dolCreateRenderbuffers; PFNDOLNAMEDRENDERBUFFERSTORAGEPROC dolNamedRenderbufferStorage; PFNDOLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC dolNamedRenderbufferStorageMultisample; PFNDOLGETNAMEDRENDERBUFFERPARAMETERIVPROC dolGetNamedRenderbufferParameteriv; PFNDOLCREATETEXTURESPROC dolCreateTextures; PFNDOLTEXTUREBUFFERPROC dolTextureBuffer; PFNDOLTEXTUREBUFFERRANGEPROC dolTextureBufferRange; PFNDOLTEXTURESTORAGE1DPROC dolTextureStorage1D; PFNDOLTEXTURESTORAGE2DPROC dolTextureStorage2D; PFNDOLTEXTURESTORAGE3DPROC dolTextureStorage3D; PFNDOLTEXTURESTORAGE2DMULTISAMPLEPROC dolTextureStorage2DMultisample; PFNDOLTEXTURESTORAGE3DMULTISAMPLEPROC dolTextureStorage3DMultisample; PFNDOLTEXTURESUBIMAGE1DPROC dolTextureSubImage1D; PFNDOLTEXTURESUBIMAGE2DPROC dolTextureSubImage2D; PFNDOLTEXTURESUBIMAGE3DPROC dolTextureSubImage3D; PFNDOLCOMPRESSEDTEXTURESUBIMAGE1DPROC dolCompressedTextureSubImage1D; PFNDOLCOMPRESSEDTEXTURESUBIMAGE2DPROC dolCompressedTextureSubImage2D; PFNDOLCOMPRESSEDTEXTURESUBIMAGE3DPROC dolCompressedTextureSubImage3D; PFNDOLCOPYTEXTURESUBIMAGE1DPROC dolCopyTextureSubImage1D; PFNDOLCOPYTEXTURESUBIMAGE2DPROC dolCopyTextureSubImage2D; PFNDOLCOPYTEXTURESUBIMAGE3DPROC dolCopyTextureSubImage3D; PFNDOLTEXTUREPARAMETERFPROC dolTextureParameterf; PFNDOLTEXTUREPARAMETERFVPROC dolTextureParameterfv; PFNDOLTEXTUREPARAMETERIPROC dolTextureParameteri; PFNDOLTEXTUREPARAMETERIIVPROC dolTextureParameterIiv; PFNDOLTEXTUREPARAMETERIUIVPROC dolTextureParameterIuiv; PFNDOLTEXTUREPARAMETERIVPROC dolTextureParameteriv; PFNDOLGENERATETEXTUREMIPMAPPROC dolGenerateTextureMipmap; PFNDOLBINDTEXTUREUNITPROC dolBindTextureUnit; PFNDOLGETTEXTUREIMAGEPROC dolGetTextureImage; PFNDOLGETCOMPRESSEDTEXTUREIMAGEPROC dolGetCompressedTextureImage; PFNDOLGETTEXTURELEVELPARAMETERFVPROC dolGetTextureLevelParameterfv; PFNDOLGETTEXTURELEVELPARAMETERIVPROC dolGetTextureLevelParameteriv; PFNDOLGETTEXTUREPARAMETERFVPROC dolGetTextureParameterfv; PFNDOLGETTEXTUREPARAMETERIIVPROC dolGetTextureParameterIiv; PFNDOLGETTEXTUREPARAMETERIUIVPROC dolGetTextureParameterIuiv; PFNDOLGETTEXTUREPARAMETERIVPROC dolGetTextureParameteriv; PFNDOLCREATEVERTEXARRAYSPROC dolCreateVertexArrays; PFNDOLDISABLEVERTEXARRAYATTRIBPROC dolDisableVertexArrayAttrib; PFNDOLENABLEVERTEXARRAYATTRIBPROC dolEnableVertexArrayAttrib; PFNDOLVERTEXARRAYELEMENTBUFFERPROC dolVertexArrayElementBuffer; PFNDOLVERTEXARRAYVERTEXBUFFERPROC dolVertexArrayVertexBuffer; PFNDOLVERTEXARRAYVERTEXBUFFERSPROC dolVertexArrayVertexBuffers; PFNDOLVERTEXARRAYATTRIBBINDINGPROC dolVertexArrayAttribBinding; PFNDOLVERTEXARRAYATTRIBFORMATPROC dolVertexArrayAttribFormat; PFNDOLVERTEXARRAYATTRIBIFORMATPROC dolVertexArrayAttribIFormat; PFNDOLVERTEXARRAYATTRIBLFORMATPROC dolVertexArrayAttribLFormat; PFNDOLVERTEXARRAYBINDINGDIVISORPROC dolVertexArrayBindingDivisor; PFNDOLGETVERTEXARRAYIVPROC dolGetVertexArrayiv; PFNDOLGETVERTEXARRAYINDEXEDIVPROC dolGetVertexArrayIndexediv; PFNDOLGETVERTEXARRAYINDEXED64IVPROC dolGetVertexArrayIndexed64iv; PFNDOLCREATESAMPLERSPROC dolCreateSamplers; PFNDOLCREATEPROGRAMPIPELINESPROC dolCreateProgramPipelines; PFNDOLCREATEQUERIESPROC dolCreateQueries; PFNDOLGETQUERYBUFFEROBJECTI64VPROC dolGetQueryBufferObjecti64v; PFNDOLGETQUERYBUFFEROBJECTIVPROC dolGetQueryBufferObjectiv; PFNDOLGETQUERYBUFFEROBJECTUI64VPROC dolGetQueryBufferObjectui64v; PFNDOLGETQUERYBUFFEROBJECTUIVPROC dolGetQueryBufferObjectuiv; PFNDOLMEMORYBARRIERBYREGIONPROC dolMemoryBarrierByRegion; PFNDOLGETTEXTURESUBIMAGEPROC dolGetTextureSubImage; PFNDOLGETCOMPRESSEDTEXTURESUBIMAGEPROC dolGetCompressedTextureSubImage; PFNDOLGETGRAPHICSRESETSTATUSPROC dolGetGraphicsResetStatus; PFNDOLGETNCOMPRESSEDTEXIMAGEPROC dolGetnCompressedTexImage; PFNDOLGETNTEXIMAGEPROC dolGetnTexImage; PFNDOLGETNUNIFORMDVPROC dolGetnUniformdv; PFNDOLGETNUNIFORMFVPROC dolGetnUniformfv; PFNDOLGETNUNIFORMIVPROC dolGetnUniformiv; PFNDOLGETNUNIFORMUIVPROC dolGetnUniformuiv; PFNDOLREADNPIXELSPROC dolReadnPixels; PFNDOLGETNMAPDVPROC dolGetnMapdv; PFNDOLGETNMAPFVPROC dolGetnMapfv; PFNDOLGETNMAPIVPROC dolGetnMapiv; PFNDOLGETNPIXELMAPFVPROC dolGetnPixelMapfv; PFNDOLGETNPIXELMAPUIVPROC dolGetnPixelMapuiv; PFNDOLGETNPIXELMAPUSVPROC dolGetnPixelMapusv; PFNDOLGETNPOLYGONSTIPPLEPROC dolGetnPolygonStipple; PFNDOLGETNCOLORTABLEPROC dolGetnColorTable; PFNDOLGETNCONVOLUTIONFILTERPROC dolGetnConvolutionFilter; PFNDOLGETNSEPARABLEFILTERPROC dolGetnSeparableFilter; PFNDOLGETNHISTOGRAMPROC dolGetnHistogram; PFNDOLGETNMINMAXPROC dolGetnMinmax; PFNDOLTEXTUREBARRIERPROC dolTextureBarrier; // ARB_uniform_buffer_object PFNDOLBINDBUFFERBASEPROC dolBindBufferBase; PFNDOLBINDBUFFERRANGEPROC dolBindBufferRange; PFNDOLGETACTIVEUNIFORMBLOCKNAMEPROC dolGetActiveUniformBlockName; PFNDOLGETACTIVEUNIFORMBLOCKIVPROC dolGetActiveUniformBlockiv; PFNDOLGETACTIVEUNIFORMNAMEPROC dolGetActiveUniformName; PFNDOLGETACTIVEUNIFORMSIVPROC dolGetActiveUniformsiv; PFNDOLGETINTEGERI_VPROC dolGetIntegeri_v; PFNDOLGETUNIFORMBLOCKINDEXPROC dolGetUniformBlockIndex; PFNDOLGETUNIFORMINDICESPROC dolGetUniformIndices; PFNDOLUNIFORMBLOCKBINDINGPROC dolUniformBlockBinding; // ARB_sampler_objects PFNDOLBINDSAMPLERPROC dolBindSampler; PFNDOLDELETESAMPLERSPROC dolDeleteSamplers; PFNDOLGENSAMPLERSPROC dolGenSamplers; PFNDOLGETSAMPLERPARAMETERIIVPROC dolGetSamplerParameterIiv; PFNDOLGETSAMPLERPARAMETERIUIVPROC dolGetSamplerParameterIuiv; PFNDOLGETSAMPLERPARAMETERFVPROC dolGetSamplerParameterfv; PFNDOLGETSAMPLERPARAMETERIVPROC dolGetSamplerParameteriv; PFNDOLISSAMPLERPROC dolIsSampler; PFNDOLSAMPLERPARAMETERIIVPROC dolSamplerParameterIiv; PFNDOLSAMPLERPARAMETERIUIVPROC dolSamplerParameterIuiv; PFNDOLSAMPLERPARAMETERFPROC dolSamplerParameterf; PFNDOLSAMPLERPARAMETERFVPROC dolSamplerParameterfv; PFNDOLSAMPLERPARAMETERIPROC dolSamplerParameteri; PFNDOLSAMPLERPARAMETERIVPROC dolSamplerParameteriv; // ARB_map_buffer_range PFNDOLFLUSHMAPPEDBUFFERRANGEPROC dolFlushMappedBufferRange; PFNDOLMAPBUFFERRANGEPROC dolMapBufferRange; // ARB_vertex_array_object PFNDOLBINDVERTEXARRAYPROC dolBindVertexArray; PFNDOLDELETEVERTEXARRAYSPROC dolDeleteVertexArrays; PFNDOLGENVERTEXARRAYSPROC dolGenVertexArrays; PFNDOLISVERTEXARRAYPROC dolIsVertexArray; // ARB_framebuffer_object PFNDOLBINDFRAMEBUFFERPROC dolBindFramebuffer; PFNDOLBINDRENDERBUFFERPROC dolBindRenderbuffer; PFNDOLBLITFRAMEBUFFERPROC dolBlitFramebuffer; PFNDOLCHECKFRAMEBUFFERSTATUSPROC dolCheckFramebufferStatus; PFNDOLDELETEFRAMEBUFFERSPROC dolDeleteFramebuffers; PFNDOLDELETERENDERBUFFERSPROC dolDeleteRenderbuffers; PFNDOLFRAMEBUFFERRENDERBUFFERPROC dolFramebufferRenderbuffer; PFNDOLFRAMEBUFFERTEXTURE1DPROC dolFramebufferTexture1D; PFNDOLFRAMEBUFFERTEXTURE2DPROC dolFramebufferTexture2D; PFNDOLFRAMEBUFFERTEXTURE3DPROC dolFramebufferTexture3D; PFNDOLFRAMEBUFFERTEXTURELAYERPROC dolFramebufferTextureLayer; PFNDOLGENFRAMEBUFFERSPROC dolGenFramebuffers; PFNDOLGENRENDERBUFFERSPROC dolGenRenderbuffers; PFNDOLGENERATEMIPMAPPROC dolGenerateMipmap; PFNDOLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC dolGetFramebufferAttachmentParameteriv; PFNDOLGETRENDERBUFFERPARAMETERIVPROC dolGetRenderbufferParameteriv; PFNDOLISFRAMEBUFFERPROC dolIsFramebuffer; PFNDOLISRENDERBUFFERPROC dolIsRenderbuffer; PFNDOLRENDERBUFFERSTORAGEPROC dolRenderbufferStorage; PFNDOLRENDERBUFFERSTORAGEMULTISAMPLEPROC dolRenderbufferStorageMultisample; // ARB_get_program_binary PFNDOLGETPROGRAMBINARYPROC dolGetProgramBinary; PFNDOLPROGRAMBINARYPROC dolProgramBinary; PFNDOLPROGRAMPARAMETERIPROC dolProgramParameteri; // ARB_sync PFNDOLCLIENTWAITSYNCPROC dolClientWaitSync; PFNDOLDELETESYNCPROC dolDeleteSync; PFNDOLFENCESYNCPROC dolFenceSync; PFNDOLGETINTEGER64VPROC dolGetInteger64v; PFNDOLGETSYNCIVPROC dolGetSynciv; PFNDOLISSYNCPROC dolIsSync; PFNDOLWAITSYNCPROC dolWaitSync; // ARB_texture_multisample PFNDOLTEXIMAGE2DMULTISAMPLEPROC dolTexImage2DMultisample; PFNDOLTEXIMAGE3DMULTISAMPLEPROC dolTexImage3DMultisample; PFNDOLGETMULTISAMPLEFVPROC dolGetMultisamplefv; PFNDOLSAMPLEMASKIPROC dolSampleMaski; // ARB_texture_storage_multisample PFNDOLTEXSTORAGE2DMULTISAMPLEPROC dolTexStorage2DMultisample; PFNDOLTEXSTORAGE3DMULTISAMPLEPROC dolTexStorage3DMultisample; // ARB_ES2_compatibility PFNDOLCLEARDEPTHFPROC dolClearDepthf; PFNDOLDEPTHRANGEFPROC dolDepthRangef; PFNDOLGETSHADERPRECISIONFORMATPROC dolGetShaderPrecisionFormat; PFNDOLRELEASESHADERCOMPILERPROC dolReleaseShaderCompiler; PFNDOLSHADERBINARYPROC dolShaderBinary; // NV_primitive_restart PFNDOLPRIMITIVERESTARTINDEXNVPROC dolPrimitiveRestartIndexNV; PFNDOLPRIMITIVERESTARTNVPROC dolPrimitiveRestartNV; // ARB_blend_func_extended PFNDOLBINDFRAGDATALOCATIONINDEXEDPROC dolBindFragDataLocationIndexed; PFNDOLGETFRAGDATAINDEXPROC dolGetFragDataIndex; // ARB_viewport_array PFNDOLDEPTHRANGEARRAYVPROC dolDepthRangeArrayv; PFNDOLDEPTHRANGEINDEXEDPROC dolDepthRangeIndexed; PFNDOLGETDOUBLEI_VPROC dolGetDoublei_v; PFNDOLGETFLOATI_VPROC dolGetFloati_v; PFNDOLSCISSORARRAYVPROC dolScissorArrayv; PFNDOLSCISSORINDEXEDPROC dolScissorIndexed; PFNDOLSCISSORINDEXEDVPROC dolScissorIndexedv; PFNDOLVIEWPORTARRAYVPROC dolViewportArrayv; PFNDOLVIEWPORTINDEXEDFPROC dolViewportIndexedf; PFNDOLVIEWPORTINDEXEDFVPROC dolViewportIndexedfv; // ARB_draw_elements_base_vertex PFNDOLDRAWELEMENTSBASEVERTEXPROC dolDrawElementsBaseVertex; PFNDOLDRAWELEMENTSINSTANCEDBASEVERTEXPROC dolDrawElementsInstancedBaseVertex; PFNDOLDRAWRANGEELEMENTSBASEVERTEXPROC dolDrawRangeElementsBaseVertex; PFNDOLMULTIDRAWELEMENTSBASEVERTEXPROC dolMultiDrawElementsBaseVertex; // ARB_sample_shading PFNDOLMINSAMPLESHADINGARBPROC dolMinSampleShading; // ARB_debug_output PFNDOLDEBUGMESSAGECALLBACKARBPROC dolDebugMessageCallbackARB; PFNDOLDEBUGMESSAGECONTROLARBPROC dolDebugMessageControlARB; PFNDOLDEBUGMESSAGEINSERTARBPROC dolDebugMessageInsertARB; PFNDOLGETDEBUGMESSAGELOGARBPROC dolGetDebugMessageLogARB; // KHR_debug PFNDOLDEBUGMESSAGECALLBACKPROC dolDebugMessageCallback; PFNDOLDEBUGMESSAGECONTROLPROC dolDebugMessageControl; PFNDOLDEBUGMESSAGEINSERTPROC dolDebugMessageInsert; PFNDOLGETDEBUGMESSAGELOGPROC dolGetDebugMessageLog; PFNDOLGETOBJECTLABELPROC dolGetObjectLabel; PFNDOLGETOBJECTPTRLABELPROC dolGetObjectPtrLabel; PFNDOLOBJECTLABELPROC dolObjectLabel; PFNDOLOBJECTPTRLABELPROC dolObjectPtrLabel; PFNDOLPOPDEBUGGROUPPROC dolPopDebugGroup; PFNDOLPUSHDEBUGGROUPPROC dolPushDebugGroup; // ARB_buffer_storage PFNDOLBUFFERSTORAGEPROC dolBufferStorage; // GL_NV_occlusion_query_samples PFNDOLGENOCCLUSIONQUERIESNVPROC dolGenOcclusionQueriesNV; PFNDOLDELETEOCCLUSIONQUERIESNVPROC dolDeleteOcclusionQueriesNV; PFNDOLISOCCLUSIONQUERYNVPROC dolIsOcclusionQueryNV; PFNDOLBEGINOCCLUSIONQUERYNVPROC dolBeginOcclusionQueryNV; PFNDOLENDOCCLUSIONQUERYNVPROC dolEndOcclusionQueryNV; PFNDOLGETOCCLUSIONQUERYIVNVPROC dolGetOcclusionQueryivNV; PFNDOLGETOCCLUSIONQUERYUIVNVPROC dolGetOcclusionQueryuivNV; // ARB_clip_control PFNDOLCLIPCONTROLPROC dolClipControl; // ARB_copy_image PFNDOLCOPYIMAGESUBDATAPROC dolCopyImageSubData; // ARB_shader_storage_buffer_object PFNDOLSHADERSTORAGEBLOCKBINDINGPROC dolShaderStorageBlockBinding; // Creates a GLFunc object that requires a feature #define GLFUNC_REQUIRES(x, y) { (void**)&x, #x, y } // Creates a GLFunc object with a different function suffix // For when we want to use the same function pointer, but different function name #define GLFUNC_SUFFIX(x, y, z) { (void**)&x, #x #y, z } // Creates a GLFunc object that should always be able to get grabbed // Used for Desktop OpenGL functions that should /always/ be provided. // aka GL 1.1/1.2/1.3/1.4 #define GLFUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL" } // Creates a GLFunc object that should be able to get grabbed // on both GL and ES #define GL_ES_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_2" } // Creates a GLFunc object that should be able to get grabbed // on both GL and ES 3.0 #define GL_ES3_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_3" } // Creates a GLFunc object that should be able to get grabbed // on both GL and ES 3.2 #define GL_ES32_FUNC_ALWAYS_REQUIRED(x) { (void**)&x, #x, "VERSION_GL |VERSION_GLES_3_2" } struct GLFunc { void** function_ptr; const std::string function_name; const std::string requirements; }; const GLFunc gl_function_array[] = { // gl_1_1 GLFUNC_ALWAYS_REQUIRED(glClearIndex), GLFUNC_ALWAYS_REQUIRED(glIndexMask), GLFUNC_ALWAYS_REQUIRED(glAlphaFunc), GLFUNC_ALWAYS_REQUIRED(glLogicOp), GLFUNC_ALWAYS_REQUIRED(glPointSize), GLFUNC_ALWAYS_REQUIRED(glLineStipple), GLFUNC_ALWAYS_REQUIRED(glPolygonMode), GLFUNC_ALWAYS_REQUIRED(glPolygonStipple), GLFUNC_ALWAYS_REQUIRED(glGetPolygonStipple), GLFUNC_ALWAYS_REQUIRED(glEdgeFlag), GLFUNC_ALWAYS_REQUIRED(glEdgeFlagv), GLFUNC_ALWAYS_REQUIRED(glClipPlane), GLFUNC_ALWAYS_REQUIRED(glGetClipPlane), GLFUNC_ALWAYS_REQUIRED(glDrawBuffer), GLFUNC_ALWAYS_REQUIRED(glEnableClientState), GLFUNC_ALWAYS_REQUIRED(glDisableClientState), GLFUNC_ALWAYS_REQUIRED(glGetDoublev), GLFUNC_ALWAYS_REQUIRED(glPushAttrib), GLFUNC_ALWAYS_REQUIRED(glPopAttrib), GLFUNC_ALWAYS_REQUIRED(glPushClientAttrib), GLFUNC_ALWAYS_REQUIRED(glPopClientAttrib), GLFUNC_ALWAYS_REQUIRED(glRenderMode), GLFUNC_ALWAYS_REQUIRED(glClearDepth), GLFUNC_ALWAYS_REQUIRED(glDepthRange), GLFUNC_ALWAYS_REQUIRED(glClearAccum), GLFUNC_ALWAYS_REQUIRED(glAccum), GLFUNC_ALWAYS_REQUIRED(glMatrixMode), GLFUNC_ALWAYS_REQUIRED(glOrtho), GLFUNC_ALWAYS_REQUIRED(glFrustum), GLFUNC_ALWAYS_REQUIRED(glPushMatrix), GLFUNC_ALWAYS_REQUIRED(glPopMatrix), GLFUNC_ALWAYS_REQUIRED(glLoadIdentity), GLFUNC_ALWAYS_REQUIRED(glLoadMatrixd), GLFUNC_ALWAYS_REQUIRED(glLoadMatrixf), GLFUNC_ALWAYS_REQUIRED(glMultMatrixd), GLFUNC_ALWAYS_REQUIRED(glMultMatrixf), GLFUNC_ALWAYS_REQUIRED(glRotated), GLFUNC_ALWAYS_REQUIRED(glRotatef), GLFUNC_ALWAYS_REQUIRED(glScaled), GLFUNC_ALWAYS_REQUIRED(glScalef), GLFUNC_ALWAYS_REQUIRED(glTranslated), GLFUNC_ALWAYS_REQUIRED(glTranslatef), GLFUNC_ALWAYS_REQUIRED(glIsList), GLFUNC_ALWAYS_REQUIRED(glDeleteLists), GLFUNC_ALWAYS_REQUIRED(glGenLists), GLFUNC_ALWAYS_REQUIRED(glNewList), GLFUNC_ALWAYS_REQUIRED(glEndList), GLFUNC_ALWAYS_REQUIRED(glCallList), GLFUNC_ALWAYS_REQUIRED(glCallLists), GLFUNC_ALWAYS_REQUIRED(glListBase), GLFUNC_ALWAYS_REQUIRED(glBegin), GLFUNC_ALWAYS_REQUIRED(glEnd), GLFUNC_ALWAYS_REQUIRED(glVertex2d), GLFUNC_ALWAYS_REQUIRED(glVertex2f), GLFUNC_ALWAYS_REQUIRED(glVertex2i), GLFUNC_ALWAYS_REQUIRED(glVertex2s), GLFUNC_ALWAYS_REQUIRED(glVertex3d), GLFUNC_ALWAYS_REQUIRED(glVertex3f), GLFUNC_ALWAYS_REQUIRED(glVertex3i), GLFUNC_ALWAYS_REQUIRED(glVertex3s), GLFUNC_ALWAYS_REQUIRED(glVertex4d), GLFUNC_ALWAYS_REQUIRED(glVertex4f), GLFUNC_ALWAYS_REQUIRED(glVertex4i), GLFUNC_ALWAYS_REQUIRED(glVertex4s), GLFUNC_ALWAYS_REQUIRED(glVertex2dv), GLFUNC_ALWAYS_REQUIRED(glVertex2fv), GLFUNC_ALWAYS_REQUIRED(glVertex2iv), GLFUNC_ALWAYS_REQUIRED(glVertex2sv), GLFUNC_ALWAYS_REQUIRED(glVertex3dv), GLFUNC_ALWAYS_REQUIRED(glVertex3fv), GLFUNC_ALWAYS_REQUIRED(glVertex3iv), GLFUNC_ALWAYS_REQUIRED(glVertex3sv), GLFUNC_ALWAYS_REQUIRED(glVertex4dv), GLFUNC_ALWAYS_REQUIRED(glVertex4fv), GLFUNC_ALWAYS_REQUIRED(glVertex4iv), GLFUNC_ALWAYS_REQUIRED(glVertex4sv), GLFUNC_ALWAYS_REQUIRED(glNormal3b), GLFUNC_ALWAYS_REQUIRED(glNormal3d), GLFUNC_ALWAYS_REQUIRED(glNormal3f), GLFUNC_ALWAYS_REQUIRED(glNormal3i), GLFUNC_ALWAYS_REQUIRED(glNormal3s), GLFUNC_ALWAYS_REQUIRED(glNormal3bv), GLFUNC_ALWAYS_REQUIRED(glNormal3dv), GLFUNC_ALWAYS_REQUIRED(glNormal3fv), GLFUNC_ALWAYS_REQUIRED(glNormal3iv), GLFUNC_ALWAYS_REQUIRED(glNormal3sv), GLFUNC_ALWAYS_REQUIRED(glIndexd), GLFUNC_ALWAYS_REQUIRED(glIndexf), GLFUNC_ALWAYS_REQUIRED(glIndexi), GLFUNC_ALWAYS_REQUIRED(glIndexs), GLFUNC_ALWAYS_REQUIRED(glIndexub), GLFUNC_ALWAYS_REQUIRED(glIndexdv), GLFUNC_ALWAYS_REQUIRED(glIndexfv), GLFUNC_ALWAYS_REQUIRED(glIndexiv), GLFUNC_ALWAYS_REQUIRED(glIndexsv), GLFUNC_ALWAYS_REQUIRED(glIndexubv), GLFUNC_ALWAYS_REQUIRED(glColor3b), GLFUNC_ALWAYS_REQUIRED(glColor3d), GLFUNC_ALWAYS_REQUIRED(glColor3f), GLFUNC_ALWAYS_REQUIRED(glColor3i), GLFUNC_ALWAYS_REQUIRED(glColor3s), GLFUNC_ALWAYS_REQUIRED(glColor3ub), GLFUNC_ALWAYS_REQUIRED(glColor3ui), GLFUNC_ALWAYS_REQUIRED(glColor3us), GLFUNC_ALWAYS_REQUIRED(glColor4b), GLFUNC_ALWAYS_REQUIRED(glColor4d), GLFUNC_ALWAYS_REQUIRED(glColor4f), GLFUNC_ALWAYS_REQUIRED(glColor4i), GLFUNC_ALWAYS_REQUIRED(glColor4s), GLFUNC_ALWAYS_REQUIRED(glColor4ub), GLFUNC_ALWAYS_REQUIRED(glColor4ui), GLFUNC_ALWAYS_REQUIRED(glColor4us), GLFUNC_ALWAYS_REQUIRED(glColor3bv), GLFUNC_ALWAYS_REQUIRED(glColor3dv), GLFUNC_ALWAYS_REQUIRED(glColor3fv), GLFUNC_ALWAYS_REQUIRED(glColor3iv), GLFUNC_ALWAYS_REQUIRED(glColor3sv), GLFUNC_ALWAYS_REQUIRED(glColor3ubv), GLFUNC_ALWAYS_REQUIRED(glColor3uiv), GLFUNC_ALWAYS_REQUIRED(glColor3usv), GLFUNC_ALWAYS_REQUIRED(glColor4bv), GLFUNC_ALWAYS_REQUIRED(glColor4dv), GLFUNC_ALWAYS_REQUIRED(glColor4fv), GLFUNC_ALWAYS_REQUIRED(glColor4iv), GLFUNC_ALWAYS_REQUIRED(glColor4sv), GLFUNC_ALWAYS_REQUIRED(glColor4ubv), GLFUNC_ALWAYS_REQUIRED(glColor4uiv), GLFUNC_ALWAYS_REQUIRED(glColor4usv), GLFUNC_ALWAYS_REQUIRED(glTexCoord1d), GLFUNC_ALWAYS_REQUIRED(glTexCoord1f), GLFUNC_ALWAYS_REQUIRED(glTexCoord1i), GLFUNC_ALWAYS_REQUIRED(glTexCoord1s), GLFUNC_ALWAYS_REQUIRED(glTexCoord2d), GLFUNC_ALWAYS_REQUIRED(glTexCoord2f), GLFUNC_ALWAYS_REQUIRED(glTexCoord2i), GLFUNC_ALWAYS_REQUIRED(glTexCoord2s), GLFUNC_ALWAYS_REQUIRED(glTexCoord3d), GLFUNC_ALWAYS_REQUIRED(glTexCoord3f), GLFUNC_ALWAYS_REQUIRED(glTexCoord3i), GLFUNC_ALWAYS_REQUIRED(glTexCoord3s), GLFUNC_ALWAYS_REQUIRED(glTexCoord4d), GLFUNC_ALWAYS_REQUIRED(glTexCoord4f), GLFUNC_ALWAYS_REQUIRED(glTexCoord4i), GLFUNC_ALWAYS_REQUIRED(glTexCoord4s), GLFUNC_ALWAYS_REQUIRED(glTexCoord1dv), GLFUNC_ALWAYS_REQUIRED(glTexCoord1fv), GLFUNC_ALWAYS_REQUIRED(glTexCoord1iv), GLFUNC_ALWAYS_REQUIRED(glTexCoord1sv), GLFUNC_ALWAYS_REQUIRED(glTexCoord2dv), GLFUNC_ALWAYS_REQUIRED(glTexCoord2fv), GLFUNC_ALWAYS_REQUIRED(glTexCoord2iv), GLFUNC_ALWAYS_REQUIRED(glTexCoord2sv), GLFUNC_ALWAYS_REQUIRED(glTexCoord3dv), GLFUNC_ALWAYS_REQUIRED(glTexCoord3fv), GLFUNC_ALWAYS_REQUIRED(glTexCoord3iv), GLFUNC_ALWAYS_REQUIRED(glTexCoord3sv), GLFUNC_ALWAYS_REQUIRED(glTexCoord4dv), GLFUNC_ALWAYS_REQUIRED(glTexCoord4fv), GLFUNC_ALWAYS_REQUIRED(glTexCoord4iv), GLFUNC_ALWAYS_REQUIRED(glTexCoord4sv), GLFUNC_ALWAYS_REQUIRED(glRasterPos2d), GLFUNC_ALWAYS_REQUIRED(glRasterPos2f), GLFUNC_ALWAYS_REQUIRED(glRasterPos2i), GLFUNC_ALWAYS_REQUIRED(glRasterPos2s), GLFUNC_ALWAYS_REQUIRED(glRasterPos3d), GLFUNC_ALWAYS_REQUIRED(glRasterPos3f), GLFUNC_ALWAYS_REQUIRED(glRasterPos3i), GLFUNC_ALWAYS_REQUIRED(glRasterPos3s), GLFUNC_ALWAYS_REQUIRED(glRasterPos4d), GLFUNC_ALWAYS_REQUIRED(glRasterPos4f), GLFUNC_ALWAYS_REQUIRED(glRasterPos4i), GLFUNC_ALWAYS_REQUIRED(glRasterPos4s), GLFUNC_ALWAYS_REQUIRED(glRasterPos2dv), GLFUNC_ALWAYS_REQUIRED(glRasterPos2fv), GLFUNC_ALWAYS_REQUIRED(glRasterPos2iv), GLFUNC_ALWAYS_REQUIRED(glRasterPos2sv), GLFUNC_ALWAYS_REQUIRED(glRasterPos3dv), GLFUNC_ALWAYS_REQUIRED(glRasterPos3fv), GLFUNC_ALWAYS_REQUIRED(glRasterPos3iv), GLFUNC_ALWAYS_REQUIRED(glRasterPos3sv), GLFUNC_ALWAYS_REQUIRED(glRasterPos4dv), GLFUNC_ALWAYS_REQUIRED(glRasterPos4fv), GLFUNC_ALWAYS_REQUIRED(glRasterPos4iv), GLFUNC_ALWAYS_REQUIRED(glRasterPos4sv), GLFUNC_ALWAYS_REQUIRED(glRectd), GLFUNC_ALWAYS_REQUIRED(glRectf), GLFUNC_ALWAYS_REQUIRED(glRecti), GLFUNC_ALWAYS_REQUIRED(glRects), GLFUNC_ALWAYS_REQUIRED(glRectdv), GLFUNC_ALWAYS_REQUIRED(glRectfv), GLFUNC_ALWAYS_REQUIRED(glRectiv), GLFUNC_ALWAYS_REQUIRED(glRectsv), GLFUNC_ALWAYS_REQUIRED(glVertexPointer), GLFUNC_ALWAYS_REQUIRED(glNormalPointer), GLFUNC_ALWAYS_REQUIRED(glColorPointer), GLFUNC_ALWAYS_REQUIRED(glIndexPointer), GLFUNC_ALWAYS_REQUIRED(glTexCoordPointer), GLFUNC_ALWAYS_REQUIRED(glEdgeFlagPointer), GLFUNC_ALWAYS_REQUIRED(glArrayElement), GLFUNC_ALWAYS_REQUIRED(glInterleavedArrays), GLFUNC_ALWAYS_REQUIRED(glShadeModel), GLFUNC_ALWAYS_REQUIRED(glLightf), GLFUNC_ALWAYS_REQUIRED(glLighti), GLFUNC_ALWAYS_REQUIRED(glLightfv), GLFUNC_ALWAYS_REQUIRED(glLightiv), GLFUNC_ALWAYS_REQUIRED(glGetLightfv), GLFUNC_ALWAYS_REQUIRED(glGetLightiv), GLFUNC_ALWAYS_REQUIRED(glLightModelf), GLFUNC_ALWAYS_REQUIRED(glLightModeli), GLFUNC_ALWAYS_REQUIRED(glLightModelfv), GLFUNC_ALWAYS_REQUIRED(glLightModeliv), GLFUNC_ALWAYS_REQUIRED(glMaterialf), GLFUNC_ALWAYS_REQUIRED(glMateriali), GLFUNC_ALWAYS_REQUIRED(glMaterialfv), GLFUNC_ALWAYS_REQUIRED(glMaterialiv), GLFUNC_ALWAYS_REQUIRED(glGetMaterialfv), GLFUNC_ALWAYS_REQUIRED(glGetMaterialiv), GLFUNC_ALWAYS_REQUIRED(glColorMaterial), GLFUNC_ALWAYS_REQUIRED(glPixelZoom), GLFUNC_ALWAYS_REQUIRED(glPixelStoref), GLFUNC_ALWAYS_REQUIRED(glPixelTransferf), GLFUNC_ALWAYS_REQUIRED(glPixelTransferi), GLFUNC_ALWAYS_REQUIRED(glPixelMapfv), GLFUNC_ALWAYS_REQUIRED(glPixelMapuiv), GLFUNC_ALWAYS_REQUIRED(glPixelMapusv), GLFUNC_ALWAYS_REQUIRED(glGetPixelMapfv), GLFUNC_ALWAYS_REQUIRED(glGetPixelMapuiv), GLFUNC_ALWAYS_REQUIRED(glGetPixelMapusv), GLFUNC_ALWAYS_REQUIRED(glBitmap), GLFUNC_ALWAYS_REQUIRED(glDrawPixels), GLFUNC_ALWAYS_REQUIRED(glCopyPixels), GLFUNC_ALWAYS_REQUIRED(glTexGend), GLFUNC_ALWAYS_REQUIRED(glTexGenf), GLFUNC_ALWAYS_REQUIRED(glTexGeni), GLFUNC_ALWAYS_REQUIRED(glTexGendv), GLFUNC_ALWAYS_REQUIRED(glTexGenfv), GLFUNC_ALWAYS_REQUIRED(glTexGeniv), GLFUNC_ALWAYS_REQUIRED(glGetTexGendv), GLFUNC_ALWAYS_REQUIRED(glGetTexGenfv), GLFUNC_ALWAYS_REQUIRED(glGetTexGeniv), GLFUNC_ALWAYS_REQUIRED(glTexEnvf), GLFUNC_ALWAYS_REQUIRED(glTexEnvi), GLFUNC_ALWAYS_REQUIRED(glTexEnvfv), GLFUNC_ALWAYS_REQUIRED(glTexEnviv), GLFUNC_ALWAYS_REQUIRED(glGetTexEnvfv), GLFUNC_ALWAYS_REQUIRED(glGetTexEnviv), GLFUNC_ALWAYS_REQUIRED(glGetTexLevelParameterfv), GLFUNC_ALWAYS_REQUIRED(glGetTexLevelParameteriv), GLFUNC_ALWAYS_REQUIRED(glTexImage1D), GLFUNC_ALWAYS_REQUIRED(glGetTexImage), GLFUNC_ALWAYS_REQUIRED(glPrioritizeTextures), GLFUNC_ALWAYS_REQUIRED(glAreTexturesResident), GLFUNC_ALWAYS_REQUIRED(glTexSubImage1D), GLFUNC_ALWAYS_REQUIRED(glCopyTexImage1D), GLFUNC_ALWAYS_REQUIRED(glCopyTexSubImage1D), GLFUNC_ALWAYS_REQUIRED(glMap1d), GLFUNC_ALWAYS_REQUIRED(glMap1f), GLFUNC_ALWAYS_REQUIRED(glMap2d), GLFUNC_ALWAYS_REQUIRED(glMap2f), GLFUNC_ALWAYS_REQUIRED(glGetMapdv), GLFUNC_ALWAYS_REQUIRED(glGetMapfv), GLFUNC_ALWAYS_REQUIRED(glGetMapiv), GLFUNC_ALWAYS_REQUIRED(glEvalCoord1d), GLFUNC_ALWAYS_REQUIRED(glEvalCoord1f), GLFUNC_ALWAYS_REQUIRED(glEvalCoord1dv), GLFUNC_ALWAYS_REQUIRED(glEvalCoord1fv), GLFUNC_ALWAYS_REQUIRED(glEvalCoord2d), GLFUNC_ALWAYS_REQUIRED(glEvalCoord2f), GLFUNC_ALWAYS_REQUIRED(glEvalCoord2dv), GLFUNC_ALWAYS_REQUIRED(glEvalCoord2fv), GLFUNC_ALWAYS_REQUIRED(glMapGrid1d), GLFUNC_ALWAYS_REQUIRED(glMapGrid1f), GLFUNC_ALWAYS_REQUIRED(glMapGrid2d), GLFUNC_ALWAYS_REQUIRED(glMapGrid2f), GLFUNC_ALWAYS_REQUIRED(glEvalPoint1), GLFUNC_ALWAYS_REQUIRED(glEvalPoint2), GLFUNC_ALWAYS_REQUIRED(glEvalMesh1), GLFUNC_ALWAYS_REQUIRED(glEvalMesh2), GLFUNC_ALWAYS_REQUIRED(glFogf), GLFUNC_ALWAYS_REQUIRED(glFogi), GLFUNC_ALWAYS_REQUIRED(glFogfv), GLFUNC_ALWAYS_REQUIRED(glFogiv), GLFUNC_ALWAYS_REQUIRED(glFeedbackBuffer), GLFUNC_ALWAYS_REQUIRED(glPassThrough), GLFUNC_ALWAYS_REQUIRED(glSelectBuffer), GLFUNC_ALWAYS_REQUIRED(glInitNames), GLFUNC_ALWAYS_REQUIRED(glLoadName), GLFUNC_ALWAYS_REQUIRED(glPushName), GLFUNC_ALWAYS_REQUIRED(glPopName), GL_ES_FUNC_ALWAYS_REQUIRED(glTexImage2D), GL_ES_FUNC_ALWAYS_REQUIRED(glClearColor), GL_ES_FUNC_ALWAYS_REQUIRED(glClear), GL_ES_FUNC_ALWAYS_REQUIRED(glColorMask), GL_ES_FUNC_ALWAYS_REQUIRED(glBlendFunc), GL_ES_FUNC_ALWAYS_REQUIRED(glCullFace), GL_ES_FUNC_ALWAYS_REQUIRED(glFrontFace), GL_ES_FUNC_ALWAYS_REQUIRED(glLineWidth), GL_ES_FUNC_ALWAYS_REQUIRED(glPolygonOffset), GL_ES_FUNC_ALWAYS_REQUIRED(glScissor), GL_ES_FUNC_ALWAYS_REQUIRED(glEnable), GL_ES_FUNC_ALWAYS_REQUIRED(glDisable), GL_ES_FUNC_ALWAYS_REQUIRED(glIsEnabled), GL_ES_FUNC_ALWAYS_REQUIRED(glGetBooleanv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetFloatv), GL_ES_FUNC_ALWAYS_REQUIRED(glFinish), GL_ES_FUNC_ALWAYS_REQUIRED(glFlush), GL_ES_FUNC_ALWAYS_REQUIRED(glHint), GL_ES_FUNC_ALWAYS_REQUIRED(glDepthFunc), GL_ES_FUNC_ALWAYS_REQUIRED(glDepthMask), GL_ES_FUNC_ALWAYS_REQUIRED(glViewport), GL_ES_FUNC_ALWAYS_REQUIRED(glDrawArrays), GL_ES_FUNC_ALWAYS_REQUIRED(glDrawElements), GL_ES_FUNC_ALWAYS_REQUIRED(glPixelStorei), GL_ES_FUNC_ALWAYS_REQUIRED(glReadPixels), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilFunc), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilMask), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilOp), GL_ES_FUNC_ALWAYS_REQUIRED(glClearStencil), GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameterf), GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameteri), GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameterfv), GL_ES_FUNC_ALWAYS_REQUIRED(glTexParameteriv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetTexParameterfv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetTexParameteriv), GL_ES_FUNC_ALWAYS_REQUIRED(glGenTextures), GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteTextures), GL_ES_FUNC_ALWAYS_REQUIRED(glBindTexture), GL_ES_FUNC_ALWAYS_REQUIRED(glIsTexture), GL_ES_FUNC_ALWAYS_REQUIRED(glTexSubImage2D), GL_ES_FUNC_ALWAYS_REQUIRED(glCopyTexImage2D), GL_ES_FUNC_ALWAYS_REQUIRED(glCopyTexSubImage2D), GL_ES3_FUNC_ALWAYS_REQUIRED(glReadBuffer), GL_ES32_FUNC_ALWAYS_REQUIRED(glGetPointerv), // gl_1_2 GL_ES3_FUNC_ALWAYS_REQUIRED(glCopyTexSubImage3D), GL_ES3_FUNC_ALWAYS_REQUIRED(glDrawRangeElements), GL_ES3_FUNC_ALWAYS_REQUIRED(glTexImage3D), GL_ES3_FUNC_ALWAYS_REQUIRED(glTexSubImage3D), // gl_1_3 GLFUNC_ALWAYS_REQUIRED(glClientActiveTexture), GLFUNC_ALWAYS_REQUIRED(glCompressedTexImage1D), GLFUNC_ALWAYS_REQUIRED(glCompressedTexSubImage1D), GLFUNC_ALWAYS_REQUIRED(glGetCompressedTexImage), GLFUNC_ALWAYS_REQUIRED(glLoadTransposeMatrixd), GLFUNC_ALWAYS_REQUIRED(glLoadTransposeMatrixf), GLFUNC_ALWAYS_REQUIRED(glMultTransposeMatrixd), GLFUNC_ALWAYS_REQUIRED(glMultTransposeMatrixf), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1d), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1dv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1f), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1fv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1i), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1iv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1s), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord1sv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2d), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2dv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2f), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2fv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2i), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2iv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2s), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord2sv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3d), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3dv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3f), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3fv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3i), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3iv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3s), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord3sv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4d), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4dv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4f), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4fv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4i), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4iv), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4s), GLFUNC_ALWAYS_REQUIRED(glMultiTexCoord4sv), GL_ES_FUNC_ALWAYS_REQUIRED(glSampleCoverage), GL_ES_FUNC_ALWAYS_REQUIRED(glActiveTexture), GL_ES_FUNC_ALWAYS_REQUIRED(glCompressedTexImage2D), GL_ES_FUNC_ALWAYS_REQUIRED(glCompressedTexSubImage2D), GL_ES3_FUNC_ALWAYS_REQUIRED(glCompressedTexImage3D), GL_ES3_FUNC_ALWAYS_REQUIRED(glCompressedTexSubImage3D), // gl_1_4 GLFUNC_ALWAYS_REQUIRED(glFogCoordPointer), GLFUNC_ALWAYS_REQUIRED(glFogCoordd), GLFUNC_ALWAYS_REQUIRED(glFogCoorddv), GLFUNC_ALWAYS_REQUIRED(glFogCoordf), GLFUNC_ALWAYS_REQUIRED(glFogCoordfv), GLFUNC_ALWAYS_REQUIRED(glMultiDrawArrays), GLFUNC_ALWAYS_REQUIRED(glMultiDrawElements), GLFUNC_ALWAYS_REQUIRED(glPointParameterf), GLFUNC_ALWAYS_REQUIRED(glPointParameterfv), GLFUNC_ALWAYS_REQUIRED(glPointParameteri), GLFUNC_ALWAYS_REQUIRED(glPointParameteriv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3b), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3bv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3d), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3dv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3f), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3fv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3i), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3iv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3s), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3sv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ub), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ubv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3ui), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3uiv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3us), GLFUNC_ALWAYS_REQUIRED(glSecondaryColor3usv), GLFUNC_ALWAYS_REQUIRED(glSecondaryColorPointer), GLFUNC_ALWAYS_REQUIRED(glWindowPos2d), GLFUNC_ALWAYS_REQUIRED(glWindowPos2dv), GLFUNC_ALWAYS_REQUIRED(glWindowPos2f), GLFUNC_ALWAYS_REQUIRED(glWindowPos2fv), GLFUNC_ALWAYS_REQUIRED(glWindowPos2i), GLFUNC_ALWAYS_REQUIRED(glWindowPos2iv), GLFUNC_ALWAYS_REQUIRED(glWindowPos2s), GLFUNC_ALWAYS_REQUIRED(glWindowPos2sv), GLFUNC_ALWAYS_REQUIRED(glWindowPos3d), GLFUNC_ALWAYS_REQUIRED(glWindowPos3dv), GLFUNC_ALWAYS_REQUIRED(glWindowPos3f), GLFUNC_ALWAYS_REQUIRED(glWindowPos3fv), GLFUNC_ALWAYS_REQUIRED(glWindowPos3i), GLFUNC_ALWAYS_REQUIRED(glWindowPos3iv), GLFUNC_ALWAYS_REQUIRED(glWindowPos3s), GLFUNC_ALWAYS_REQUIRED(glWindowPos3sv), GL_ES_FUNC_ALWAYS_REQUIRED(glBlendColor), GL_ES_FUNC_ALWAYS_REQUIRED(glBlendEquation), GL_ES_FUNC_ALWAYS_REQUIRED(glBlendFuncSeparate), // gl_1_5 GLFUNC_ALWAYS_REQUIRED(glGetBufferSubData), GLFUNC_ALWAYS_REQUIRED(glGetQueryObjectiv), GLFUNC_ALWAYS_REQUIRED(glMapBuffer), GL_ES_FUNC_ALWAYS_REQUIRED(glBindBuffer), GL_ES_FUNC_ALWAYS_REQUIRED(glBufferData), GL_ES_FUNC_ALWAYS_REQUIRED(glBufferSubData), GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteBuffers), GL_ES_FUNC_ALWAYS_REQUIRED(glGenBuffers), GL_ES_FUNC_ALWAYS_REQUIRED(glGetBufferParameteriv), GL_ES_FUNC_ALWAYS_REQUIRED(glIsBuffer), GL_ES3_FUNC_ALWAYS_REQUIRED(glBeginQuery), GL_ES3_FUNC_ALWAYS_REQUIRED(glDeleteQueries), GL_ES3_FUNC_ALWAYS_REQUIRED(glEndQuery), GL_ES3_FUNC_ALWAYS_REQUIRED(glGenQueries), GL_ES3_FUNC_ALWAYS_REQUIRED(glIsQuery), GL_ES3_FUNC_ALWAYS_REQUIRED(glGetQueryiv), GL_ES3_FUNC_ALWAYS_REQUIRED(glGetQueryObjectuiv), GL_ES3_FUNC_ALWAYS_REQUIRED(glGetBufferPointerv), GL_ES3_FUNC_ALWAYS_REQUIRED(glUnmapBuffer), // gl_2_0 GLFUNC_ALWAYS_REQUIRED(glGetVertexAttribdv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1d), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1dv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1s), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib1sv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2d), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2dv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2s), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib2sv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3d), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3dv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3s), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib3sv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nbv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Niv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nsv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nub), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nubv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nuiv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4Nusv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4bv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4d), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4dv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4iv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4s), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4sv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4ubv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4uiv), GLFUNC_ALWAYS_REQUIRED(glVertexAttrib4usv), GL_ES_FUNC_ALWAYS_REQUIRED(glAttachShader), GL_ES_FUNC_ALWAYS_REQUIRED(glBindAttribLocation), GL_ES_FUNC_ALWAYS_REQUIRED(glBlendEquationSeparate), GL_ES_FUNC_ALWAYS_REQUIRED(glCompileShader), GL_ES_FUNC_ALWAYS_REQUIRED(glCreateProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glCreateShader), GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glDeleteShader), GL_ES_FUNC_ALWAYS_REQUIRED(glDetachShader), GL_ES_FUNC_ALWAYS_REQUIRED(glDisableVertexAttribArray), GL_ES_FUNC_ALWAYS_REQUIRED(glEnableVertexAttribArray), GL_ES_FUNC_ALWAYS_REQUIRED(glGetActiveAttrib), GL_ES_FUNC_ALWAYS_REQUIRED(glGetActiveUniform), GL_ES_FUNC_ALWAYS_REQUIRED(glGetAttachedShaders), GL_ES_FUNC_ALWAYS_REQUIRED(glGetAttribLocation), GL_ES_FUNC_ALWAYS_REQUIRED(glGetProgramInfoLog), GL_ES_FUNC_ALWAYS_REQUIRED(glGetProgramiv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderInfoLog), GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderSource), GL_ES_FUNC_ALWAYS_REQUIRED(glGetShaderiv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformLocation), GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformfv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetUniformiv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribPointerv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribfv), GL_ES_FUNC_ALWAYS_REQUIRED(glGetVertexAttribiv), GL_ES_FUNC_ALWAYS_REQUIRED(glIsProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glIsShader), GL_ES_FUNC_ALWAYS_REQUIRED(glLinkProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glShaderSource), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilFuncSeparate), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilMaskSeparate), GL_ES_FUNC_ALWAYS_REQUIRED(glStencilOpSeparate), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1f), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1i), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform1iv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2f), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2i), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform2iv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3f), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3i), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform3iv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4f), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4i), GL_ES_FUNC_ALWAYS_REQUIRED(glUniform4iv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix2fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix3fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUniformMatrix4fv), GL_ES_FUNC_ALWAYS_REQUIRED(glUseProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glValidateProgram), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib1f), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib1fv), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib2f), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib2fv), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib3f), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib3fv), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib4f), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttrib4fv), GL_ES_FUNC_ALWAYS_REQUIRED(glVertexAttribPointer), GL_ES3_FUNC_ALWAYS_REQUIRED(glDrawBuffers), // gl_2_1 GLFUNC_ALWAYS_REQUIRED(glUniformMatrix2x3fv), GLFUNC_ALWAYS_REQUIRED(glUniformMatrix2x4fv), GLFUNC_ALWAYS_REQUIRED(glUniformMatrix3x2fv), GLFUNC_ALWAYS_REQUIRED(glUniformMatrix3x4fv), GLFUNC_ALWAYS_REQUIRED(glUniformMatrix4x2fv), GLFUNC_ALWAYS_REQUIRED(glUniformMatrix4x3fv), // gl_3_0 GLFUNC_REQUIRES(glBeginConditionalRender, "VERSION_3_0"), GLFUNC_REQUIRES(glBindFragDataLocation, "VERSION_3_0"), GLFUNC_REQUIRES(glClampColor, "VERSION_3_0"), GLFUNC_REQUIRES(glEndConditionalRender, "VERSION_3_0"), GLFUNC_REQUIRES(glGetBooleani_v, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI1i, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI1iv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI1ui, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI1uiv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI2i, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI2iv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI2ui, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI2uiv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI3i, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI3iv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI3ui, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI3uiv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI4bv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI4sv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI4ubv, "VERSION_3_0"), GLFUNC_REQUIRES(glVertexAttribI4usv, "VERSION_3_0"), GLFUNC_REQUIRES(glBeginTransformFeedback, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glClearBufferfi, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glClearBufferfv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glClearBufferiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glClearBufferuiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glEndTransformFeedback, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetFragDataLocation, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetStringi, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetTransformFeedbackVarying, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetUniformuiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetVertexAttribIiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetVertexAttribIuiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glTransformFeedbackVaryings, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform1ui, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform1uiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform2ui, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform2uiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform3ui, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform3uiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform4ui, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniform4uiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glVertexAttribI4i, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glVertexAttribI4iv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glVertexAttribI4ui, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glVertexAttribI4uiv, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glVertexAttribIPointer, "VERSION_3_0 |VERSION_GLES_3"), GLFUNC_REQUIRES(glColorMaski, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glDisablei, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glEnablei, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetTexParameterIiv, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetTexParameterIuiv, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glIsEnabledi, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glTexParameterIiv, "VERSION_3_0 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glTexParameterIuiv, "VERSION_3_0 |VERSION_GLES_3_2"), // gl_3_1 GLFUNC_REQUIRES(glPrimitiveRestartIndex, "VERSION_3_1"), GLFUNC_REQUIRES(glDrawArraysInstanced, "VERSION_3_1 |VERSION_GLES_3"), GLFUNC_REQUIRES(glDrawElementsInstanced, "VERSION_3_1 |VERSION_GLES_3"), GLFUNC_REQUIRES(glTexBuffer, "VERSION_3_1 |VERSION_GLES_3_2"), // gl_3_2 GLFUNC_REQUIRES(glGetBufferParameteri64v, "VERSION_3_2 |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetInteger64i_v, "VERSION_3_2 |VERSION_GLES_3"), GLFUNC_REQUIRES(glFramebufferTexture, "VERSION_3_2 |VERSION_GLES_3_2"), // gl_4_2 GLFUNC_REQUIRES(glDrawArraysInstancedBaseInstance, "VERSION_4_2"), GLFUNC_REQUIRES(glDrawElementsInstancedBaseInstance, "VERSION_4_2"), GLFUNC_REQUIRES(glDrawElementsInstancedBaseVertexBaseInstance, "VERSION_4_2"), GLFUNC_REQUIRES(glGetInternalformativ, "VERSION_4_2"), GLFUNC_REQUIRES(glGetActiveAtomicCounterBufferiv, "VERSION_4_2"), GLFUNC_REQUIRES(glBindImageTexture, "VERSION_4_2"), GLFUNC_REQUIRES(glMemoryBarrier, "VERSION_4_2"), GLFUNC_REQUIRES(glTexStorage1D, "VERSION_4_2"), GLFUNC_REQUIRES(glTexStorage2D, "VERSION_4_2"), GLFUNC_REQUIRES(glTexStorage3D, "VERSION_4_2"), GLFUNC_REQUIRES(glDrawTransformFeedbackInstanced, "VERSION_4_2"), GLFUNC_REQUIRES(glDrawTransformFeedbackStreamInstanced, "VERSION_4_2"), // gl_4_3 GLFUNC_REQUIRES(glClearBufferData, "VERSION_4_3"), GLFUNC_REQUIRES(glClearBufferSubData, "VERSION_4_3"), GLFUNC_REQUIRES(glDispatchCompute, "VERSION_4_3"), GLFUNC_REQUIRES(glDispatchComputeIndirect, "VERSION_4_3"), GLFUNC_REQUIRES(glCopyImageSubData, "VERSION_4_3"), GLFUNC_REQUIRES(glFramebufferParameteri, "VERSION_4_3"), GLFUNC_REQUIRES(glGetFramebufferParameteriv, "VERSION_4_3"), GLFUNC_REQUIRES(glGetInternalformati64v, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateTexSubImage, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateTexImage, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateBufferSubData, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateBufferData, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateFramebuffer, "VERSION_4_3"), GLFUNC_REQUIRES(glInvalidateSubFramebuffer, "VERSION_4_3"), GLFUNC_REQUIRES(glMultiDrawArraysIndirect, "VERSION_4_3"), GLFUNC_REQUIRES(glMultiDrawElementsIndirect, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramInterfaceiv, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramResourceIndex, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramResourceName, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramResourceiv, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramResourceLocation, "VERSION_4_3"), GLFUNC_REQUIRES(glGetProgramResourceLocationIndex, "VERSION_4_3"), GLFUNC_REQUIRES(glShaderStorageBlockBinding, "VERSION_4_3"), GLFUNC_REQUIRES(glTexBufferRange, "VERSION_4_3"), GLFUNC_REQUIRES(glTexStorage2DMultisample, "VERSION_4_3"), GLFUNC_REQUIRES(glTexStorage3DMultisample, "VERSION_4_3"), GLFUNC_REQUIRES(glTextureView, "VERSION_4_3"), GLFUNC_REQUIRES(glBindVertexBuffer, "VERSION_4_3"), GLFUNC_REQUIRES(glVertexAttribFormat, "VERSION_4_3"), GLFUNC_REQUIRES(glVertexAttribIFormat, "VERSION_4_3"), GLFUNC_REQUIRES(glVertexAttribLFormat, "VERSION_4_3"), GLFUNC_REQUIRES(glVertexAttribBinding, "VERSION_4_3"), GLFUNC_REQUIRES(glVertexBindingDivisor, "VERSION_4_3"), GLFUNC_REQUIRES(glDebugMessageControl, "VERSION_4_3"), GLFUNC_REQUIRES(glDebugMessageInsert, "VERSION_4_3"), GLFUNC_REQUIRES(glDebugMessageCallback, "VERSION_4_3"), GLFUNC_REQUIRES(glGetDebugMessageLog, "VERSION_4_3"), GLFUNC_REQUIRES(glPushDebugGroup, "VERSION_4_3"), GLFUNC_REQUIRES(glPopDebugGroup, "VERSION_4_3"), GLFUNC_REQUIRES(glObjectLabel, "VERSION_4_3"), GLFUNC_REQUIRES(glGetObjectLabel, "VERSION_4_3"), GLFUNC_REQUIRES(glObjectPtrLabel, "VERSION_4_3"), GLFUNC_REQUIRES(glGetObjectPtrLabel, "VERSION_4_3"), // gl_4_4 GLFUNC_REQUIRES(glBufferStorage, "VERSION_4_4"), GLFUNC_REQUIRES(glClearTexImage, "VERSION_4_4"), GLFUNC_REQUIRES(glClearTexSubImage, "VERSION_4_4"), GLFUNC_REQUIRES(glBindBuffersBase, "VERSION_4_4"), GLFUNC_REQUIRES(glBindBuffersRange, "VERSION_4_4"), GLFUNC_REQUIRES(glBindTextures, "VERSION_4_4"), GLFUNC_REQUIRES(glBindSamplers, "VERSION_4_4"), GLFUNC_REQUIRES(glBindImageTextures, "VERSION_4_4"), GLFUNC_REQUIRES(glBindVertexBuffers, "VERSION_4_4"), // gl_4_5 GLFUNC_REQUIRES(glClipControl, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateTransformFeedbacks, "VERSION_4_5"), GLFUNC_REQUIRES(glTransformFeedbackBufferBase, "VERSION_4_5"), GLFUNC_REQUIRES(glTransformFeedbackBufferRange, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTransformFeedbackiv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTransformFeedbacki_v, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTransformFeedbacki64_v, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateBuffers, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedBufferStorage, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedBufferData, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedBufferSubData, "VERSION_4_5"), GLFUNC_REQUIRES(glCopyNamedBufferSubData, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedBufferData, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedBufferSubData, "VERSION_4_5"), GLFUNC_REQUIRES(glMapNamedBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glMapNamedBufferRange, "VERSION_4_5"), GLFUNC_REQUIRES(glUnmapNamedBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glFlushMappedNamedBufferRange, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedBufferParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedBufferParameteri64v, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedBufferPointerv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedBufferSubData, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateFramebuffers, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferRenderbuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferParameteri, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferTexture, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferTextureLayer, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferDrawBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferDrawBuffers, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedFramebufferReadBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glInvalidateNamedFramebufferData, "VERSION_4_5"), GLFUNC_REQUIRES(glInvalidateNamedFramebufferSubData, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedFramebufferiv, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedFramebufferuiv, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedFramebufferfv, "VERSION_4_5"), GLFUNC_REQUIRES(glClearNamedFramebufferfi, "VERSION_4_5"), GLFUNC_REQUIRES(glBlitNamedFramebuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glCheckNamedFramebufferStatus, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedFramebufferParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedFramebufferAttachmentParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateRenderbuffers, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedRenderbufferStorage, "VERSION_4_5"), GLFUNC_REQUIRES(glNamedRenderbufferStorageMultisample, "VERSION_4_5"), GLFUNC_REQUIRES(glGetNamedRenderbufferParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateTextures, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureBufferRange, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureStorage1D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureStorage2D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureStorage3D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureStorage2DMultisample, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureStorage3DMultisample, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureSubImage1D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureSubImage2D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureSubImage3D, "VERSION_4_5"), GLFUNC_REQUIRES(glCompressedTextureSubImage1D, "VERSION_4_5"), GLFUNC_REQUIRES(glCompressedTextureSubImage2D, "VERSION_4_5"), GLFUNC_REQUIRES(glCompressedTextureSubImage3D, "VERSION_4_5"), GLFUNC_REQUIRES(glCopyTextureSubImage1D, "VERSION_4_5"), GLFUNC_REQUIRES(glCopyTextureSubImage2D, "VERSION_4_5"), GLFUNC_REQUIRES(glCopyTextureSubImage3D, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameterf, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameterfv, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameteri, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameterIiv, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameterIuiv, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glGenerateTextureMipmap, "VERSION_4_5"), GLFUNC_REQUIRES(glBindTextureUnit, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureImage, "VERSION_4_5"), GLFUNC_REQUIRES(glGetCompressedTextureImage, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureLevelParameterfv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureLevelParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureParameterfv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureParameterIiv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureParameterIuiv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureParameteriv, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateVertexArrays, "VERSION_4_5"), GLFUNC_REQUIRES(glDisableVertexArrayAttrib, "VERSION_4_5"), GLFUNC_REQUIRES(glEnableVertexArrayAttrib, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayElementBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayVertexBuffer, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayVertexBuffers, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayAttribBinding, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayAttribFormat, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayAttribIFormat, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayAttribLFormat, "VERSION_4_5"), GLFUNC_REQUIRES(glVertexArrayBindingDivisor, "VERSION_4_5"), GLFUNC_REQUIRES(glGetVertexArrayiv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetVertexArrayIndexediv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetVertexArrayIndexed64iv, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateSamplers, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateProgramPipelines, "VERSION_4_5"), GLFUNC_REQUIRES(glCreateQueries, "VERSION_4_5"), GLFUNC_REQUIRES(glGetQueryBufferObjecti64v, "VERSION_4_5"), GLFUNC_REQUIRES(glGetQueryBufferObjectiv, "VERSION_4_5"), GLFUNC_REQUIRES(glGetQueryBufferObjectui64v, "VERSION_4_5"), GLFUNC_REQUIRES(glGetQueryBufferObjectuiv, "VERSION_4_5"), GLFUNC_REQUIRES(glMemoryBarrierByRegion, "VERSION_4_5"), GLFUNC_REQUIRES(glGetTextureSubImage, "VERSION_4_5"), GLFUNC_REQUIRES(glGetCompressedTextureSubImage, "VERSION_4_5"), GLFUNC_REQUIRES(glGetGraphicsResetStatus, "VERSION_4_5"), GLFUNC_REQUIRES(glReadnPixels, "VERSION_4_5"), GLFUNC_REQUIRES(glTextureBarrier, "VERSION_4_5"), // AMD's video driver is trash and doesn't expose these function pointers // Remove them for now until they learn how to implement the spec properly. // GLFUNC_REQUIRES(glGetnCompressedTexImage, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnTexImage, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnUniformdv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnUniformfv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnUniformiv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnUniformuiv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnMapdv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnMapfv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnMapiv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnPixelMapfv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnPixelMapuiv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnPixelMapusv, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnPolygonStipple, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnColorTable, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnConvolutionFilter, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnSeparableFilter, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnHistogram, "VERSION_4_5"), // GLFUNC_REQUIRES(glGetnMinmax, "VERSION_4_5"), // ARB_uniform_buffer_object GLFUNC_REQUIRES(glGetActiveUniformName, "GL_ARB_uniform_buffer_object"), GLFUNC_REQUIRES(glBindBufferBase, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glBindBufferRange, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetActiveUniformBlockName, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetActiveUniformBlockiv, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetActiveUniformsiv, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetIntegeri_v, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetUniformBlockIndex, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetUniformIndices, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glUniformBlockBinding, "GL_ARB_uniform_buffer_object |VERSION_GLES_3"), // ARB_sampler_objects GLFUNC_REQUIRES(glBindSampler, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glDeleteSamplers, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glGenSamplers, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetSamplerParameterfv, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetSamplerParameteriv, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glIsSampler, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glSamplerParameterf, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glSamplerParameterfv, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glSamplerParameteri, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glSamplerParameteriv, "GL_ARB_sampler_objects |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetSamplerParameterIiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetSamplerParameterIuiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glSamplerParameterIiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glSamplerParameterIuiv, "GL_ARB_sampler_objects |VERSION_GLES_3_2"), // ARB_map_buffer_range GLFUNC_REQUIRES(glFlushMappedBufferRange, "GL_ARB_map_buffer_range |VERSION_GLES_3"), GLFUNC_REQUIRES(glMapBufferRange, "GL_ARB_map_buffer_range |VERSION_GLES_3"), // ARB_vertex_array_object GLFUNC_REQUIRES(glBindVertexArray, "GL_ARB_vertex_array_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glDeleteVertexArrays, "GL_ARB_vertex_array_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGenVertexArrays, "GL_ARB_vertex_array_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glIsVertexArray, "GL_ARB_vertex_array_object |VERSION_GLES_3"), // APPLE_vertex_array_object GLFUNC_SUFFIX(glBindVertexArray, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"), GLFUNC_SUFFIX(glDeleteVertexArrays, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"), GLFUNC_SUFFIX(glGenVertexArrays, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"), GLFUNC_SUFFIX(glIsVertexArray, APPLE, "GL_APPLE_vertex_array_object !GL_ARB_vertex_array_object"), // ARB_framebuffer_object GLFUNC_REQUIRES(glFramebufferTexture1D, "GL_ARB_framebuffer_object"), GLFUNC_REQUIRES(glFramebufferTexture3D, "GL_ARB_framebuffer_object"), GLFUNC_REQUIRES(glBindFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glBindRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glBlitFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glCheckFramebufferStatus, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glDeleteFramebuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glDeleteRenderbuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glFramebufferRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glFramebufferTexture2D, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glFramebufferTextureLayer, "GL_ARB_framebuffer_object |VERSION_GLES_3"), GLFUNC_REQUIRES(glGenFramebuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glGenRenderbuffers, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glGenerateMipmap, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glGetFramebufferAttachmentParameteriv, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glGetRenderbufferParameteriv, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glIsFramebuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glIsRenderbuffer, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glRenderbufferStorage, "GL_ARB_framebuffer_object |VERSION_GLES_2"), GLFUNC_REQUIRES(glRenderbufferStorageMultisample, "GL_ARB_framebuffer_object |VERSION_GLES_3"), // ARB_get_program_binary GLFUNC_REQUIRES(glGetProgramBinary, "GL_ARB_get_program_binary |VERSION_GLES_3"), GLFUNC_REQUIRES(glProgramBinary, "GL_ARB_get_program_binary |VERSION_GLES_3"), GLFUNC_REQUIRES(glProgramParameteri, "GL_ARB_get_program_binary |VERSION_GLES_3"), // ARB_sync GLFUNC_REQUIRES(glClientWaitSync, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glDeleteSync, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glFenceSync, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetInteger64v, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glGetSynciv, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glIsSync, "GL_ARB_sync |VERSION_GLES_3"), GLFUNC_REQUIRES(glWaitSync, "GL_ARB_sync |VERSION_GLES_3"), // ARB_texture_multisample GLFUNC_REQUIRES(glTexImage2DMultisample, "GL_ARB_texture_multisample"), GLFUNC_REQUIRES(glTexImage3DMultisample, "GL_ARB_texture_multisample"), GLFUNC_REQUIRES(glGetMultisamplefv, "GL_ARB_texture_multisample"), GLFUNC_REQUIRES(glSampleMaski, "GL_ARB_texture_multisample"), // ARB_texture_storage_multisample GLFUNC_REQUIRES(glTexStorage2DMultisample, "GL_ARB_texture_storage_multisample !VERSION_4_3 |VERSION_GLES_3_1"), GLFUNC_REQUIRES(glTexStorage3DMultisample, "GL_ARB_texture_storage_multisample !VERSION_4_3 |VERSION_GLES_3_2"), GLFUNC_SUFFIX(glTexStorage3DMultisample, OES, "GL_OES_texture_storage_multisample_2d_array !VERSION_GLES_3_2"), // ARB_ES2_compatibility GLFUNC_REQUIRES(glClearDepthf, "GL_ARB_ES2_compatibility |VERSION_GLES_2"), GLFUNC_REQUIRES(glDepthRangef, "GL_ARB_ES2_compatibility |VERSION_GLES_2"), GLFUNC_REQUIRES(glGetShaderPrecisionFormat, "GL_ARB_ES2_compatibility |VERSION_GLES_2"), GLFUNC_REQUIRES(glReleaseShaderCompiler, "GL_ARB_ES2_compatibility |VERSION_GLES_2"), GLFUNC_REQUIRES(glShaderBinary, "GL_ARB_ES2_compatibility |VERSION_GLES_2"), // NV_primitive_restart GLFUNC_REQUIRES(glPrimitiveRestartIndexNV, "GL_NV_primitive_restart"), GLFUNC_REQUIRES(glPrimitiveRestartNV, "GL_NV_primitive_restart"), // ARB_blend_func_extended GLFUNC_REQUIRES(glBindFragDataLocationIndexed, "GL_ARB_blend_func_extended"), GLFUNC_REQUIRES(glGetFragDataIndex, "GL_ARB_blend_func_extended"), // ARB_viewport_array GLFUNC_REQUIRES(glDepthRangeArrayv, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glDepthRangeIndexed, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glGetDoublei_v, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glGetFloati_v, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glScissorArrayv, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glScissorIndexed, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glScissorIndexedv, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glViewportArrayv, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glViewportIndexedf, "GL_ARB_viewport_array"), GLFUNC_REQUIRES(glViewportIndexedfv, "GL_ARB_viewport_array"), // ARB_draw_elements_base_vertex GLFUNC_REQUIRES(glDrawElementsBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glDrawElementsInstancedBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glDrawRangeElementsBaseVertex, "GL_ARB_draw_elements_base_vertex |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glMultiDrawElementsBaseVertex, "GL_ARB_draw_elements_base_vertex"), // OES_draw_elements_base_vertex GLFUNC_SUFFIX(glDrawElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glDrawElementsInstancedBaseVertex, OES, "GL_OES_draw_elements_base_vertex VERSION_GLES_3 !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glDrawRangeElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex VERSION_GLES_3 !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glMultiDrawElementsBaseVertex, OES, "GL_OES_draw_elements_base_vertex GL_EXT_multi_draw_arrays"), // EXT_draw_elements_base_vertex GLFUNC_SUFFIX(glDrawElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glDrawElementsInstancedBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex VERSION_GLES_3 !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glDrawRangeElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex VERSION_GLES_3 !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"), GLFUNC_SUFFIX(glMultiDrawElementsBaseVertex, EXT, "GL_EXT_draw_elements_base_vertex GL_EXT_multi_draw_arrays !GL_OES_draw_elements_base_vertex !VERSION_GLES_3_2"), // ARB_sample_shading GLFUNC_SUFFIX(glMinSampleShading, ARB, "GL_ARB_sample_shading"), // OES_sample_shading GLFUNC_SUFFIX(glMinSampleShading, OES, "GL_OES_sample_shading !VERSION_GLES_3_2"), GLFUNC_REQUIRES(glMinSampleShading, "VERSION_GLES_3_2"), // ARB_debug_output GLFUNC_REQUIRES(glDebugMessageCallbackARB, "GL_ARB_debug_output"), GLFUNC_REQUIRES(glDebugMessageControlARB, "GL_ARB_debug_output"), GLFUNC_REQUIRES(glDebugMessageInsertARB, "GL_ARB_debug_output"), GLFUNC_REQUIRES(glGetDebugMessageLogARB, "GL_ARB_debug_output"), // KHR_debug GLFUNC_SUFFIX(glDebugMessageCallback, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glDebugMessageControl, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glDebugMessageInsert, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glGetDebugMessageLog, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glGetObjectLabel, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glGetObjectPtrLabel, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glObjectLabel, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glObjectPtrLabel, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glPopDebugGroup, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_SUFFIX(glPushDebugGroup, KHR, "GL_KHR_debug VERSION_GLES_3"), GLFUNC_REQUIRES(glDebugMessageCallback, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glDebugMessageControl, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glDebugMessageInsert, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetDebugMessageLog, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetObjectLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glGetObjectPtrLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glObjectLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glObjectPtrLabel, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glPopDebugGroup, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), GLFUNC_REQUIRES(glPushDebugGroup, "GL_KHR_debug !VERSION_GLES_3 !VERSION_GL_4_3 |VERSION_GLES_3_2"), // ARB_buffer_storage GLFUNC_REQUIRES(glBufferStorage, "GL_ARB_buffer_storage !VERSION_4_4"), GLFUNC_SUFFIX(glNamedBufferStorage, EXT, "GL_ARB_buffer_storage GL_EXT_direct_state_access !VERSION_4_5"), // EXT_buffer_storage GLFUNC_SUFFIX(glBufferStorage, EXT, "GL_EXT_buffer_storage !GL_ARB_buffer_storage !VERSION_4_4"), // EXT_geometry_shader GLFUNC_SUFFIX(glFramebufferTexture, EXT, "GL_EXT_geometry_shader !VERSION_3_2"), // NV_occlusion_query_samples GLFUNC_REQUIRES(glGenOcclusionQueriesNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glDeleteOcclusionQueriesNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glIsOcclusionQueryNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glBeginOcclusionQueryNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glEndOcclusionQueryNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glGetOcclusionQueryivNV, "GL_NV_occlusion_query_samples"), GLFUNC_REQUIRES(glGetOcclusionQueryuivNV, "GL_NV_occlusion_query_samples"), // ARB_clip_control GLFUNC_REQUIRES(glClipControl, "GL_ARB_clip_control !VERSION_4_5"), // ARB_copy_image GLFUNC_REQUIRES(glCopyImageSubData, "GL_ARB_copy_image !VERSION_4_3 |VERSION_GLES_3_2"), // NV_copy_image GLFUNC_SUFFIX(glCopyImageSubData, NV, "GL_NV_copy_image !GL_ARB_copy_image !VERSION_GLES_3_2"), // OES_copy_image GLFUNC_SUFFIX(glCopyImageSubData, OES, "GL_OES_copy_image !VERSION_GLES_3_2"), // EXT_copy_image GLFUNC_SUFFIX(glCopyImageSubData, EXT, "GL_EXT_copy_image !GL_OES_copy_image !VERSION_GLES_3_2"), // EXT_texture_buffer GLFUNC_SUFFIX(glTexBuffer, OES, "GL_OES_texture_buffer !VERSION_GLES_3_2"), // EXT_texture_buffer GLFUNC_SUFFIX(glTexBuffer, EXT, "GL_EXT_texture_buffer !GL_OES_texture_buffer !VERSION_GLES_3_2"), // EXT_blend_func_extended GLFUNC_SUFFIX(glBindFragDataLocationIndexed, EXT, "GL_EXT_blend_func_extended"), GLFUNC_SUFFIX(glGetFragDataIndex, EXT, "GL_EXT_blend_func_extended"), // ARB_shader_storage_buffer_object GLFUNC_REQUIRES(glShaderStorageBlockBinding, "ARB_shader_storage_buffer_object !VERSION_4_3"), }; namespace GLExtensions { // Private members and functions static bool _isES; static u32 _GLVersion; static std::unordered_map<std::string, bool> m_extension_list; // Private initialization functions bool InitFunctionPointers(); // Initializes the extension list the old way static void InitExtensionList21() { const char* extensions = (const char*)glGetString(GL_EXTENSIONS); std::string tmp(extensions); std::istringstream buffer(tmp); while (buffer >> tmp) m_extension_list[tmp] = true; } static void InitExtensionList() { m_extension_list.clear(); if (_isES) { switch (_GLVersion) { default: case 320: m_extension_list["VERSION_GLES_3_2"] = true; case 310: m_extension_list["VERSION_GLES_3_1"] = true; case 300: m_extension_list["VERSION_GLES_3"] = true; break; } // We always have ES 2.0 m_extension_list["VERSION_GLES_2"] = true; } else { // Some OpenGL implementations chose to not expose core extensions as extensions // Let's add them to the list manually depending on which version of OpenGL we have // We need to be slightly careful here // When an extension got merged in to core, the naming may have changed // This has intentional fall through switch (_GLVersion) { default: case 450: { std::string gl450exts[] = { "GL_ARB_ES3_1_compatibility", "GL_ARB_clip_control", "GL_ARB_conditional_render_inverted", "GL_ARB_cull_distance", "GL_ARB_derivative_control", "GL_ARB_direct_state_access", "GL_ARB_get_texture_sub_image", "GL_ARB_robustness", "GL_ARB_shader_texture_image_samples", "GL_ARB_texture_barrier", "VERSION_4_5", }; for (auto it : gl450exts) m_extension_list[it] = true; } case 440: { std::string gl440exts[] = { "GL_ARB_buffer_storage", "GL_ARB_clear_texture", "GL_ARB_enhanced_layouts", "GL_ARB_multi_bind", "GL_ARB_query_buffer_object", "GL_ARB_texture_mirror_clamp_to_edge", "GL_ARB_texture_stencil8", "GL_ARB_vertex_type_10f_11f_11f_rev", "VERSION_4_4", }; for (auto it : gl440exts) m_extension_list[it] = true; } case 430: { std::string gl430exts[] = { "GL_ARB_ES3_compatibility", "GL_ARB_arrays_of_arrays", "GL_ARB_clear_buffer_object", "GL_ARB_compute_shader", "GL_ARB_copy_image", "GL_ARB_explicit_uniform_location", "GL_ARB_fragment_layer_viewport", "GL_ARB_framebuffer_no_attachments", "GL_ARB_internalformat_query2", "GL_ARB_invalidate_subdata", "GL_ARB_multi_draw_indirect", "GL_ARB_program_interface_query", "GL_ARB_shader_image_size", "GL_ARB_shader_storage_buffer_object", "GL_ARB_stencil_texturing", "GL_ARB_texture_buffer_range", "GL_ARB_texture_query_levels", "GL_ARB_texture_storage_multisample", "GL_ARB_texture_view", "GL_ARB_vertex_attrib_binding", "VERSION_4_3", }; for (auto it : gl430exts) m_extension_list[it] = true; } case 420: { std::string gl420exts[] = { "GL_ARB_base_instance", "GL_ARB_compressed_texture_pixel_storage", "GL_ARB_conservative_depth", "GL_ARB_internalformat_query", "GL_ARB_map_buffer_alignment", "GL_ARB_shader_atomic_counters", "GL_ARB_shader_image_load_store", "GL_ARB_shading_language_420pack", "GL_ARB_shading_language_packing", "GL_ARB_texture_compression_BPTC", "GL_ARB_texture_storage", "GL_ARB_transform_feedback_instanced", "VERSION_4_2", }; for (auto it : gl420exts) m_extension_list[it] = true; } case 410: { std::string gl410exts[] = { "GL_ARB_ES2_compatibility", "GL_ARB_get_program_binary", "GL_ARB_separate_shader_objects", "GL_ARB_shader_precision", "GL_ARB_vertex_attrib_64_bit", "GL_ARB_viewport_array", "VERSION_4_1", }; for (auto it : gl410exts) m_extension_list[it] = true; } case 400: { std::string gl400exts[] = { "GL_ARB_draw_indirect", "GL_ARB_gpu_shader5", "GL_ARB_gpu_shader_fp64", "GL_ARB_sample_shading", "GL_ARB_shader_subroutine", "GL_ARB_tessellation_shader", "GL_ARB_texture_buffer_object_rgb32", "GL_ARB_texture_cube_map_array", "GL_ARB_texture_gather", "GL_ARB_texture_query_lod", "GL_ARB_transform_feedback2", "GL_ARB_transform_feedback3", "VERSION_4_0", }; for (auto it : gl400exts) m_extension_list[it] = true; } case 330: { std::string gl330exts[] = { "GL_ARB_shader_bit_encoding", "GL_ARB_blend_func_extended", "GL_ARB_explicit_attrib_location", "GL_ARB_occlusion_query2", "GL_ARB_sampler_objects", "GL_ARB_texture_swizzle", "GL_ARB_timer_query", "GL_ARB_instanced_arrays", "GL_ARB_texture_rgb10_a2ui", "GL_ARB_vertex_type_2_10_10_10_rev", "VERSION_3_3", }; for (auto it : gl330exts) m_extension_list[it] = true; } case 320: { std::string gl320exts[] = { "GL_ARB_geometry_shader4", "GL_ARB_sync", "GL_ARB_vertex_array_bgra", "GL_ARB_draw_elements_base_vertex", "GL_ARB_seamless_cube_map", "GL_ARB_texture_multisample", "GL_ARB_fragment_coord_conventions", "GL_ARB_provoking_vertex", "GL_ARB_depth_clamp", "VERSION_3_2", }; for (auto it : gl320exts) m_extension_list[it] = true; } case 310: { // Can't add NV_primitive_restart since function name changed std::string gl310exts[] = { "GL_ARB_draw_instanced", "GL_ARB_copy_buffer", "GL_ARB_texture_buffer_object", "GL_ARB_texture_rectangle", "GL_ARB_uniform_buffer_object", //"GL_NV_primitive_restart", "VERSION_3_1", }; for (auto it : gl310exts) m_extension_list[it] = true; } case 300: { // Quite a lot of these had their names changed when merged in to core // Disable the ones that have std::string gl300exts[] = { "GL_ARB_map_buffer_range", //"GL_EXT_gpu_shader4", //"GL_APPLE_flush_buffer_range", "GL_ARB_color_buffer_float", //"GL_NV_depth_buffer_float", "GL_ARB_texture_float", //"GL_EXT_packed_float", //"GL_EXT_texture_shared_exponent", "GL_ARB_half_float_pixel", //"GL_NV_half_float", "GL_ARB_framebuffer_object", //"GL_EXT_framebuffer_sRGB", "GL_ARB_texture_float", //"GL_EXT_texture_integer", //"GL_EXT_draw_buffers2", //"GL_EXT_texture_integer", //"GL_EXT_texture_array", //"GL_EXT_texture_compression_rgtc", //"GL_EXT_transform_feedback", "GL_ARB_vertex_array_object", //"GL_NV_conditional_render", "VERSION_3_0", }; for (auto it : gl300exts) m_extension_list[it] = true; } case 210: case 200: case 150: case 140: case 130: case 121: case 120: case 110: case 100: break; } // So we can easily determine if we are running dekstop GL m_extension_list["VERSION_GL"] = true; } if (_GLVersion < 300) { InitExtensionList21(); return; } GLint NumExtension = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &NumExtension); for (GLint i = 0; i < NumExtension; ++i) m_extension_list[std::string((const char*)glGetStringi(GL_EXTENSIONS, i))] = true; } static void InitVersion() { GLint major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); if (glGetError() == GL_NO_ERROR) _GLVersion = major * 100 + minor * 10; else _GLVersion = 210; } static void* GetFuncAddress(const std::string& name, void **func) { *func = GLInterface->GetFuncAddress(name); if (*func == nullptr) { #if defined(__linux__) || defined(__APPLE__) // Give it a second try with dlsym *func = dlsym(RTLD_NEXT, name.c_str()); #endif if (*func == nullptr) ERROR_LOG(VIDEO, "Couldn't load function %s", name.c_str()); } return *func; } // Public members u32 Version() { return _GLVersion; } bool Supports(const std::string& name) { return m_extension_list[name]; } bool Init() { _isES = GLInterface->GetMode() != GLInterfaceMode::MODE_OPENGL; // Grab a few functions for initial checking // We need them to grab the extension list // Also to check if there is an error grabbing the version if (GetFuncAddress("glGetIntegerv", (void**)&glGetIntegerv) == nullptr) return false; if (GetFuncAddress("glGetString", (void**)&glGetString) == nullptr) return false; if (GetFuncAddress("glGetError", (void**)&glGetError) == nullptr) return false; InitVersion(); // We need to use glGetStringi to get the extension list // if we are using GLES3 or a GL version greater than 2.1 if (_GLVersion > 210 && GetFuncAddress("glGetStringi", (void**)&glGetStringi) == nullptr) return false; InitExtensionList(); return InitFunctionPointers(); } // Private initialization functions static bool HasFeatures(const std::string& extensions) { bool result = true; std::string tmp; std::istringstream buffer(extensions); while (buffer >> tmp) { if (tmp[0] == '!') result &= !m_extension_list[tmp.erase(0, 1)]; else if (tmp[0] == '|') result |= m_extension_list[tmp.erase(0, 1)]; else result &= m_extension_list[tmp]; } return result; } bool InitFunctionPointers() { bool result = true; for (const auto &it : gl_function_array) if (HasFeatures(it.requirements)) result &= !!GetFuncAddress(it.function_name, it.function_ptr); return result; } }
mmastrac/dolphin
Source/Core/Common/GL/GLExtensions/GLExtensions.cpp
C++
gpl-2.0
108,368
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * This code is based on Labyrinth of Time code with assistance of * * Copyright (c) 1993 Terra Nova Development * Copyright (c) 2004 The Wyrmkeep Entertainment Co. * */ #include "lab/lab.h" #include "lab/anim.h" #include "lab/dispman.h" #include "lab/eventman.h" #include "lab/intro.h" #include "lab/music.h" #include "lab/resource.h" #include "lab/utils.h" namespace Lab { Intro::Intro(LabEngine *vm) : _vm(vm) { _quitIntro = false; _introDoBlack = false; _font = _vm->_resource->getFont("F:Map.fon"); } Intro::~Intro() { _vm->_graphics->freeFont(&_font); } void Intro::introEatMessages() { while (1) { IntuiMessage *msg = _vm->_event->getMsg(); if (_vm->shouldQuit()) { _quitIntro = true; return; } if (!msg) return; if ((msg->_msgClass == kMessageRightClick) || ((msg->_msgClass == kMessageRawKey) && (msg->_code == Common::KEYCODE_ESCAPE))) _quitIntro = true; } } void Intro::doPictText(const Common::String filename, bool isScreen) { Common::String path = Common::String("Lab:rooms/Intro/") + filename; uint timeDelay = (isScreen) ? 35 : 7; _vm->updateEvents(); if (_quitIntro) return; uint32 lastMillis = 0; bool drawNextText = true; bool doneFl = false; bool begin = true; Common::File *textFile = _vm->_resource->openDataFile(path); char *textBuffer = new char[textFile->size()]; textFile->read(textBuffer, textFile->size()); delete textFile; const char *curText = textBuffer; while (1) { if (drawNextText) { if (begin) begin = false; else if (isScreen) _vm->_graphics->fade(false); if (isScreen) { _vm->_graphics->rectFillScaled(10, 10, 310, 190, 7); curText += _vm->_graphics->flowText(_font, _vm->_isHiRes ? 0 : -1, 5, 7, false, false, true, true, _vm->_utils->vgaRectScale(14, 11, 306, 189), curText); _vm->_graphics->fade(true); } else curText += _vm->_graphics->longDrawMessage(Common::String(curText), false); doneFl = (*curText == 0); drawNextText = false; introEatMessages(); if (_quitIntro) { if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } lastMillis = _vm->_system->getMillis(); } IntuiMessage *msg = _vm->_event->getMsg(); if (_vm->shouldQuit()) { _quitIntro = true; return; } if (!msg) { _vm->updateEvents(); _vm->_anim->diffNextFrame(); uint32 elapsedSeconds = (_vm->_system->getMillis() - lastMillis) / 1000; if (elapsedSeconds > timeDelay) { if (doneFl) { if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } else { drawNextText = true; } } _vm->waitTOF(); } else { uint32 msgClass = msg->_msgClass; uint16 code = msg->_code; if ((msgClass == kMessageRightClick) || ((msgClass == kMessageRawKey) && (code == Common::KEYCODE_ESCAPE))) { _quitIntro = true; if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } else if ((msgClass == kMessageLeftClick) || (msgClass == kMessageRightClick)) { if (msgClass == kMessageLeftClick) { if (doneFl) { if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } else drawNextText = true; } introEatMessages(); if (_quitIntro) { if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } } if (doneFl) { if (isScreen) _vm->_graphics->fade(false); delete[] textBuffer; return; } else drawNextText = true; } } // while(1) } void Intro::musicDelay() { _vm->updateEvents(); if (_quitIntro) return; for (int i = 0; i < 20; i++) { _vm->updateEvents(); _vm->waitTOF(); _vm->waitTOF(); _vm->waitTOF(); } } void Intro::nReadPict(const Common::String filename, bool playOnce) { Common::String finalFileName = Common::String("P:Intro/") + filename; _vm->updateEvents(); introEatMessages(); if (_quitIntro) return; _vm->_anim->_doBlack = _introDoBlack; _vm->_anim->stopDiffEnd(); _vm->_graphics->readPict(finalFileName, playOnce); } void Intro::play() { uint16 palette[16] = { 0x0000, 0x0855, 0x0FF9, 0x0EE7, 0x0ED5, 0x0DB4, 0x0CA2, 0x0C91, 0x0B80, 0x0B80, 0x0B91, 0x0CA2, 0x0CB3, 0x0DC4, 0x0DD6, 0x0EE7 }; _vm->_anim->_doBlack = true; if (_vm->getPlatform() == Common::kPlatformDOS) { nReadPict("EA0"); nReadPict("EA1"); nReadPict("EA2"); nReadPict("EA3"); } else if (_vm->getPlatform() == Common::kPlatformWindows) { nReadPict("WYRMKEEP"); // Wait 4 seconds (400 x 10ms) for (int i = 0; i < 400; i++) { introEatMessages(); if (_quitIntro) break; _vm->_system->delayMillis(10); } } _vm->_graphics->blackAllScreen(); if (_vm->getPlatform() != Common::kPlatformAmiga) _vm->_music->changeMusic("Music:BackGrou", false, false); else _vm->_music->changeMusic("Music:BackGround", false, false); _vm->_anim->_noPalChange = true; if (_vm->getPlatform() == Common::kPlatformDOS) nReadPict("TNDcycle.pic"); else nReadPict("TNDcycle2.pic"); _vm->_anim->_noPalChange = false; _vm->_graphics->_fadePalette = palette; for (int i = 0; i < 16; i++) { palette[i] = ((_vm->_anim->_diffPalette[i * 3] >> 2) << 8) + ((_vm->_anim->_diffPalette[i * 3 + 1] >> 2) << 4) + (_vm->_anim->_diffPalette[i * 3 + 2] >> 2); } _vm->updateEvents(); if (!_quitIntro) _vm->_graphics->fade(true); for (int times = 0; times < 150; times++) { introEatMessages(); if (_quitIntro) break; _vm->updateEvents(); uint16 temp = palette[2]; for (int i = 2; i < 15; i++) palette[i] = palette[i + 1]; palette[15] = temp; _vm->_graphics->setAmigaPal(palette); _vm->waitTOF(); } if (!_quitIntro) { _vm->_graphics->fade(false); _vm->_graphics->blackAllScreen(); _vm->updateEvents(); } nReadPict("Title.A"); nReadPict("AB"); musicDelay(); nReadPict("BA"); nReadPict("AC"); musicDelay(); if (_vm->getPlatform() == Common::kPlatformWindows) musicDelay(); // more credits on this page now nReadPict("CA"); nReadPict("AD"); musicDelay(); if (_vm->getPlatform() == Common::kPlatformWindows) musicDelay(); // more credits on this page now nReadPict("DA"); musicDelay(); _vm->updateEvents(); _vm->_graphics->blackAllScreen(); _vm->updateEvents(); _vm->_anim->_noPalChange = true; nReadPict("Intro.1"); _vm->_anim->_noPalChange = false; for (int i = 0; i < 16; i++) { palette[i] = ((_vm->_anim->_diffPalette[i * 3] >> 2) << 8) + ((_vm->_anim->_diffPalette[i * 3 + 1] >> 2) << 4) + (_vm->_anim->_diffPalette[i * 3 + 2] >> 2); } doPictText("i.1", true); if (_vm->getPlatform() == Common::kPlatformWindows) { doPictText("i.2A", true); doPictText("i.2B", true); } _vm->_graphics->blackAllScreen(); _vm->updateEvents(); _introDoBlack = true; nReadPict("Station1"); doPictText("i.3"); nReadPict("Station2"); doPictText("i.4"); nReadPict("Stiles4"); doPictText("i.5"); nReadPict("Stiles3"); doPictText("i.6"); if (_vm->getPlatform() == Common::kPlatformWindows) nReadPict("Platform2"); else nReadPict("Platform"); doPictText("i.7"); nReadPict("Subway.1"); doPictText("i.8"); nReadPict("Subway.2"); doPictText("i.9"); doPictText("i.10"); doPictText("i.11"); if (!_quitIntro) for (int i = 0; i < 50; i++) { for (int idx = (8 * 3); idx < (255 * 3); idx++) _vm->_anim->_diffPalette[idx] = 255 - _vm->_anim->_diffPalette[idx]; _vm->updateEvents(); _vm->waitTOF(); _vm->_graphics->setPalette(_vm->_anim->_diffPalette, 256); _vm->waitTOF(); _vm->waitTOF(); } doPictText("i.12"); doPictText("i.13"); _introDoBlack = false; nReadPict("Daed0"); doPictText("i.14"); nReadPict("Daed1"); doPictText("i.15"); nReadPict("Daed2"); doPictText("i.16"); doPictText("i.17"); doPictText("i.18"); nReadPict("Daed3"); doPictText("i.19"); doPictText("i.20"); nReadPict("Daed4"); doPictText("i.21"); nReadPict("Daed5"); doPictText("i.22"); doPictText("i.23"); doPictText("i.24"); nReadPict("Daed6"); doPictText("i.25"); doPictText("i.26"); nReadPict("Daed7", false); doPictText("i.27"); doPictText("i.28"); _vm->_anim->stopDiffEnd(); nReadPict("Daed8"); doPictText("i.29"); doPictText("i.30"); nReadPict("Daed9"); doPictText("i.31"); doPictText("i.32"); doPictText("i.33"); nReadPict("Daed9a"); nReadPict("Daed10"); doPictText("i.34"); doPictText("i.35"); doPictText("i.36"); nReadPict("SubX"); if (_quitIntro) { _vm->_graphics->rectFill(0, 0, _vm->_graphics->_screenWidth - 1, _vm->_graphics->_screenHeight - 1, 0); _vm->_anim->_doBlack = true; } } } // End of namespace Lab
project-cabal/cabal
engines/lab/intro.cpp
C++
gpl-2.0
9,600
/* Manage an ftp connection Copyright (C) 1997,2001,02 Free Software Foundation, Inc. Written by Miles Bader <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __FTPCONN_H__ #define __FTPCONN_H__ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #define __need_error_t #include <errno.h> #ifndef __error_t_defined typedef int error_t; #define __error_t_defined #endif #ifndef FTP_CONN_EI # define FTP_CONN_EI extern inline #endif struct ftp_conn; struct ftp_conn_params; struct ftp_conn_stat; /* The type of the function called by ...get_stats to add each new stat. NAME is the file in question, STAT is stat info about it, and if NAME is a symlink, SYMLINK_TARGET is what it is linked to, or 0 if it's not a symlink. NAME and SYMLINK_TARGET should be copied if they are used outside of this function. HOOK is as passed into ...get_stats. */ typedef error_t (*ftp_conn_add_stat_fun_t) (const char *name, # if _FILE_OFFSET_BITS == 64 const struct stat *stat, # else const struct stat64 *stat, # endif const char *symlink_target, void *hook); /* Hooks that customize behavior for particular types of remote system. */ struct ftp_conn_syshooks { /* Should return in ADDR a malloced struct sockaddr containing the address of the host referenced by the PASV reply contained in TXT. */ error_t (*pasv_addr) (struct ftp_conn *conn, const char *txt, struct sockaddr **addr); /* Look at the error string in TXT, and try to guess an error code to return. If POSS_ERRS is non-zero, it contains a list of errors that are likely to occur with the previous command, terminated with 0. If no match is found and POSS_ERRS is non-zero, the first error in POSS_ERRS should be returned by default. */ error_t (*interp_err) (struct ftp_conn *conn, const char *txt, const error_t *poss_errs); /* Start an operation to get a list of file-stat structures for NAME (this is often similar to ftp_conn_start_dir, but with OS-specific flags), and return a file-descriptor for reading on, and a state structure in STATE suitable for passing to cont_get_stats. If CONTENTS is true, NAME must refer to a directory, and the contents will be returned, otherwise, the (single) result will refer to NAME. */ error_t (*start_get_stats) (struct ftp_conn *conn, const char *name, int contents, int *fd, void **state); /* Read stats information from FD, calling ADD_STAT for each new stat (HOOK is passed to ADD_STAT). FD and STATE should be returned from start_get_stats. If this function returns EAGAIN, then it should be called again to finish the job (possibly after calling select on FD); if it returns 0, then it is finishe,d and FD and STATE are deallocated. */ error_t (*cont_get_stats) (struct ftp_conn *conn, int fd, void *state, ftp_conn_add_stat_fun_t add_stat, void *hook); /* Give a name which refers to a directory file, and a name in that directory, this should return in COMPOSITE the composite name refering to that name in that directory, in malloced storage. */ error_t (*append_name) (struct ftp_conn *conn, const char *dir, const char *name, char **composite); /* If the name of a file *NAME is a composite name (containing both a filename and a directory name), this function should change *NAME to be the name component only; if the result is shorter than the original *NAME, the storage pointed to it may be modified, otherwise, *NAME should be changed to point to malloced storage holding the result, which will be freed by the caller. */ error_t (*basename) (struct ftp_conn *conn, char **name); }; /* Type parameter for the cntl_debug hook. */ #define FTP_CONN_CNTL_DEBUG_CMD 1 #define FTP_CONN_CNTL_DEBUG_REPLY 2 /* Type parameter for the get_login_param hook. */ #define FTP_CONN_GET_LOGIN_PARAM_USER 1 #define FTP_CONN_GET_LOGIN_PARAM_PASS 2 #define FTP_CONN_GET_LOGIN_PARAM_ACCT 3 /* General connection customization. */ struct ftp_conn_hooks { /* If non-zero, should look at the SYST reply in SYST, and fill in CONN's syshooks (with ftp_conn_set_hooks) appropriately; SYST may be zero if the remote system doesn't support that command. If zero, then the default ftp_conn_choose_syshooks is used. */ void (*choose_syshooks) (struct ftp_conn *conn, const char *syst); /* If non-zero, called during io on the ftp control connection -- TYPE is FTP_CONN_CNTL_DEBUG_CMD for commands, and FTP_CONN_CNTL_DEBUG_REPLY for replies; TXT is the actual text. */ void (*cntl_debug) (struct ftp_conn *conn, int type, const char *txt); /* Called after CONN's connection the server has been opened (or reopened). */ void (*opened) (struct ftp_conn *conn); /* If the remote system requires some login parameter that isn't available, this hook is called to try and get it, returning a value in TXT. The return value should be in a malloced block of memory. The returned value will only be used once; if it's desired that it should `stick', the user may modify the value stored in CONN's params field, but that is an issue outside of the scope of this interface -- params are only read, never written. */ error_t (*get_login_param) (struct ftp_conn *conn, int type, char **txt); /* Called after CONN's connection the server has closed for some reason. */ void (*closed) (struct ftp_conn *conn); /* Called when CONN is initially created before any other hook calls. An error return causes the creation to fail with that error code. */ error_t (*init) (struct ftp_conn *conn); /* Called when CONN is about to be destroyed. No hook calls are ever made after this one. */ void (*fini) (struct ftp_conn *conn); /* This hook should return true if the current thread has been interrupted in some way, and EINTR (or a short count in some cases) should be returned from a blocking function. */ int (*interrupt_check) (struct ftp_conn *conn); }; /* A single ftp connection. */ struct ftp_conn { const struct ftp_conn_params *params; /* machine, user, &c */ const struct ftp_conn_hooks *hooks; /* Customization hooks. */ struct ftp_conn_syshooks syshooks; /* host-dependent hook functions */ int syshooks_valid : 1; /* True if the system type has been determined. */ int control; /* fd for ftp control connection */ char *line; /* buffer for reading control replies */ size_t line_sz; /* allocated size of LINE */ size_t line_offs; /* Start of unread input in LINE. */ size_t line_len; /* End of the contents in LINE. */ char *reply_txt; /* A buffer for the text of entire replies */ size_t reply_txt_sz; /* size of it */ char *cwd; /* Last know CWD, or 0 if unknown. */ const char *type; /* Connection type, or 0 if default. */ void *hook; /* Random user data. */ int use_passive : 1; /* If true, first try passive data conns. */ struct sockaddr *actv_data_addr;/* Address of port for active data conns. */ }; /* Parameters for an ftp connection; doesn't include any actual connection state. */ struct ftp_conn_params { void *addr; /* Address. */ size_t addr_len; /* Length in bytes of ADDR. */ int addr_type; /* Type of ADDR (AF_*). */ char *user, *pass, *acct; /* Parameters for logging into ftp. */ }; /* Unix hooks */ extern error_t ftp_conn_unix_pasv_addr (struct ftp_conn *conn, const char *txt, struct sockaddr **addr); extern error_t ftp_conn_unix_interp_err (struct ftp_conn *conn, const char *txt, const error_t *poss_errs); extern error_t ftp_conn_unix_start_get_stats (struct ftp_conn *conn, const char *name, int contents, int *fd, void **state); extern error_t ftp_conn_unix_cont_get_stats (struct ftp_conn *conn, int fd, void *state, ftp_conn_add_stat_fun_t add_stat, void *hook); error_t ftp_conn_unix_append_name (struct ftp_conn *conn, const char *dir, const char *name, char **composite); error_t ftp_conn_unix_basename (struct ftp_conn *conn, char **name); extern struct ftp_conn_syshooks ftp_conn_unix_syshooks; error_t ftp_conn_get_raw_reply (struct ftp_conn *conn, int *reply, const char **reply_txt); error_t ftp_conn_get_reply (struct ftp_conn *conn, int *reply, const char **reply_txt); error_t ftp_conn_cmd (struct ftp_conn *conn, const char *cmd, const char *arg, int *reply, const char **reply_txt); error_t ftp_conn_cmd_reopen (struct ftp_conn *conn, const char *cmd, const char *arg, int *reply, const char **reply_txt); void ftp_conn_abort (struct ftp_conn *conn); /* Sets CONN's syshooks to a copy of SYSHOOKS. */ void ftp_conn_set_syshooks (struct ftp_conn *conn, struct ftp_conn_syshooks *syshooks); error_t ftp_conn_open (struct ftp_conn *conn); void ftp_conn_close (struct ftp_conn *conn); /* Makes sure that CONN's syshooks are set according to the remote system type. */ FTP_CONN_EI error_t ftp_conn_validate_syshooks (struct ftp_conn *conn) { if (conn->syshooks_valid) return 0; else /* Opening the connection should set the syshooks. */ return ftp_conn_open (conn); } /* Create a new ftp connection as specified by PARAMS, and return it in CONN; HOOKS contains customization hooks used by the connection. Neither PARAMS nor HOOKS is copied, so a copy of it should be made if necessary before calling this function; if it should be freed later, a FINI hook may be used to do so. */ error_t ftp_conn_create (const struct ftp_conn_params *params, const struct ftp_conn_hooks *hooks, struct ftp_conn **conn); /* Free the ftp connection CONN, closing it first, and freeing all resources it uses. */ void ftp_conn_free (struct ftp_conn *conn); /* Start a transfer command CMD (and optional args ...), returning a file descriptor in DATA. POSS_ERRS is a list of errnos to try matching against any resulting error text. */ error_t ftp_conn_start_transfer (struct ftp_conn *conn, const char *cmd, const char *arg, const error_t *poss_errs, int *data); /* Wait for the reply signalling the end of a data transfer. */ error_t ftp_conn_finish_transfer (struct ftp_conn *conn); /* Start retreiving file NAME over CONN, returning a file descriptor in DATA over which the data can be read. */ error_t ftp_conn_start_retrieve (struct ftp_conn *conn, const char *name, int *data); /* Start retreiving a list of files in NAME over CONN, returning a file descriptor in DATA over which the data can be read. */ error_t ftp_conn_start_list (struct ftp_conn *conn, const char *name, int *data); /* Start retreiving a directory listing of NAME over CONN, returning a file descriptor in DATA over which the data can be read. */ error_t ftp_conn_start_dir (struct ftp_conn *conn, const char *name, int *data); /* Start storing into file NAME over CONN, returning a file descriptor in DATA into which the data can be written. */ error_t ftp_conn_start_store (struct ftp_conn *conn, const char *name, int *data); /* Transfer the output of SRC_CMD/SRC_NAME on SRC_CONN to DST_NAME on DST_CONN, moving the data directly between servers. */ error_t ftp_conn_rmt_transfer (struct ftp_conn *src_conn, const char *src_cmd, const char *src_name, const int *src_poss_errs, struct ftp_conn *dst_conn, const char *dst_name); /* Copy the SRC_NAME on SRC_CONN to DST_NAME on DST_CONN, moving the data directly between servers. */ error_t ftp_conn_rmt_copy (struct ftp_conn *src_conn, const char *src_name, struct ftp_conn *dst_conn, const char *dst_name); /* Return a malloced string containing CONN's working directory in CWD. */ error_t ftp_conn_get_cwd (struct ftp_conn *conn, char **cwd); /* Return a malloced string containing CONN's working directory in CWD. */ error_t ftp_conn_cwd (struct ftp_conn *conn, const char *cwd); /* Return a malloced string containing CONN's working directory in CWD. */ error_t ftp_conn_cdup (struct ftp_conn *conn); /* Set the ftp connection type of CONN to TYPE, or return an error. */ error_t ftp_conn_set_type (struct ftp_conn *conn, const char *type); /* Start an operation to get a list of file-stat structures for NAME (this is often similar to ftp_conn_start_dir, but with OS-specific flags), and return a file-descriptor for reading on, and a state structure in STATE suitable for passing to cont_get_stats. If CONTENTS is true, NAME must refer to a directory, and the contents will be returned, otherwise, the (single) result will refer to NAME. */ error_t ftp_conn_start_get_stats (struct ftp_conn *conn, const char *name, int contents, int *fd, void **state); /* Read stats information from FD, calling ADD_STAT for each new stat (HOOK is passed to ADD_STAT). FD and STATE should be returned from start_get_stats. If this function returns EAGAIN, then it should be called again to finish the job (possibly after calling select on FD); if it returns 0, then it is finishe,d and FD and STATE are deallocated. */ error_t ftp_conn_cont_get_stats (struct ftp_conn *conn, int fd, void *state, ftp_conn_add_stat_fun_t add_stat, void *hook); /* Get a list of file-stat structures for NAME, calling ADD_STAT for each one (HOOK is passed to ADD_STAT). If CONTENTS is true, NAME must refer to a directory, and the contents will be returned, otherwise, the (single) result will refer to NAME. This function may block. */ error_t ftp_conn_get_stats (struct ftp_conn *conn, const char *name, int contents, ftp_conn_add_stat_fun_t add_stat, void *hook); /* The type of the function called by ...get_names to add each new name. NAME is the name in question and HOOK is as passed into ...get_stats. */ typedef error_t (*ftp_conn_add_name_fun_t) (const char *name, void *hook); /* Start an operation to get a list of filenames in the directory NAME, and return a file-descriptor for reading on, and a state structure in STATE suitable for passing to cont_get_names. */ error_t ftp_conn_start_get_names (struct ftp_conn *conn, const char *name, int *fd, void **state); /* Read filenames from FD, calling ADD_NAME for each new NAME (HOOK is passed to ADD_NAME). FD and STATE should be returned from start_get_stats. If this function returns EAGAIN, then it should be called again to finish the job (possibly after calling select on FD); if it returns 0, then it is finishe,d and FD and STATE are deallocated. */ error_t ftp_conn_cont_get_names (struct ftp_conn *conn, int fd, void *state, ftp_conn_add_name_fun_t add_name, void *hook); /* Get a list of names in the directory NAME, calling ADD_NAME for each one (HOOK is passed to ADD_NAME). This function may block. */ error_t ftp_conn_get_names (struct ftp_conn *conn, const char *name, ftp_conn_add_name_fun_t add_name, void *hook); /* Give a name which refers to a directory file, and a name in that directory, this should return in COMPOSITE the composite name refering to that name in that directory, in malloced storage. */ error_t ftp_conn_append_name (struct ftp_conn *conn, const char *dir, const char *name, char **composite); /* If the name of a file COMPOSITE is a composite name (containing both a filename and a directory name), this function will return the name component only in BASE, in malloced storage, otherwise it simply returns a newly malloced copy of COMPOSITE in BASE. */ error_t ftp_conn_basename (struct ftp_conn *conn, const char *composite, char **base); #endif /* __FTPCONN_H__ */
diegonc/console-xkb-support
libftpconn/ftpconn.h
C
gpl-2.0
16,482
/* * Block driver for media (i.e., flash cards) * * Copyright 2002 Hewlett-Packard Company * Copyright 2005-2008 Pierre Ossman * * Use consistent with the GNU GPL is permitted, * provided that this copyright notice is * preserved in its entirety in all copies and derived works. * * HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED, * AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS * FITNESS FOR ANY PARTICULAR PURPOSE. * * Many thanks to Alessandro Rubini and Jonathan Corbet! * * Author: Andrew Christian * 28 May 2002 */ #include <linux/moduleparam.h> #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/hdreg.h> #include <linux/kdev_t.h> #include <linux/blkdev.h> #include <linux/mutex.h> #include <linux/scatterlist.h> #include <linux/string_helpers.h> #include <linux/delay.h> #include <linux/capability.h> #include <linux/compat.h> #include <linux/sysfs.h> #include <linux/mmc/ioctl.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <asm/uaccess.h> #include "queue.h" MODULE_ALIAS("mmc:block"); #if defined(CONFIG_MMC_CPRM) #include "cprmdrv_samsung.h" #include <linux/ioctl.h> #define MMC_IOCTL_BASE 0xB3 /* Same as MMC block device major number */ #define MMC_IOCTL_GET_SECTOR_COUNT _IOR(MMC_IOCTL_BASE, 100, int) #define MMC_IOCTL_GET_SECTOR_SIZE _IOR(MMC_IOCTL_BASE, 101, int) #define MMC_IOCTL_GET_BLOCK_SIZE _IOR(MMC_IOCTL_BASE, 102, int) #define MMC_IOCTL_SET_RETRY_AKE_PROCESS _IOR(MMC_IOCTL_BASE, 104, int) static int cprm_ake_retry_flag; #endif #ifdef MODULE_PARAM_PREFIX #undef MODULE_PARAM_PREFIX #endif #define MODULE_PARAM_PREFIX "mmcblk." #define INAND_CMD38_ARG_EXT_CSD 113 #define INAND_CMD38_ARG_ERASE 0x00 #define INAND_CMD38_ARG_TRIM 0x01 #define INAND_CMD38_ARG_SECERASE 0x80 #define INAND_CMD38_ARG_SECTRIM1 0x81 #define INAND_CMD38_ARG_SECTRIM2 0x88 #define MMC_BLK_TIMEOUT_MS (30 * 1000) /* 30 sec timeout */ #define MMC_SANITIZE_REQ_TIMEOUT 240000 /* msec */ #define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \ (req->cmd_flags & REQ_META)) && \ (rq_data_dir(req) == WRITE)) #define PACKED_CMD_VER 0x01 #define PACKED_CMD_WR 0x02 #define MMC_BLK_UPDATE_STOP_REASON(stats, reason) \ do { \ if (stats->enabled) \ stats->pack_stop_reason[reason]++; \ } while (0) static DEFINE_MUTEX(block_mutex); /* * The defaults come from config options but can be overriden by module * or bootarg options. */ static int perdev_minors = CONFIG_MMC_BLOCK_MINORS; /* * We've only got one major, so number of mmcblk devices is * limited to 256 / number of minors per device. */ static int max_devices; /* 256 minors, so at most 256 separate devices */ static DECLARE_BITMAP(dev_use, 256); static DECLARE_BITMAP(name_use, 256); /* * There is one mmc_blk_data per slot. */ struct mmc_blk_data { spinlock_t lock; struct gendisk *disk; struct mmc_queue queue; struct list_head part; unsigned int flags; #define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */ #define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */ unsigned int usage; unsigned int read_only; unsigned int part_type; unsigned int name_idx; unsigned int reset_done; #define MMC_BLK_READ BIT(0) #define MMC_BLK_WRITE BIT(1) #define MMC_BLK_DISCARD BIT(2) #define MMC_BLK_SECDISCARD BIT(3) /* * Only set in main mmc_blk_data associated * with mmc_card with mmc_set_drvdata, and keeps * track of the current selected device partition. */ unsigned int part_curr; struct device_attribute force_ro; struct device_attribute power_ro_lock; struct device_attribute num_wr_reqs_to_start_packing; struct device_attribute bkops_check_threshold; int area_type; }; static DEFINE_MUTEX(open_lock); enum { MMC_PACKED_N_IDX = -1, MMC_PACKED_N_ZERO, MMC_PACKED_N_SINGLE, }; module_param(perdev_minors, int, 0444); MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device"); static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq) { mqrq->packed_cmd = MMC_PACKED_NONE; mqrq->packed_num = MMC_PACKED_N_ZERO; } static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk) { struct mmc_blk_data *md; mutex_lock(&open_lock); md = disk->private_data; if (md && md->usage == 0) md = NULL; if (md) md->usage++; mutex_unlock(&open_lock); return md; } static inline int mmc_get_devidx(struct gendisk *disk) { int devidx = disk->first_minor / perdev_minors; return devidx; } static void mmc_blk_put(struct mmc_blk_data *md) { mutex_lock(&open_lock); md->usage--; if (md->usage == 0) { int devidx = mmc_get_devidx(md->disk); blk_cleanup_queue(md->queue.queue); __clear_bit(devidx, dev_use); put_disk(md->disk); kfree(md); } mutex_unlock(&open_lock); } static ssize_t power_ro_lock_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int locked = 0; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN) locked = 2; else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN) locked = 1; ret = snprintf(buf, PAGE_SIZE, "%d\n", locked); return ret; } static ssize_t power_ro_lock_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; struct mmc_blk_data *md, *part_md; struct mmc_card *card; unsigned long set; if (kstrtoul(buf, 0, &set)) return -EINVAL; if (set != 1) return count; md = mmc_blk_get(dev_to_disk(dev)); card = md->queue.card; mmc_claim_host(card->host); ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP, card->ext_csd.boot_ro_lock | EXT_CSD_BOOT_WP_B_PWR_WP_EN, card->ext_csd.part_time); if (ret) pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret); else card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN; mmc_release_host(card->host); if (!ret) { pr_info("%s: Locking boot partition ro until next power on\n", md->disk->disk_name); set_disk_ro(md->disk, 1); list_for_each_entry(part_md, &md->part, part) if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) { pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name); set_disk_ro(part_md->disk, 1); } } mmc_blk_put(md); return count; } static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); ret = snprintf(buf, PAGE_SIZE, "%d", get_disk_ro(dev_to_disk(dev)) ^ md->read_only); mmc_blk_put(md); return ret; } static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; char *end; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); unsigned long set = simple_strtoul(buf, &end, 0); if (end == buf) { ret = -EINVAL; goto out; } set_disk_ro(dev_to_disk(dev), set || md->read_only); ret = count; out: mmc_blk_put(md); return ret; } static ssize_t num_wr_reqs_to_start_packing_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); int num_wr_reqs_to_start_packing; int ret; num_wr_reqs_to_start_packing = md->queue.num_wr_reqs_to_start_packing; ret = snprintf(buf, PAGE_SIZE, "%d\n", num_wr_reqs_to_start_packing); mmc_blk_put(md); return ret; } static ssize_t num_wr_reqs_to_start_packing_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int value; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); sscanf(buf, "%d", &value); if (value >= 0) md->queue.num_wr_reqs_to_start_packing = value; mmc_blk_put(md); return count; } static ssize_t bkops_check_threshold_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; int ret; if (!card) ret = -EINVAL; else ret = snprintf(buf, PAGE_SIZE, "%d\n", card->bkops_info.size_percentage_to_queue_delayed_work); mmc_blk_put(md); return ret; } static ssize_t bkops_check_threshold_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int value; struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev)); struct mmc_card *card = md->queue.card; unsigned int card_size; int ret = count; if (!card) { ret = -EINVAL; goto exit; } sscanf(buf, "%d", &value); if ((value <= 0) || (value >= 100)) { ret = -EINVAL; goto exit; } card_size = (unsigned int)get_capacity(md->disk); if (card_size <= 0) { ret = -EINVAL; goto exit; } card->bkops_info.size_percentage_to_queue_delayed_work = value; card->bkops_info.min_sectors_to_queue_delayed_work = (card_size * value) / 100; pr_debug("%s: size_percentage = %d, min_sectors = %d", mmc_hostname(card->host), card->bkops_info.size_percentage_to_queue_delayed_work, card->bkops_info.min_sectors_to_queue_delayed_work); exit: mmc_blk_put(md); return count; } static int mmc_blk_open(struct block_device *bdev, fmode_t mode) { struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk); int ret = -ENXIO; mutex_lock(&block_mutex); if (md) { if (md->usage == 2) check_disk_change(bdev); ret = 0; if ((mode & FMODE_WRITE) && md->read_only) { mmc_blk_put(md); ret = -EROFS; } } mutex_unlock(&block_mutex); return ret; } static int mmc_blk_release(struct gendisk *disk, fmode_t mode) { struct mmc_blk_data *md = disk->private_data; mutex_lock(&block_mutex); mmc_blk_put(md); mutex_unlock(&block_mutex); return 0; } static int mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo) { geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16); geo->heads = 4; geo->sectors = 16; return 0; } struct mmc_blk_ioc_data { struct mmc_ioc_cmd ic; unsigned char *buf; u64 buf_bytes; }; static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user( struct mmc_ioc_cmd __user *user) { struct mmc_blk_ioc_data *idata; int err; idata = kzalloc(sizeof(*idata), GFP_KERNEL); if (!idata) { err = -ENOMEM; goto out; } if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) { err = -EFAULT; goto idata_err; } idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks; if (idata->buf_bytes > MMC_IOC_MAX_BYTES) { err = -EOVERFLOW; goto idata_err; } if (!idata->buf_bytes) return idata; idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL); if (!idata->buf) { err = -ENOMEM; goto idata_err; } if (copy_from_user(idata->buf, (void __user *)(unsigned long) idata->ic.data_ptr, idata->buf_bytes)) { err = -EFAULT; goto copy_err; } return idata; copy_err: kfree(idata->buf); idata_err: kfree(idata); out: return ERR_PTR(err); } struct scatterlist *mmc_blk_get_sg(struct mmc_card *card, unsigned char *buf, int *sg_len, int size) { struct scatterlist *sg; struct scatterlist *sl; int total_sec_cnt, sec_cnt; int max_seg_size, len; total_sec_cnt = size; max_seg_size = card->host->max_seg_size; len = (size - 1 + max_seg_size) / max_seg_size; sl = kmalloc(sizeof(struct scatterlist) * len, GFP_KERNEL); if (!sl) { return NULL; } sg = (struct scatterlist *)sl; sg_init_table(sg, len); while (total_sec_cnt) { if (total_sec_cnt < max_seg_size) sec_cnt = total_sec_cnt; else sec_cnt = max_seg_size; sg_set_page(sg, virt_to_page(buf), sec_cnt, offset_in_page(buf)); buf = buf + sec_cnt; total_sec_cnt = total_sec_cnt - sec_cnt; if (total_sec_cnt == 0) break; sg = sg_next(sg); } if (sg) sg_mark_end(sg); *sg_len = len; return sl; } static int mmc_blk_ioctl_cmd(struct block_device *bdev, struct mmc_ioc_cmd __user *ic_ptr) { struct mmc_blk_ioc_data *idata; struct mmc_blk_data *md; struct mmc_card *card; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct mmc_request mrq = {NULL}; struct scatterlist *sg = 0; int err=0; /* * The caller must have CAP_SYS_RAWIO, and must be calling this on the * whole block device, not on a partition. This prevents overspray * between sibling partitions. */ if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains)) return -EPERM; idata = mmc_blk_ioctl_copy_from_user(ic_ptr); if (IS_ERR(idata)) return PTR_ERR(idata); md = mmc_blk_get(bdev->bd_disk); if (!md) { err = -EINVAL; goto cmd_done; } card = md->queue.card; if (IS_ERR(card)) { err = PTR_ERR(card); goto cmd_done; } cmd.opcode = idata->ic.opcode; cmd.arg = idata->ic.arg; cmd.flags = idata->ic.flags; if (idata->buf_bytes) { int len; data.blksz = idata->ic.blksz; data.blocks = idata->ic.blocks; sg = mmc_blk_get_sg(card, idata->buf, &len, idata->buf_bytes); data.sg = sg; data.sg_len = len; if (idata->ic.write_flag) data.flags = MMC_DATA_WRITE; else data.flags = MMC_DATA_READ; /* data.flags must already be set before doing this. */ mmc_set_data_timeout(&data, card); /* Allow overriding the timeout_ns for empirical tuning. */ if (idata->ic.data_timeout_ns) data.timeout_ns = idata->ic.data_timeout_ns; if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) { /* * Pretend this is a data transfer and rely on the * host driver to compute timeout. When all host * drivers support cmd.cmd_timeout for R1B, this * can be changed to: * * mrq.data = NULL; * cmd.cmd_timeout = idata->ic.cmd_timeout_ms; */ data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000; } mrq.data = &data; } mrq.cmd = &cmd; mmc_claim_host(card->host); if (idata->ic.is_acmd) { err = mmc_app_cmd(card->host, card); if (err) goto cmd_rel_host; } mmc_wait_for_req(card->host, &mrq); if (cmd.error) { dev_err(mmc_dev(card->host), "%s: cmd error %d\n", __func__, cmd.error); err = cmd.error; goto cmd_rel_host; } if (data.error) { dev_err(mmc_dev(card->host), "%s: data error %d\n", __func__, data.error); err = data.error; goto cmd_rel_host; } /* * According to the SD specs, some commands require a delay after * issuing the command. */ if (idata->ic.postsleep_min_us) usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us); if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) { err = -EFAULT; goto cmd_rel_host; } if (!idata->ic.write_flag) { if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr, idata->buf, idata->buf_bytes)) { err = -EFAULT; goto cmd_rel_host; } } cmd_rel_host: mmc_release_host(card->host); cmd_done: mmc_blk_put(md); if (sg) kfree(sg); kfree(idata->buf); kfree(idata); return err; } static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { #if defined(CONFIG_MMC_CPRM) struct mmc_blk_data *md = bdev->bd_disk->private_data; struct mmc_card *card = md->queue.card; static int i; static unsigned long temp_arg[16] = {0}; #endif int ret = -EINVAL; if (cmd == MMC_IOC_CMD) ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg); #if defined(CONFIG_MMC_CPRM) printk(KERN_DEBUG " %s ], %x ", __func__, cmd); switch (cmd) { case MMC_IOCTL_SET_RETRY_AKE_PROCESS: cprm_ake_retry_flag = 1; ret = 0; break; case MMC_IOCTL_GET_SECTOR_COUNT: { int size = 0; size = (int)get_capacity(md->disk) << 9; printk(KERN_DEBUG "[%s]:MMC_IOCTL_GET_SECTOR_COUNT size = %d\n", __func__, size); return copy_to_user((void *)arg, &size, sizeof(u64)); } break; case ACMD13: case ACMD18: case ACMD25: case ACMD43: case ACMD44: case ACMD45: case ACMD46: case ACMD47: case ACMD48: { struct cprm_request *req = (struct cprm_request *)arg; printk(KERN_DEBUG "%s:cmd [%x]\n", __func__, cmd); if (cmd == ACMD43) { printk(KERN_DEBUG"storing acmd43 arg[%d] = %ul\n", i, (unsigned int)req->arg); temp_arg[i] = req->arg; i++; if (i >= 16) { printk(KERN_DEBUG"reset acmd43 i = %d\n", i); i = 0; } } if (cmd == ACMD45 && cprm_ake_retry_flag == 1) { cprm_ake_retry_flag = 0; printk(KERN_DEBUG"ACMD45.. I'll call ACMD43 and ACMD44 first\n"); for (i = 0; i < 16; i++) { printk(KERN_DEBUG"calling ACMD43 with arg[%d] = %ul\n", i, (unsigned int)temp_arg[i]); if (stub_sendcmd(card, ACMD43, temp_arg[i], 512, NULL) < 0) { printk(KERN_DEBUG"error ACMD43 %d\n", i); return -EINVAL; } } printk(KERN_DEBUG"calling ACMD44\n"); if (stub_sendcmd(card, ACMD44, 0, 8, NULL) < 0) { printk(KERN_DEBUG"error in ACMD44 %d\n", i); return -EINVAL; } } return stub_sendcmd(card, req->cmd, req->arg, req->len, req->buff); } break; default: printk(KERN_DEBUG"%s: Invalid ioctl command\n", __func__); break; } #endif return ret; } #ifdef CONFIG_COMPAT static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg)); } #endif static const struct block_device_operations mmc_bdops = { .open = mmc_blk_open, .release = mmc_blk_release, .getgeo = mmc_blk_getgeo, .owner = THIS_MODULE, .ioctl = mmc_blk_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = mmc_blk_compat_ioctl, #endif }; static inline int mmc_blk_part_switch(struct mmc_card *card, struct mmc_blk_data *md) { int ret; struct mmc_blk_data *main_md = mmc_get_drvdata(card); if (main_md->part_curr == md->part_type) return 0; if (mmc_card_mmc(card)) { u8 part_config = card->ext_csd.part_config; part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK; part_config |= md->part_type; ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_PART_CONFIG, part_config, card->ext_csd.part_time); if (ret) return ret; card->ext_csd.part_config = part_config; } main_md->part_curr = md->part_type; return 0; } static u32 mmc_sd_num_wr_blocks(struct mmc_card *card) { int err; u32 result; __be32 *blocks; struct mmc_request mrq = {NULL}; struct mmc_command cmd = {0}; struct mmc_data data = {0}; struct scatterlist sg; cmd.opcode = MMC_APP_CMD; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) return (u32)-1; if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD)) return (u32)-1; memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = SD_APP_SEND_NUM_WR_BLKS; cmd.arg = 0; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; data.blksz = 4; data.blocks = 1; data.flags = MMC_DATA_READ; data.sg = &sg; data.sg_len = 1; mmc_set_data_timeout(&data, card); mrq.cmd = &cmd; mrq.data = &data; blocks = kmalloc(4, GFP_KERNEL); if (!blocks) return (u32)-1; sg_init_one(&sg, blocks, 4); mmc_wait_for_req(card->host, &mrq); result = ntohl(*blocks); kfree(blocks); if (cmd.error || data.error) result = (u32)-1; return result; } static int send_stop(struct mmc_card *card, u32 *status) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_STOP_TRANSMISSION; cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 5); if (err == 0) *status = cmd.resp[0]; return err; } static int get_card_status(struct mmc_card *card, u32 *status, int retries) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, retries); if (err == 0) *status = cmd.resp[0]; return err; } #define ERR_NOMEDIUM 3 #define ERR_RETRY 2 #define ERR_ABORT 1 #define ERR_CONTINUE 0 static int mmc_blk_cmd_error(struct request *req, const char *name, int error, bool status_valid, u32 status) { switch (error) { case -EILSEQ: /* response crc error, retry the r/w cmd */ pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "response CRC error", name, status); return ERR_RETRY; case -ETIMEDOUT: pr_err("%s: %s sending %s command, card status %#x\n", req->rq_disk->disk_name, "timed out", name, status); /* If the status cmd initially failed, retry the r/w cmd */ if (!status_valid) { pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name); return ERR_RETRY; } /* * If it was a r/w cmd crc error, or illegal command * (eg, issued in wrong state) then retry - we should * have corrected the state problem above. */ if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) { pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name); return ERR_RETRY; } /* Otherwise abort the command */ pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name); return ERR_ABORT; default: /* We don't understand the error code the driver gave us */ pr_err("%s: unknown error %d sending read/write command, card status %#x\n", req->rq_disk->disk_name, error, status); return ERR_ABORT; } } /* * Initial r/w and stop cmd error recovery. * We don't know whether the card received the r/w cmd or not, so try to * restore things back to a sane state. Essentially, we do this as follows: * - Obtain card status. If the first attempt to obtain card status fails, * the status word will reflect the failed status cmd, not the failed * r/w cmd. If we fail to obtain card status, it suggests we can no * longer communicate with the card. * - Check the card state. If the card received the cmd but there was a * transient problem with the response, it might still be in a data transfer * mode. Try to send it a stop command. If this fails, we can't recover. * - If the r/w cmd failed due to a response CRC error, it was probably * transient, so retry the cmd. * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry. * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or * illegal cmd, retry. * Otherwise we don't understand what happened, so abort. */ static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req, struct mmc_blk_request *brq, int *ecc_err, int *gen_err) { bool prev_cmd_status_valid = true; u32 status, stop_status = 0; int err, retry; if (mmc_card_removed(card)) return ERR_NOMEDIUM; /* * Try to get card status which indicates both the card state * and why there was no response. If the first attempt fails, * we can't be sure the returned status is for the r/w command. */ for (retry = 2; retry >= 0; retry--) { err = get_card_status(card, &status, 0); if (!err) break; prev_cmd_status_valid = false; pr_err("%s: error %d sending status command, %sing\n", req->rq_disk->disk_name, err, retry ? "retry" : "abort"); } /* We couldn't get a response from the card. Give up. */ if (err) { /* Check if the card is removed */ if (mmc_detect_card_removed(card->host)) return ERR_NOMEDIUM; return ERR_ABORT; } /* Flag ECC errors */ if ((status & R1_CARD_ECC_FAILED) || (brq->stop.resp[0] & R1_CARD_ECC_FAILED) || (brq->cmd.resp[0] & R1_CARD_ECC_FAILED)) *ecc_err = 1; /* Flag General errors */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) if ((status & R1_ERROR) || (brq->stop.resp[0] & R1_ERROR)) { pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0], status); *gen_err = 1; } /* * Check the current card state. If it is in some data transfer * mode, tell it to stop (and hopefully transition back to TRAN.) */ if (R1_CURRENT_STATE(status) == R1_STATE_DATA || R1_CURRENT_STATE(status) == R1_STATE_RCV) { err = send_stop(card, &stop_status); if (err) pr_err("%s: error %d sending stop command\n", req->rq_disk->disk_name, err); /* * If the stop cmd also timed out, the card is probably * not present, so abort. Other errors are bad news too. */ if (err) return ERR_ABORT; if (stop_status & R1_CARD_ECC_FAILED) *ecc_err = 1; if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) if (stop_status & R1_ERROR) { pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n", req->rq_disk->disk_name, __func__, stop_status); *gen_err = 1; } } /* Check for set block count errors */ if (brq->sbc.error) return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error, prev_cmd_status_valid, status); /* Check for r/w command errors */ if (brq->cmd.error) return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error, prev_cmd_status_valid, status); /* Data errors */ if (!brq->stop.error) return ERR_CONTINUE; /* Now for stop errors. These aren't fatal to the transfer. */ pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->stop.error, brq->cmd.resp[0], status); /* * Subsitute in our own stop status as this will give the error * state which happened during the execution of the r/w command. */ if (stop_status) { brq->stop.resp[0] = stop_status; brq->stop.error = 0; } return ERR_CONTINUE; } static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host, int type) { int err; if (md->reset_done & type) return -EEXIST; md->reset_done |= type; err = mmc_hw_reset(host); /* Ensure we switch back to the correct partition */ if (err != -EOPNOTSUPP) { struct mmc_blk_data *main_md = mmc_get_drvdata(host->card); int part_err; main_md->part_curr = main_md->part_type; part_err = mmc_blk_part_switch(host->card, md); if (part_err) { /* * We have failed to get back into the correct * partition, so we need to abort the whole request. */ return -ENODEV; } } return err; } static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type) { md->reset_done &= ~type; } static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_DISCARD; if (!mmc_can_erase(card)) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (card->ext_csd.bkops_en) card->bkops_info.sectors_changed += blk_rq_sectors(req); if (mmc_can_discard(card)) arg = MMC_DISCARD_ARG; else if (mmc_can_trim(card)) arg = MMC_TRIM_ARG; else arg = MMC_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_TRIM_ARG ? INAND_CMD38_ARG_TRIM : INAND_CMD38_ARG_ERASE, 0); if (err) goto out; } err = mmc_erase(card, from, nr, arg); out: if (err == -EIO && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; unsigned int from, nr, arg; int err = 0, type = MMC_BLK_SECDISCARD; if (!(mmc_can_secure_erase_trim(card))) { err = -EOPNOTSUPP; goto out; } from = blk_rq_pos(req); nr = blk_rq_sectors(req); if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr)) arg = MMC_SECURE_TRIM1_ARG; else arg = MMC_SECURE_ERASE_ARG; retry: if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, arg == MMC_SECURE_TRIM1_ARG ? INAND_CMD38_ARG_SECTRIM1 : INAND_CMD38_ARG_SECERASE, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, arg); if (err == -EIO) goto out_retry; if (err) goto out; if (arg == MMC_SECURE_TRIM1_ARG) { if (card->quirks & MMC_QUIRK_INAND_CMD38) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, INAND_CMD38_ARG_EXT_CSD, INAND_CMD38_ARG_SECTRIM2, 0); if (err) goto out_retry; } err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG); if (err == -EIO) goto out_retry; if (err) goto out; } if (mmc_can_sanitize(card) && (card->host->caps2 & MMC_CAP2_SANITIZE)) err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_SANITIZE_START, 1, 0); out_retry: if (err && !mmc_blk_reset(md, card->host, type)) goto retry; if (!err) mmc_blk_reset_success(md, type); out: blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_sanitize_rq(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; int err = 0; BUG_ON(!card); BUG_ON(!card->host); if (!(mmc_can_sanitize(card) && (card->host->caps2 & MMC_CAP2_SANITIZE))) { pr_warning("%s: %s - SANITIZE is not supported\n", mmc_hostname(card->host), __func__); err = -EOPNOTSUPP; goto out; } pr_debug("%s: %s - SANITIZE IN PROGRESS...\n", mmc_hostname(card->host), __func__); err = mmc_switch_ignore_timeout(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_SANITIZE_START, 1, MMC_SANITIZE_REQ_TIMEOUT); if (err) pr_err("%s: %s - mmc_switch() with " "EXT_CSD_SANITIZE_START failed. err=%d\n", mmc_hostname(card->host), __func__, err); pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host), __func__); out: blk_end_request(req, err, blk_rq_bytes(req)); return err ? 0 : 1; } static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; int ret = 0; ret = mmc_flush_cache(card); if (ret) ret = -EIO; blk_end_request_all(req, ret); return ret ? 0 : 1; } /* * Reformat current write as a reliable write, supporting * both legacy and the enhanced reliable write MMC cards. * In each transfer we'll handle only as much as a single * reliable write can handle, thus finish the request in * partial completions. */ static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq, struct mmc_card *card, struct request *req) { if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) { /* Legacy mode imposes restrictions on transfers. */ if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors)) brq->data.blocks = 1; if (brq->data.blocks > card->ext_csd.rel_sectors) brq->data.blocks = card->ext_csd.rel_sectors; else if (brq->data.blocks < card->ext_csd.rel_sectors) brq->data.blocks = 1; } } #define CMD_ERRORS \ (R1_OUT_OF_RANGE | /* Command argument out of range */ \ R1_ADDRESS_ERROR | /* Misaligned address */ \ R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\ R1_WP_VIOLATION | /* Tried to write to protected block */ \ R1_CC_ERROR | /* Card controller error */ \ R1_ERROR) /* General/unknown error */ static int mmc_blk_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req, mmc_active); struct mmc_blk_request *brq = &mq_mrq->brq; struct request *req = mq_mrq->req; int ecc_err = 0, gen_err = 0; /* * sbc.error indicates a problem with the set block count * command. No data will have been transferred. * * cmd.error indicates a problem with the r/w command. No * data will have been transferred. * * stop.error indicates a problem with the stop command. Data * may have been transferred, or may still be transferring. */ if (brq->sbc.error || brq->cmd.error || brq->stop.error || brq->data.error) { switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) { case ERR_RETRY: return MMC_BLK_RETRY; case ERR_ABORT: return MMC_BLK_ABORT; case ERR_NOMEDIUM: return MMC_BLK_NOMEDIUM; case ERR_CONTINUE: break; } } /* * Check for errors relating to the execution of the * initial command - such as address errors. No data * has been transferred. */ if (brq->cmd.resp[0] & CMD_ERRORS) { pr_err("%s: r/w command failed, status = %#x\n", req->rq_disk->disk_name, brq->cmd.resp[0]); return MMC_BLK_ABORT; } /* * Everything else is either success, or a data error of some * kind. If it was a write, we may have transitioned to * program mode, which we have to wait for it to complete. */ if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) { u32 status; unsigned long timeout; /* Check stop command response */ if (brq->stop.resp[0] & R1_ERROR) { pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n", req->rq_disk->disk_name, __func__, brq->stop.resp[0]); gen_err = 1; } timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS); do { int err = get_card_status(card, &status, 5); if (err) { pr_err("%s: error %d requesting status\n", req->rq_disk->disk_name, err); return MMC_BLK_CMD_ERR; } /* Timeout if the device never becomes ready for data * and never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state!"\ " %s %s\n", mmc_hostname(card->host), req->rq_disk->disk_name, __func__); return MMC_BLK_CMD_ERR; } if (status & R1_ERROR) { pr_err("%s: %s: general error sending status command, card status %#x\n", req->rq_disk->disk_name, __func__, status); gen_err = 1; } /* * Some cards mishandle the status bits, * so make sure to check both the busy * indication and the card state. */ } while (!(status & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(status) == R1_STATE_PRG)); } /* if general error occurs, retry the write operation. */ if (gen_err) { pr_warning("%s: retrying write for general error\n", req->rq_disk->disk_name); return MMC_BLK_RETRY; } if (brq->data.error) { pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n", req->rq_disk->disk_name, brq->data.error, (unsigned)blk_rq_pos(req), (unsigned)blk_rq_sectors(req), brq->cmd.resp[0], brq->stop.resp[0]); if (rq_data_dir(req) == READ) { if (ecc_err) return MMC_BLK_ECC_ERR; return MMC_BLK_DATA_ERR; } else { return MMC_BLK_CMD_ERR; } } if (!brq->data.bytes_xfered) return MMC_BLK_RETRY; if (mq_mrq->packed_cmd != MMC_PACKED_NONE) { if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered)) return MMC_BLK_PARTIAL; else return MMC_BLK_SUCCESS; } if (blk_rq_bytes(req) != brq->data.bytes_xfered) return MMC_BLK_PARTIAL; return MMC_BLK_SUCCESS; } static int mmc_blk_packed_err_check(struct mmc_card *card, struct mmc_async_req *areq) { struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); struct request *req = mq_rq->req; int err, check, status; u8 ext_csd[512]; mq_rq->packed_retries--; check = mmc_blk_err_check(card, areq); err = get_card_status(card, &status, 0); if (err) { pr_err("%s: error %d sending status command\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if (status & R1_EXCEPTION_EVENT) { err = mmc_send_ext_csd(card, ext_csd); if (err) { pr_err("%s: error %d sending ext_csd\n", req->rq_disk->disk_name, err); return MMC_BLK_ABORT; } if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] & EXT_CSD_PACKED_FAILURE) && (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_GENERIC_ERROR)) { if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] & EXT_CSD_PACKED_INDEXED_ERROR) { mq_rq->packed_fail_idx = ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1; return MMC_BLK_PARTIAL; } } } return check; } static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, int disable_multi, struct mmc_queue *mq) { u32 readcmd, writecmd; struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct mmc_blk_data *md = mq->data; bool do_data_tag; /* * Reliable writes are used to implement Forced Unit Access and * REQ_META accesses, and are supported only on MMCs. * * XXX: this really needs a good explanation of why REQ_META * is treated special. */ bool do_rel_wr = ((req->cmd_flags & REQ_FUA) || (req->cmd_flags & REQ_META)) && (rq_data_dir(req) == WRITE) && (md->flags & MMC_BLK_REL_WR); memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; if (rq_data_dir(req) == WRITE) brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; else brq->stop.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1B | MMC_CMD_AC; brq->data.blocks = blk_rq_sectors(req); brq->data.fault_injected = false; /* * The block layer doesn't support all sector count * restrictions, so we need to be prepared for too big * requests. */ if (brq->data.blocks > card->host->max_blk_count) brq->data.blocks = card->host->max_blk_count; if (brq->data.blocks > 1) { /* * After a read error, we redo the request one sector * at a time in order to accurately determine which * sectors can be read successfully. */ if (disable_multi) brq->data.blocks = 1; /* Some controllers can't do multiblock reads due to hw bugs */ if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ && rq_data_dir(req) == READ) brq->data.blocks = 1; } if (brq->data.blocks > 1 || do_rel_wr) { /* SPI multiblock writes terminate using a special * token, not a STOP_TRANSMISSION request. */ if (!mmc_host_is_spi(card->host) || rq_data_dir(req) == READ) brq->mrq.stop = &brq->stop; readcmd = MMC_READ_MULTIPLE_BLOCK; writecmd = MMC_WRITE_MULTIPLE_BLOCK; } else { brq->mrq.stop = NULL; readcmd = MMC_READ_SINGLE_BLOCK; writecmd = MMC_WRITE_BLOCK; } if (rq_data_dir(req) == READ) { brq->cmd.opcode = readcmd; brq->data.flags |= MMC_DATA_READ; } else { brq->cmd.opcode = writecmd; brq->data.flags |= MMC_DATA_WRITE; } if (do_rel_wr) mmc_apply_rel_rw(brq, card, req); /* * Data tag is used only during writing meta data to speed * up write and any subsequent read of this meta data */ do_data_tag = (card->ext_csd.data_tag_unit_size) && (req->cmd_flags & REQ_META) && (rq_data_dir(req) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* * Pre-defined multi-block transfers are preferable to * open ended-ones (and necessary for reliable writes). * However, it is not sufficient to just send CMD23, * and avoid the final CMD12, as on an error condition * CMD12 (stop) needs to be sent anyway. This, coupled * with Auto-CMD23 enhancements provided by some * hosts, means that the complexity of dealing * with this is best left to the host. If CMD23 is * supported by card and host, we'll fill sbc in and let * the host deal with handling it correctly. This means * that for hosts that don't expose MMC_CAP_CMD23, no * change of behavior will be observed. * * N.B: Some MMC cards experience perf degradation. * We'll avoid using CMD23-bounded multiblock writes for * these, while retaining features like reliable writes. */ if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) && (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) || do_data_tag)) { brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = brq->data.blocks | (do_rel_wr ? (1 << 31) : 0) | (do_data_tag ? (1 << 29) : 0); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->mrq.sbc = &brq->sbc; } mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); /* * Adjust the sg list so it is the same size as the * request. */ if (brq->data.blocks != blk_rq_sectors(req)) { int i, data_size = brq->data.blocks << 9; struct scatterlist *sg; for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) { data_size -= sg->length; if (data_size <= 0) { sg->length += data_size; i++; break; } } brq->data.sg_len = i; } mqrq->mmc_active.mrq = &brq->mrq; mqrq->mmc_active.err_check = mmc_blk_err_check; mmc_queue_bounce_pre(mqrq); } static void mmc_blk_write_packing_control(struct mmc_queue *mq, struct request *req) { struct mmc_host *host = mq->card->host; int data_dir; if (!(host->caps2 & MMC_CAP2_PACKED_WR)) return; /* * In case the packing control is not supported by the host, it should * not have an effect on the write packing. Therefore we have to enable * the write packing */ if (!(host->caps2 & MMC_CAP2_PACKED_WR_CONTROL)) { mq->wr_packing_enabled = true; return; } if (!req || (req && (req->cmd_flags & REQ_FLUSH))) { if (mq->num_of_potential_packed_wr_reqs > mq->num_wr_reqs_to_start_packing) mq->wr_packing_enabled = true; mq->num_of_potential_packed_wr_reqs = 0; return; } data_dir = rq_data_dir(req); if (data_dir == READ) { mq->num_of_potential_packed_wr_reqs = 0; mq->wr_packing_enabled = false; return; } else if (data_dir == WRITE) { mq->num_of_potential_packed_wr_reqs++; } if (mq->num_of_potential_packed_wr_reqs > mq->num_wr_reqs_to_start_packing) mq->wr_packing_enabled = true; } struct mmc_wr_pack_stats *mmc_blk_get_packed_statistics(struct mmc_card *card) { if (!card) return NULL; return &card->wr_pack_stats; } EXPORT_SYMBOL(mmc_blk_get_packed_statistics); void mmc_blk_init_packed_statistics(struct mmc_card *card) { int max_num_of_packed_reqs = 0; if (!card || !card->wr_pack_stats.packing_events) return; max_num_of_packed_reqs = card->ext_csd.max_packed_writes; spin_lock(&card->wr_pack_stats.lock); memset(card->wr_pack_stats.packing_events, 0, (max_num_of_packed_reqs + 1) * sizeof(*card->wr_pack_stats.packing_events)); memset(&card->wr_pack_stats.pack_stop_reason, 0, sizeof(card->wr_pack_stats.pack_stop_reason)); card->wr_pack_stats.enabled = true; spin_unlock(&card->wr_pack_stats.lock); } EXPORT_SYMBOL(mmc_blk_init_packed_statistics); void print_mmc_packing_stats(struct mmc_card *card) { int i; int max_num_of_packed_reqs = 0; if ((!card) || (!card->wr_pack_stats.packing_events)) return; max_num_of_packed_reqs = card->ext_csd.max_packed_writes; spin_lock(&card->wr_pack_stats.lock); pr_info("%s: write packing statistics:\n", mmc_hostname(card->host)); for (i = 1 ; i <= max_num_of_packed_reqs ; ++i) { if (card->wr_pack_stats.packing_events[i] != 0) pr_info("%s: Packed %d reqs - %d times\n", mmc_hostname(card->host), i, card->wr_pack_stats.packing_events[i]); } pr_info("%s: stopped packing due to the following reasons:\n", mmc_hostname(card->host)); if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS]) pr_info("%s: %d times: exceedmax num of segments\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EXCEEDS_SEGMENTS]); if (card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS]) pr_info("%s: %d times: exceeding the max num of sectors\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EXCEEDS_SECTORS]); if (card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR]) pr_info("%s: %d times: wrong data direction\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[WRONG_DATA_DIR]); if (card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD]) pr_info("%s: %d times: flush or discard\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[FLUSH_OR_DISCARD]); if (card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE]) pr_info("%s: %d times: empty queue\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[EMPTY_QUEUE]); if (card->wr_pack_stats.pack_stop_reason[REL_WRITE]) pr_info("%s: %d times: rel write\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[REL_WRITE]); if (card->wr_pack_stats.pack_stop_reason[THRESHOLD]) pr_info("%s: %d times: Threshold\n", mmc_hostname(card->host), card->wr_pack_stats.pack_stop_reason[THRESHOLD]); spin_unlock(&card->wr_pack_stats.lock); } EXPORT_SYMBOL(print_mmc_packing_stats); static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req) { struct request_queue *q = mq->queue; struct mmc_card *card = mq->card; struct request *cur = req, *next = NULL; struct mmc_blk_data *md = mq->data; bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN; unsigned int req_sectors = 0, phys_segments = 0; unsigned int max_blk_count, max_phys_segs; u8 put_back = 0; u8 max_packed_rw = 0; u8 reqs = 0; struct mmc_wr_pack_stats *stats = &card->wr_pack_stats; mmc_blk_clear_packed(mq->mqrq_cur); if (!(md->flags & MMC_BLK_CMD23) || !card->ext_csd.packed_event_en) goto no_packed; if (!mq->wr_packing_enabled) goto no_packed; if ((rq_data_dir(cur) == WRITE) && (card->host->caps2 & MMC_CAP2_PACKED_WR)) max_packed_rw = card->ext_csd.max_packed_writes; if (max_packed_rw == 0) goto no_packed; if (mmc_req_rel_wr(cur) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) goto no_packed; if (mmc_large_sec(card) && !IS_ALIGNED(blk_rq_sectors(cur), 8)) goto no_packed; max_blk_count = min(card->host->max_blk_count, card->host->max_req_size >> 9); if (unlikely(max_blk_count > 0xffff)) max_blk_count = 0xffff; max_phys_segs = queue_max_segments(q); req_sectors += blk_rq_sectors(cur); phys_segments += cur->nr_phys_segments; if (rq_data_dir(cur) == WRITE) { req_sectors++; phys_segments++; } spin_lock(&stats->lock); while (reqs < max_packed_rw - 1) { /* We should stop no-more packing its nopacked_period */ if ((card->host->caps2 & MMC_CAP2_ADAPT_PACKED) && time_is_after_jiffies(mq->nopacked_period)) break; spin_lock_irq(q->queue_lock); next = blk_fetch_request(q); spin_unlock_irq(q->queue_lock); if (!next) { MMC_BLK_UPDATE_STOP_REASON(stats, EMPTY_QUEUE); break; } if (mmc_large_sec(card) && !IS_ALIGNED(blk_rq_sectors(next), 8)) { MMC_BLK_UPDATE_STOP_REASON(stats, LARGE_SEC_ALIGN); put_back = 1; break; } if (next->cmd_flags & REQ_DISCARD || next->cmd_flags & REQ_FLUSH) { MMC_BLK_UPDATE_STOP_REASON(stats, FLUSH_OR_DISCARD); put_back = 1; break; } if (rq_data_dir(cur) != rq_data_dir(next)) { MMC_BLK_UPDATE_STOP_REASON(stats, WRONG_DATA_DIR); put_back = 1; break; } if (mmc_req_rel_wr(next) && (md->flags & MMC_BLK_REL_WR) && !en_rel_wr) { MMC_BLK_UPDATE_STOP_REASON(stats, REL_WRITE); put_back = 1; break; } req_sectors += blk_rq_sectors(next); if (req_sectors > max_blk_count) { if (stats->enabled) stats->pack_stop_reason[EXCEEDS_SECTORS]++; put_back = 1; break; } phys_segments += next->nr_phys_segments; if (phys_segments > max_phys_segs) { MMC_BLK_UPDATE_STOP_REASON(stats, EXCEEDS_SEGMENTS); put_back = 1; break; } if (rq_data_dir(next) == WRITE) { mq->num_of_potential_packed_wr_reqs++; if (card->ext_csd.bkops_en) card->bkops_info.sectors_changed += blk_rq_sectors(next); } list_add_tail(&next->queuelist, &mq->mqrq_cur->packed_list); cur = next; reqs++; } if (put_back) { spin_lock_irq(q->queue_lock); blk_requeue_request(q, next); spin_unlock_irq(q->queue_lock); } if (stats->enabled) { if (reqs + 1 <= card->ext_csd.max_packed_writes) stats->packing_events[reqs + 1]++; if (reqs + 1 == max_packed_rw) MMC_BLK_UPDATE_STOP_REASON(stats, THRESHOLD); } spin_unlock(&stats->lock); /* if (stats->enabled) { if (reqs + 1 <= card->ext_csd.max_packed_writes) stats->packing_events[reqs + 1]++; if (reqs + 1 == max_packed_rw) MMC_BLK_UPDATE_STOP_REASON(stats, THRESHOLD); } spin_unlock(&stats->lock); */ if (reqs > 0) { list_add(&req->queuelist, &mq->mqrq_cur->packed_list); mq->mqrq_cur->packed_num = ++reqs; mq->mqrq_cur->packed_retries = reqs; return reqs; } no_packed: mmc_blk_clear_packed(mq->mqrq_cur); return 0; } static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq, struct mmc_card *card, struct mmc_queue *mq) { struct mmc_blk_request *brq = &mqrq->brq; struct request *req = mqrq->req; struct request *prq; struct mmc_blk_data *md = mq->data; bool do_rel_wr, do_data_tag; u32 *packed_cmd_hdr = mqrq->packed_cmd_hdr; u8 i = 1; mqrq->packed_cmd = MMC_PACKED_WRITE; mqrq->packed_blocks = 0; mqrq->packed_fail_idx = MMC_PACKED_N_IDX; memset(packed_cmd_hdr, 0, sizeof(mqrq->packed_cmd_hdr)); packed_cmd_hdr[0] = (mqrq->packed_num << 16) | (PACKED_CMD_WR << 8) | PACKED_CMD_VER; /* * Argument for each entry of packed group */ list_for_each_entry(prq, &mqrq->packed_list, queuelist) { do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR); do_data_tag = (card->ext_csd.data_tag_unit_size) && (prq->cmd_flags & REQ_META) && (rq_data_dir(prq) == WRITE) && ((brq->data.blocks * brq->data.blksz) >= card->ext_csd.data_tag_unit_size); /* Argument of CMD23 */ packed_cmd_hdr[(i * 2)] = (do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) | (do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) | blk_rq_sectors(prq); /* Argument of CMD18 or CMD25 */ packed_cmd_hdr[((i * 2)) + 1] = mmc_card_blockaddr(card) ? blk_rq_pos(prq) : blk_rq_pos(prq) << 9; mqrq->packed_blocks += blk_rq_sectors(prq); i++; } memset(brq, 0, sizeof(struct mmc_blk_request)); brq->mrq.cmd = &brq->cmd; brq->mrq.data = &brq->data; brq->mrq.sbc = &brq->sbc; brq->mrq.stop = &brq->stop; brq->sbc.opcode = MMC_SET_BLOCK_COUNT; brq->sbc.arg = MMC_CMD23_ARG_PACKED | (mqrq->packed_blocks + 1); brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC; brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK; brq->cmd.arg = blk_rq_pos(req); if (!mmc_card_blockaddr(card)) brq->cmd.arg <<= 9; brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC; brq->data.blksz = 512; brq->data.blocks = mqrq->packed_blocks + 1; brq->data.flags |= MMC_DATA_WRITE; brq->data.fault_injected = false; brq->stop.opcode = MMC_STOP_TRANSMISSION; brq->stop.arg = 0; brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; mmc_set_data_timeout(&brq->data, card); brq->data.sg = mqrq->sg; brq->data.sg_len = mmc_queue_map_sg(mq, mqrq); mqrq->mmc_active.mrq = &brq->mrq; /* * This is intended for packed commands tests usage - in case these * functions are not in use the respective pointers are NULL */ if (mq->err_check_fn) mqrq->mmc_active.err_check = mq->err_check_fn; else mqrq->mmc_active.err_check = mmc_blk_packed_err_check; if (mq->packed_test_fn) mq->packed_test_fn(mq->queue, mqrq); mmc_queue_bounce_pre(mqrq); } static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card, struct mmc_blk_request *brq, struct request *req, int ret) { struct mmc_queue_req *mq_rq; mq_rq = container_of(brq, struct mmc_queue_req, brq); /* * If this is an SD card and we're writing, we can first * mark the known good sectors as ok. * * If the card is not SD, we can still ok written sectors * as reported by the controller (which might be less than * the real number of written sectors, but never more). */ if (mmc_card_sd(card)) { u32 blocks; if (!brq->data.fault_injected) { blocks = mmc_sd_num_wr_blocks(card); if (blocks != (u32)-1) ret = blk_end_request(req, 0, blocks << 9); } else ret = blk_end_request(req, 0, brq->data.bytes_xfered); } else { if (mq_rq->packed_cmd == MMC_PACKED_NONE) ret = blk_end_request(req, 0, brq->data.bytes_xfered); } return ret; } static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; int idx = mq_rq->packed_fail_idx, i = 0; int ret = 0; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.next); if (idx == i) { /* retry from error index */ mq_rq->packed_num -= idx; mq_rq->req = prq; ret = 1; if (mq_rq->packed_num == MMC_PACKED_N_SINGLE) { list_del_init(&prq->queuelist); mmc_blk_clear_packed(mq_rq); } return ret; } list_del_init(&prq->queuelist); blk_end_request(prq, 0, blk_rq_bytes(prq)); i++; } mmc_blk_clear_packed(mq_rq); return ret; } static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq) { struct request *prq; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.next); list_del_init(&prq->queuelist); blk_end_request(prq, -EIO, blk_rq_bytes(prq)); } mmc_blk_clear_packed(mq_rq); } static void mmc_blk_revert_packed_req(struct mmc_queue *mq, struct mmc_queue_req *mq_rq) { struct request *prq; struct request_queue *q = mq->queue; while (!list_empty(&mq_rq->packed_list)) { prq = list_entry_rq(mq_rq->packed_list.prev); if (prq->queuelist.prev != &mq_rq->packed_list) { list_del_init(&prq->queuelist); spin_lock_irq(q->queue_lock); blk_requeue_request(mq->queue, prq); spin_unlock_irq(q->queue_lock); } else { list_del_init(&prq->queuelist); } } mmc_blk_clear_packed(mq_rq); } static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc) { struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; struct mmc_blk_request *brq = &mq->mqrq_cur->brq; int ret = 1, disable_multi = 0, retry = 0, type; enum mmc_blk_status status; struct mmc_queue_req *mq_rq; struct request *req; struct mmc_async_req *areq; const u8 packed_num = 2; u8 reqs = 0; if (!rqc && !mq->mqrq_prev->req) return 0; if (rqc) { if ((card->ext_csd.bkops_en) && (rq_data_dir(rqc) == WRITE)) card->bkops_info.sectors_changed += blk_rq_sectors(rqc); reqs = mmc_blk_prep_packed_list(mq, rqc); } do { if (rqc) { if (reqs >= packed_num) mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur, card, mq); else mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); areq = &mq->mqrq_cur->mmc_active; } else areq = NULL; areq = mmc_start_req(card->host, areq, (int *) &status); if (!areq) { if (status == MMC_BLK_NEW_REQUEST) mq->flags |= MMC_QUEUE_NEW_REQUEST; return 0; } mq_rq = container_of(areq, struct mmc_queue_req, mmc_active); brq = &mq_rq->brq; req = mq_rq->req; type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE; mmc_queue_bounce_post(mq_rq); switch (status) { case MMC_BLK_SUCCESS: case MMC_BLK_PARTIAL: /* * A block was successfully transferred. */ mmc_blk_reset_success(md, type); if (mq_rq->packed_cmd != MMC_PACKED_NONE) { ret = mmc_blk_end_packed_req(mq_rq); break; } else { ret = blk_end_request(req, 0, brq->data.bytes_xfered); } /* * If the blk_end_request function returns non-zero even * though all data has been transferred and no errors * were returned by the host controller, it's a bug. */ if (status == MMC_BLK_SUCCESS && ret) { pr_err("%s BUG rq_tot %d d_xfer %d\n", __func__, blk_rq_bytes(req), brq->data.bytes_xfered); rqc = NULL; goto cmd_abort; } break; case MMC_BLK_CMD_ERR: ret = mmc_blk_cmd_err(md, card, brq, req, ret); if (!mmc_blk_reset(md, card->host, type)) break; goto cmd_abort; case MMC_BLK_RETRY: if (retry++ < 5) break; /* Fall through */ case MMC_BLK_ABORT: if (!mmc_blk_reset(md, card->host, type)) break; goto cmd_abort; case MMC_BLK_DATA_ERR: { int err; err = mmc_blk_reset(md, card->host, type); if (!err) break; if (err == -ENODEV || mq_rq->packed_cmd != MMC_PACKED_NONE) goto cmd_abort; /* Fall through */ } case MMC_BLK_ECC_ERR: if (brq->data.blocks > 1) { /* Redo read one sector at a time */ pr_warning("%s: retrying using single block read\n", req->rq_disk->disk_name); disable_multi = 1; break; } /* * After an error, we redo I/O one sector at a * time, so we only reach here after trying to * read a single sector. */ ret = blk_end_request(req, -EIO, brq->data.blksz); if (!ret) goto start_new_req; break; case MMC_BLK_NOMEDIUM: goto cmd_abort; default: pr_err("%s: Unhandled return value (%d)", req->rq_disk->disk_name, status); goto cmd_abort; } if (ret) { if (mq_rq->packed_cmd == MMC_PACKED_NONE) { /* * In case of a incomplete request * prepare it again and resend. */ mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } else { if (!mq_rq->packed_retries) goto cmd_abort; mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq); mmc_start_req(card->host, &mq_rq->mmc_active, NULL); } } } while (ret); return 1; cmd_abort: if (mq_rq->packed_cmd == MMC_PACKED_NONE) { if (mmc_card_removed(card)) req->cmd_flags |= REQ_QUIET; while (ret) ret = blk_end_request(req, -EIO, blk_rq_cur_bytes(req)); } else { mmc_blk_abort_packed_req(mq_rq); } start_new_req: if (rqc) { /* * If current request is packed, it needs to put back. */ if (mq->mqrq_cur->packed_cmd != MMC_PACKED_NONE) mmc_blk_revert_packed_req(mq, mq->mqrq_cur); mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq); mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL); } return 0; } static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req) { int ret; struct mmc_blk_data *md = mq->data; struct mmc_card *card = md->queue.card; struct mmc_host *host = card->host; unsigned long flags; #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME if (mmc_bus_needs_resume(card->host)) { mmc_resume_bus(card->host); mmc_blk_set_blksize(md, card); } #endif if (req && !mq->mqrq_prev->req) { /* claim host only for the first request */ mmc_claim_host(card->host); if (card->ext_csd.bkops_en) mmc_stop_bkops(card); } ret = mmc_blk_part_switch(card, md); if (ret) { if (req) { blk_end_request_all(req, -EIO); } ret = 0; goto out; } mmc_blk_write_packing_control(mq, req); mq->flags &= ~MMC_QUEUE_NEW_REQUEST; if (req && req->cmd_flags & REQ_SANITIZE) { /* complete ongoing async transfer before issuing sanitize */ if (card->host && card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); ret = mmc_blk_issue_sanitize_rq(mq, req); } else if (req && req->cmd_flags & REQ_DISCARD) { /* complete ongoing async transfer before issuing discard */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); if (req->cmd_flags & REQ_SECURE && !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN)) ret = mmc_blk_issue_secdiscard_rq(mq, req); else ret = mmc_blk_issue_discard_rq(mq, req); } else if (req && req->cmd_flags & REQ_FLUSH) { /* complete ongoing async transfer before issuing flush */ if (card->host->areq) mmc_blk_issue_rw_rq(mq, NULL); ret = mmc_blk_issue_flush(mq, req); } else { if (!req && host->areq) { spin_lock_irqsave(&host->context_info.lock, flags); host->context_info.is_waiting_last_req = true; spin_unlock_irqrestore(&host->context_info.lock, flags); } ret = mmc_blk_issue_rw_rq(mq, req); } out: if (!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) /* release host only when there are no more requests */ mmc_release_host(card->host); return ret; } static inline int mmc_blk_readonly(struct mmc_card *card) { return mmc_card_readonly(card) || !(card->csd.cmdclass & CCC_BLOCK_WRITE); } static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card, struct device *parent, sector_t size, bool default_ro, const char *subname, int area_type) { struct mmc_blk_data *md; int devidx, ret; unsigned int percentage = BKOPS_SIZE_PERCENTAGE_TO_QUEUE_DELAYED_WORK; devidx = find_first_zero_bit(dev_use, max_devices); if (devidx >= max_devices) return ERR_PTR(-ENOSPC); __set_bit(devidx, dev_use); md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL); if (!md) { ret = -ENOMEM; goto out; } /* * !subname implies we are creating main mmc_blk_data that will be * associated with mmc_card with mmc_set_drvdata. Due to device * partitions, devidx will not coincide with a per-physical card * index anymore so we keep track of a name index. */ if (!subname) { md->name_idx = find_first_zero_bit(name_use, max_devices); __set_bit(md->name_idx, name_use); } else md->name_idx = ((struct mmc_blk_data *) dev_to_disk(parent)->private_data)->name_idx; md->area_type = area_type; /* * Set the read-only status based on the supported commands * and the write protect switch. */ md->read_only = mmc_blk_readonly(card); md->disk = alloc_disk(perdev_minors); if (md->disk == NULL) { ret = -ENOMEM; goto err_kfree; } spin_lock_init(&md->lock); INIT_LIST_HEAD(&md->part); md->usage = 1; ret = mmc_init_queue(&md->queue, card, &md->lock, subname); if (ret) goto err_putdisk; md->queue.issue_fn = mmc_blk_issue_rq; md->queue.data = md; md->disk->major = MMC_BLOCK_MAJOR; md->disk->first_minor = devidx * perdev_minors; md->disk->fops = &mmc_bdops; md->disk->private_data = md; md->disk->queue = md->queue.queue; md->disk->driverfs_dev = parent; set_disk_ro(md->disk, md->read_only || default_ro); md->disk->flags = GENHD_FL_EXT_DEVT; /* * As discussed on lkml, GENHD_FL_REMOVABLE should: * * - be set for removable media with permanent block devices * - be unset for removable block devices with permanent media * * Since MMC block devices clearly fall under the second * case, we do not set GENHD_FL_REMOVABLE. Userspace * should use the block device creation/destruction hotplug * messages to tell when the card is present. */ snprintf(md->disk->disk_name, sizeof(md->disk->disk_name), "mmcblk%d%s", md->name_idx, subname ? subname : ""); blk_queue_logical_block_size(md->queue.queue, 512); set_capacity(md->disk, size); card->bkops_info.size_percentage_to_queue_delayed_work = percentage; card->bkops_info.min_sectors_to_queue_delayed_work = ((unsigned int)size * percentage) / 100; if (mmc_host_cmd23(card->host)) { if (mmc_card_mmc(card) || (mmc_card_sd(card) && card->scr.cmds & SD_SCR_CMD23_SUPPORT && mmc_sd_card_uhs(card))) md->flags |= MMC_BLK_CMD23; } if (mmc_card_mmc(card) && md->flags & MMC_BLK_CMD23 && ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) || card->ext_csd.rel_sectors)) { md->flags |= MMC_BLK_REL_WR; blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA); } return md; err_putdisk: put_disk(md->disk); err_kfree: kfree(md); out: return ERR_PTR(ret); } static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card) { sector_t size; struct mmc_blk_data *md; if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) { /* * The EXT_CSD sector count is in number or 512 byte * sectors. */ size = card->ext_csd.sectors; } else { /* * The CSD capacity field is in units of read_blkbits. * set_capacity takes units of 512 bytes. */ size = card->csd.capacity << (card->csd.read_blkbits - 9); } md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL, MMC_BLK_DATA_AREA_MAIN); return md; } static int mmc_blk_alloc_part(struct mmc_card *card, struct mmc_blk_data *md, unsigned int part_type, sector_t size, bool default_ro, const char *subname, int area_type) { char cap_str[10]; struct mmc_blk_data *part_md; part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro, subname, area_type); if (IS_ERR(part_md)) return PTR_ERR(part_md); part_md->part_type = part_type; list_add(&part_md->part, &md->part); string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s partition %u %s\n", part_md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), part_md->part_type, cap_str); return 0; } /* MMC Physical partitions consist of two boot partitions and * up to four general purpose partitions. * For each partition enabled in EXT_CSD a block device will be allocatedi * to provide access to the partition. */ static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md) { int idx, ret = 0; if (!mmc_card_mmc(card)) return 0; for (idx = 0; idx < card->nr_parts; idx++) { if (card->part[idx].size) { ret = mmc_blk_alloc_part(card, md, card->part[idx].part_cfg, card->part[idx].size >> 9, card->part[idx].force_ro, card->part[idx].name, card->part[idx].area_type); if (ret) return ret; } } return ret; } static void mmc_blk_remove_req(struct mmc_blk_data *md) { struct mmc_card *card; if (md) { card = md->queue.card; device_remove_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); if (md->disk->flags & GENHD_FL_UP) { device_remove_file(disk_to_dev(md->disk), &md->force_ro); if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock); /* Stop new requests from getting into the queue */ del_gendisk(md->disk); } /* Then flush out any already in there */ mmc_cleanup_queue(&md->queue); mmc_blk_put(md); } } static void mmc_blk_remove_parts(struct mmc_card *card, struct mmc_blk_data *md) { struct list_head *pos, *q; struct mmc_blk_data *part_md; __clear_bit(md->name_idx, name_use); list_for_each_safe(pos, q, &md->part) { part_md = list_entry(pos, struct mmc_blk_data, part); list_del(pos); mmc_blk_remove_req(part_md); } } static int mmc_add_disk(struct mmc_blk_data *md) { int ret; struct mmc_card *card = md->queue.card; add_disk(md->disk); md->force_ro.show = force_ro_show; md->force_ro.store = force_ro_store; sysfs_attr_init(&md->force_ro.attr); md->force_ro.attr.name = "force_ro"; md->force_ro.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->force_ro); if (ret) goto force_ro_fail; if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) && card->ext_csd.boot_ro_lockable) { umode_t mode; if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS) mode = S_IRUGO; else mode = S_IRUGO | S_IWUSR; md->power_ro_lock.show = power_ro_lock_show; md->power_ro_lock.store = power_ro_lock_store; sysfs_attr_init(&md->power_ro_lock.attr); md->power_ro_lock.attr.mode = mode; md->power_ro_lock.attr.name = "ro_lock_until_next_power_on"; ret = device_create_file(disk_to_dev(md->disk), &md->power_ro_lock); if (ret) goto power_ro_lock_fail; } md->num_wr_reqs_to_start_packing.show = num_wr_reqs_to_start_packing_show; md->num_wr_reqs_to_start_packing.store = num_wr_reqs_to_start_packing_store; sysfs_attr_init(&md->num_wr_reqs_to_start_packing.attr); md->num_wr_reqs_to_start_packing.attr.name = "num_wr_reqs_to_start_packing"; md->num_wr_reqs_to_start_packing.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); if (ret) goto num_wr_reqs_to_start_packing_fail; md->bkops_check_threshold.show = bkops_check_threshold_show; md->bkops_check_threshold.store = bkops_check_threshold_store; sysfs_attr_init(&md->bkops_check_threshold.attr); md->bkops_check_threshold.attr.name = "bkops_check_threshold"; md->bkops_check_threshold.attr.mode = S_IRUGO | S_IWUSR; ret = device_create_file(disk_to_dev(md->disk), &md->bkops_check_threshold); if (ret) goto bkops_check_threshold_fails; return ret; bkops_check_threshold_fails: device_remove_file(disk_to_dev(md->disk), &md->num_wr_reqs_to_start_packing); num_wr_reqs_to_start_packing_fail: device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock); power_ro_lock_fail: device_remove_file(disk_to_dev(md->disk), &md->force_ro); force_ro_fail: del_gendisk(md->disk); return ret; } #define CID_MANFID_SANDISK 0x2 #define CID_MANFID_TOSHIBA 0x11 #define CID_MANFID_MICRON 0x13 #define CID_MANFID_SAMSUNG 0x15 static const struct mmc_fixup blk_fixups[] = { MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38), /* * Some MMC cards experience performance degradation with CMD23 * instead of CMD12-bounded multiblock transfers. For now we'll * black list what's bad... * - Certain Toshiba cards. * * N.B. This doesn't affect SD cards. */ MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_BLK_NO_CMD23), /* * Some Micron MMC cards needs longer data read timeout than * indicated in CSD. */ MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc, MMC_QUIRK_LONG_READ_TIME), /* Some INAND MCP devices advertise incorrect timeout values */ MMC_FIXUP("SEM04G", 0x45, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_INAND_DATA_TIMEOUT), /* * On these Samsung MoviNAND parts, performing secure erase or * secure trim can result in unrecoverable corruption due to a * firmware bug. */ MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc, MMC_QUIRK_SEC_ERASE_TRIM_BROKEN), END_FIXUP }; #ifdef CONFIG_MMC_SUPPORT_BKOPS_MODE static ssize_t bkops_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct gendisk *disk; struct mmc_blk_data *md; struct mmc_card *card; disk = dev_to_disk(dev); if (disk) md = disk->private_data; else goto show_out; if (md) card = md->queue.card; else goto show_out; return snprintf(buf, PAGE_SIZE, "%u\n", card->bkops_enable); show_out: return snprintf(buf, PAGE_SIZE, "\n"); } static ssize_t bkops_mode_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct gendisk *disk; struct mmc_blk_data *md; struct mmc_card *card; u8 value; int err = 0; disk = dev_to_disk(dev); if (disk) md = disk->private_data; else goto store_out; if (md) card = md->queue.card; else goto store_out; if (kstrtou8(buf, 0, &value)) goto store_out; err = mmc_bkops_enable(card->host, value); if (err) return err; return count; store_out: return -EINVAL; } static inline void mmc_blk_bkops_sysfs_init(struct mmc_card *card) { struct mmc_blk_data *md = mmc_get_drvdata(card); card->bkops_attr.show = bkops_mode_show; card->bkops_attr.store = bkops_mode_store; sysfs_attr_init(&card->bkops_attr.attr); card->bkops_attr.attr.name = "bkops_en"; card->bkops_attr.attr.mode = S_IRUGO | S_IWUSR | S_IWGRP; if (device_create_file((disk_to_dev(md->disk)), &card->bkops_attr)) { pr_err("%s: Failed to create bkops_en sysfs entry\n", mmc_hostname(card->host)); #if defined(CONFIG_MMC_BKOPS_NODE_UID) || defined(CONFIG_MMC_BKOPS_NODE_GID) } else { int rc; struct device * dev; dev = disk_to_dev(md->disk); rc = sysfs_chown_file(&dev->kobj, &card->bkops_attr.attr, CONFIG_MMC_BKOPS_NODE_UID, CONFIG_MMC_BKOPS_NODE_GID); if (rc) pr_err("%s: Failed to change mode of sysfs entry\n", mmc_hostname(card->host)); #endif } } #else static inline void mmc_blk_bkops_sysfs_init(struct mmc_card *card) { } #endif static int mmc_blk_probe(struct mmc_card *card) { struct mmc_blk_data *md, *part_md; char cap_str[10]; /* * Check that the card supports the command class(es) we need. */ if (!(card->csd.cmdclass & CCC_BLOCK_READ)) return -ENODEV; md = mmc_blk_alloc(card); if (IS_ERR(md)) return PTR_ERR(md); string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2, cap_str, sizeof(cap_str)); pr_info("%s: %s %s %s %s\n", md->disk->disk_name, mmc_card_id(card), mmc_card_name(card), cap_str, md->read_only ? "(ro)" : ""); if (mmc_blk_alloc_parts(card, md)) goto out; mmc_set_drvdata(card, md); mmc_fixup_device(card, blk_fixups); #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME mmc_set_bus_resume_policy(card->host, 1); #endif if (mmc_add_disk(md)) goto out; list_for_each_entry(part_md, &md->part, part) { if (mmc_add_disk(part_md)) goto out; } /* init sysfs for bkops mode */ if (card && mmc_card_mmc(card)) { mmc_blk_bkops_sysfs_init(card); spin_lock_init(&card->bkops_lock); } return 0; out: mmc_blk_remove_parts(card, md); mmc_blk_remove_req(md); return 0; } static void mmc_blk_remove(struct mmc_card *card) { struct mmc_blk_data *md = mmc_get_drvdata(card); mmc_blk_remove_parts(card, md); mmc_claim_host(card->host); mmc_blk_part_switch(card, md); mmc_release_host(card->host); mmc_blk_remove_req(md); mmc_set_drvdata(card, NULL); #ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME mmc_set_bus_resume_policy(card->host, 0); #endif } #ifdef CONFIG_PM static int mmc_blk_suspend(struct mmc_card *card) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = mmc_get_drvdata(card); int rc = 0; if (md) { rc = mmc_queue_suspend(&md->queue); if (rc) goto out; list_for_each_entry(part_md, &md->part, part) { rc = mmc_queue_suspend(&part_md->queue); if (rc) goto out_resume; } } goto out; out_resume: mmc_queue_resume(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_resume(&part_md->queue); } out: return rc; } static int mmc_blk_resume(struct mmc_card *card) { struct mmc_blk_data *part_md; struct mmc_blk_data *md = mmc_get_drvdata(card); if (md) { /* * Resume involves the card going into idle state, * so current partition is always the main one. */ md->part_curr = md->part_type; mmc_queue_resume(&md->queue); list_for_each_entry(part_md, &md->part, part) { mmc_queue_resume(&part_md->queue); } } return 0; } #else #define mmc_blk_suspend NULL #define mmc_blk_resume NULL #endif static struct mmc_driver mmc_driver = { .drv = { .name = "mmcblk", }, .probe = mmc_blk_probe, .remove = mmc_blk_remove, .suspend = mmc_blk_suspend, .resume = mmc_blk_resume, }; static int __init mmc_blk_init(void) { int res; if (perdev_minors != CONFIG_MMC_BLOCK_MINORS) pr_info("mmcblk: using %d minors per device\n", perdev_minors); max_devices = 256 / perdev_minors; res = register_blkdev(MMC_BLOCK_MAJOR, "mmc"); if (res) goto out; res = mmc_register_driver(&mmc_driver); if (res) goto out2; return 0; out2: unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); out: return res; } static void __exit mmc_blk_exit(void) { mmc_unregister_driver(&mmc_driver); unregister_blkdev(MMC_BLOCK_MAJOR, "mmc"); } module_init(mmc_blk_init); module_exit(mmc_blk_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
iJo09/Hybridmax_Kernel_I9505_Lollipop-1
drivers/mmc/card/block.c
C
gpl-2.0
76,834
--- layout: post title: Air America Radio author: Chris Metcalf date: 2004/03/31 slug: air-america-radio category: tags: [ politics ] --- Apparently <a href="http://www.airamericaradio.com/">Air America Radio</a> launched today. Somehow the idea of listening to Al Franken and Janeane Garofalo all day long doesn't really turn me on. Somehow his days on Comedy Central don't really let me see him as a powerful political figure. If you've got to make Liberalism funny to get people to listen to it, you've got more things to worry about.
chrismetcalf/chrismetcalf.net
_posts/2004-03-31-air-america-radio.md
Markdown
gpl-2.0
541
using System; using Server.Mobiles; using Server.Network; using Server.Targeting; namespace Server.Spells.First { public class HealSpell : MagerySpell { private static readonly SpellInfo m_Info = new SpellInfo( "Heal", "In Mani", 224, 9061, Reagent.Garlic, Reagent.Ginseng, Reagent.SpidersSilk); public HealSpell(Mobile caster, Item scroll) : base(caster, scroll, m_Info) { } public override SpellCircle Circle { get { return SpellCircle.First; } } public override bool CheckCast() { if (Engines.ConPVP.DuelContext.CheckSuddenDeath(this.Caster)) { this.Caster.SendMessage(0x22, "You cannot cast this spell when in sudden death."); return false; } return base.CheckCast(); } public override void OnCast() { this.Caster.Target = new InternalTarget(this); } public void Target(Mobile m) { if (!this.Caster.CanSee(m)) { this.Caster.SendLocalizedMessage(500237); // Target can not be seen. } else if (m.IsDeadBondedPet) { this.Caster.SendLocalizedMessage(1060177); // You cannot heal a creature that is already dead! } else if (m is BaseCreature && ((BaseCreature)m).IsAnimatedDead) { this.Caster.SendLocalizedMessage(1061654); // You cannot heal that which is not alive. } else if (m is IRepairableMobile) { this.Caster.LocalOverheadMessage(MessageType.Regular, 0x3B2, 500951); // You cannot heal that. } else if (m.Poisoned || Server.Items.MortalStrike.IsWounded(m)) { this.Caster.LocalOverheadMessage(MessageType.Regular, 0x22, (this.Caster == m) ? 1005000 : 1010398); } else if (this.CheckBSequence(m)) { SpellHelper.Turn(this.Caster, m); int toHeal; if (Core.AOS) { toHeal = this.Caster.Skills.Magery.Fixed / 120; toHeal += Utility.RandomMinMax(1, 4); if (Core.SE && this.Caster != m) toHeal = (int)(toHeal * 1.5); } else { toHeal = (int)(this.Caster.Skills[SkillName.Magery].Value * 0.1); toHeal += Utility.Random(1, 5); } //m.Heal( toHeal, Caster ); SpellHelper.Heal(toHeal, m, this.Caster); m.FixedParticles(0x376A, 9, 32, 5005, EffectLayer.Waist); m.PlaySound(0x1F2); } this.FinishSequence(); } public class InternalTarget : Target { private readonly HealSpell m_Owner; public InternalTarget(HealSpell owner) : base(Core.ML ? 10 : 12, false, TargetFlags.Beneficial) { this.m_Owner = owner; } protected override void OnTarget(Mobile from, object o) { if (o is Mobile) { this.m_Owner.Target((Mobile)o); } } protected override void OnTargetFinish(Mobile from) { this.m_Owner.FinishSequence(); } } } }
SirGrizzlyBear/ServUOGrizzly
Scripts/Spells/First/Heal.cs
C#
gpl-2.0
3,667
--- id: 9987 title: 慈悲为怀 date: 2009-02-17T17:48:00+00:00 author: jiang layout: post guid: http://li-and-jiang.com/blog/2009/02/17/%e6%85%88%e6%82%b2%e4%b8%ba%e6%80%80/ permalink: /2009/02/17/%e6%85%88%e6%82%b2%e4%b8%ba%e6%80%80/ categories: - 生活 --- [<img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px" height="64" alt="rak" src="http://byfiles.storage.msn.com/y1pm4z_6pUecHisRHPg-yJh52XeNtAgI9HX0UQel9yoLSRcrBahPtjY_rS82pNW0kjspkViQYxJlm8hAMazX1hfUg?PARTNER=WRITER" width="244" border="0" />](http://byfiles.storage.msn.com/y1pzm9_q0nFiMzzhHghqPN41-ynTy536wx5LR1DnO1VfkK8trCNNCeS66ebZDtnp9Xr?PARTNER=WRITER) 早上七点半,海淀万柳,起来就见外头地面铺成了一层雪,出门时雪还比较大。待九点,到宣武门,就墙角见一些积雪,天空若无其事地阴着,地面也若无其事地跟昨天一样。噫,南北之大防,其斯之谓与? 下班时习惯地看看公司主页的Quote of the Day,乖乖,今天是洋人们的Random Acts of Kindness Day。<a href="http://en.wikipedia.org/wiki/Random_act_of_kindness " target="_blank">Random Acts of Kindness</a>,就是随意地做些好事,比如替人带份盒饭,多给些小费,再买一份中关村大街小摊的烤红薯之类。有时人们把它翻成“慈悲为怀”,似乎太严肃了。著名的政治家密斯脱Alibaba Gamma说: > If you want others to be happy, practice compassion. If you want to be happy, practice compassion. 有人翻译得好: > 欲令众生离苦得乐,当修大悲心;欲令自我离苦得乐,当修大悲心。 说,宗教这东西,如果不够幽默大度,很容易陷入贾恩市义之类功利主义的泥沼。
Jiangtang/writing
cn_bk_rbind/content/post/2009-02-17-慈悲为怀.md
Markdown
gpl-2.0
1,735
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: BasePublisherService.php 79311 2011-11-03 21:18:14Z chris.nutting $ */ /** * @package OpenX * @author Andriy Petlyovanyy <[email protected]> * */ // Require Publisher Service Implementation require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php'; /** * Base Publisher Service * */ class BasePublisherService { /** * Reference to Publisher Service implementation. * * @var PublisherServiceImpl $_oPublisherServiceImp */ var $_oPublisherServiceImp; /** * This method initialises Service implementation object field. * */ function BasePublisherService() { $this->_oPublisherServiceImp = new PublisherServiceImpl(); } } ?>
kriwil/OpenX
www/api/v2/common/BasePublisherService.php
PHP
gpl-2.0
2,377
/* * This file is part of the coreboot project. * * Copyright (C) 2007-2009 coresystems GmbH * Copyright (C) 2013 Google Inc. * Copyright (C) 2015 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <arch/acpi.h> #include <console/console.h> #include <device/device.h> #include <gpio.h> #include <stdlib.h> #include <string.h> #include <soc/nhlt.h> #include "ec.h" #include "gpio.h" static const char *oem_id_maxim = "INTEL"; static const char *oem_table_id_maxim = "SCRDMAX"; static void mainboard_init(device_t dev) { mainboard_ec_init(); } static uint8_t select_audio_codec(void) { int audio_db_sel = gpio_get(AUDIO_DB_ID); return audio_db_sel; } static unsigned long mainboard_write_acpi_tables( device_t device, unsigned long current, acpi_rsdp_t *rsdp) { uintptr_t start_addr; uintptr_t end_addr; struct nhlt *nhlt; const char *oem_id = NULL; const char *oem_table_id = NULL; start_addr = current; nhlt = nhlt_init(); if (nhlt == NULL) return start_addr; /* 2 Channel DMIC array. */ if (nhlt_soc_add_dmic_array(nhlt, 2)) printk(BIOS_ERR, "Couldn't add 2CH DMIC array.\n"); /* 4 Channel DMIC array. */ if (nhlt_soc_add_dmic_array(nhlt, 4)) printk(BIOS_ERR, "Couldn't add 4CH DMIC arrays.\n"); if (select_audio_codec()) { /* ADI Smart Amps for left and right. */ if (nhlt_soc_add_ssm4567(nhlt, AUDIO_LINK_SSP0)) printk(BIOS_ERR, "Couldn't add ssm4567.\n"); } else { /* MAXIM Smart Amps for left and right. */ if (nhlt_soc_add_max98357(nhlt, AUDIO_LINK_SSP0)) printk(BIOS_ERR, "Couldn't add max98357.\n"); oem_id = oem_id_maxim; oem_table_id = oem_table_id_maxim; } /* NAU88l25 Headset codec. */ if (nhlt_soc_add_nau88l25(nhlt, AUDIO_LINK_SSP1)) printk(BIOS_ERR, "Couldn't add headset codec.\n"); end_addr = nhlt_soc_serialize_oem_overrides(nhlt, start_addr, oem_id, oem_table_id); if (end_addr != start_addr) acpi_add_table(rsdp, (void *)start_addr); return end_addr; } /* * mainboard_enable is executed as first thing after * enumerate_buses(). */ static void mainboard_enable(device_t dev) { dev->ops->init = mainboard_init; dev->ops->write_acpi_tables = mainboard_write_acpi_tables; } struct chip_operations mainboard_ops = { .enable_dev = mainboard_enable, };
latelee/coreboot
src/mainboard/intel/kunimitsu/mainboard.c
C
gpl-2.0
2,726
/* * Driver O/S-independent utility routines * * Copyright (C) 1999-2010, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * $Id: bcmutils.c,v 1.210.4.5.2.4.6.19 2010/04/26 06:05:25 Exp $ */ #include <typedefs.h> #include <bcmdefs.h> #include <stdarg.h> #include <bcmutils.h> #ifdef BCMDRIVER #include <osl.h> #include <siutils.h> #else #include <stdio.h> #include <string.h> /* This case for external supplicant use */ #if defined(BCMEXTSUP) #include <bcm_osl.h> #endif #endif /* BCMDRIVER */ #include <bcmendian.h> #include <bcmdevs.h> #include <proto/ethernet.h> #include <proto/vlan.h> #include <proto/bcmip.h> #include <proto/802.1d.h> #include <proto/802.11.h> #ifdef BCMDRIVER /* copy a pkt buffer chain into a buffer */ uint pktcopy(osl_t *osh, void *p, uint offset, int len, uchar *buf) { uint n, ret = 0; if (len < 0) len = 4096; /* "infinite" */ /* skip 'offset' bytes */ for (; p && offset; p = PKTNEXT(osh, p)) { if (offset < (uint)PKTLEN(osh, p)) break; offset -= PKTLEN(osh, p); } if (!p) return 0; /* copy the data */ for (; p && len; p = PKTNEXT(osh, p)) { n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len); bcopy(PKTDATA(osh, p) + offset, buf, n); buf += n; len -= n; ret += n; offset = 0; } return ret; } /* copy a buffer into a pkt buffer chain */ uint pktfrombuf(osl_t *osh, void *p, uint offset, int len, uchar *buf) { uint n, ret = 0; /* skip 'offset' bytes */ for (; p && offset; p = PKTNEXT(osh, p)) { if (offset < (uint)PKTLEN(osh, p)) break; offset -= PKTLEN(osh, p); } if (!p) return 0; /* copy the data */ for (; p && len; p = PKTNEXT(osh, p)) { n = MIN((uint)PKTLEN(osh, p) - offset, (uint)len); bcopy(buf, PKTDATA(osh, p) + offset, n); buf += n; len -= n; ret += n; offset = 0; } return ret; } /* return total length of buffer chain */ uint pkttotlen(osl_t *osh, void *p) { uint total; total = 0; for (; p; p = PKTNEXT(osh, p)) total += PKTLEN(osh, p); return (total); } /* return the last buffer of chained pkt */ void * pktlast(osl_t *osh, void *p) { for (; PKTNEXT(osh, p); p = PKTNEXT(osh, p)) ; return (p); } /* count segments of a chained packet */ uint pktsegcnt(osl_t *osh, void *p) { uint cnt; for (cnt = 0; p; p = PKTNEXT(osh, p)) cnt++; return cnt; } /* * osl multiple-precedence packet queue * hi_prec is always >= the number of the highest non-empty precedence */ void * pktq_penq(struct pktq *pq, int prec, void *p) { struct pktq_prec *q; ASSERT(prec >= 0 && prec < pq->num_prec); ASSERT(PKTLINK(p) == NULL); /* queueing chains not allowed */ ASSERT(!pktq_full(pq)); ASSERT(!pktq_pfull(pq, prec)); q = &pq->q[prec]; if (q->head) PKTSETLINK(q->tail, p); else q->head = p; q->tail = p; q->len++; pq->len++; if (pq->hi_prec < prec) pq->hi_prec = (uint8)prec; return p; } void * pktq_penq_head(struct pktq *pq, int prec, void *p) { struct pktq_prec *q; ASSERT(prec >= 0 && prec < pq->num_prec); ASSERT(PKTLINK(p) == NULL); /* queueing chains not allowed */ ASSERT(!pktq_full(pq)); ASSERT(!pktq_pfull(pq, prec)); q = &pq->q[prec]; if (q->head == NULL) q->tail = p; PKTSETLINK(p, q->head); q->head = p; q->len++; pq->len++; if (pq->hi_prec < prec) pq->hi_prec = (uint8)prec; return p; } void * pktq_pdeq(struct pktq *pq, int prec) { struct pktq_prec *q; void *p; ASSERT(prec >= 0 && prec < pq->num_prec); q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; pq->len--; PKTSETLINK(p, NULL); return p; } void * pktq_pdeq_tail(struct pktq *pq, int prec) { struct pktq_prec *q; void *p, *prev; ASSERT(prec >= 0 && prec < pq->num_prec); q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; for (prev = NULL; p != q->tail; p = PKTLINK(p)) prev = p; if (prev) PKTSETLINK(prev, NULL); else q->head = NULL; q->tail = prev; q->len--; pq->len--; return p; } void pktq_pflush(osl_t *osh, struct pktq *pq, int prec, bool dir) { struct pktq_prec *q; void *p; q = &pq->q[prec]; p = q->head; while (p) { q->head = PKTLINK(p); PKTSETLINK(p, NULL); PKTFREE(osh, p, dir); q->len--; pq->len--; p = q->head; } ASSERT(q->len == 0); q->tail = NULL; } bool pktq_pdel(struct pktq *pq, void *pktbuf, int prec) { struct pktq_prec *q; void *p; ASSERT(prec >= 0 && prec < pq->num_prec); if (!pktbuf) return FALSE; q = &pq->q[prec]; if (q->head == pktbuf) { if ((q->head = PKTLINK(pktbuf)) == NULL) q->tail = NULL; } else { for (p = q->head; p && PKTLINK(p) != pktbuf; p = PKTLINK(p)) ; if (p == NULL) return FALSE; PKTSETLINK(p, PKTLINK(pktbuf)); if (q->tail == pktbuf) q->tail = p; } q->len--; pq->len--; PKTSETLINK(pktbuf, NULL); return TRUE; } void pktq_init(struct pktq *pq, int num_prec, int max_len) { int prec; ASSERT(num_prec > 0 && num_prec <= PKTQ_MAX_PREC); /* pq is variable size; only zero out what's requested */ bzero(pq, OFFSETOF(struct pktq, q) + (sizeof(struct pktq_prec) * num_prec)); pq->num_prec = (uint16)num_prec; pq->max = (uint16)max_len; for (prec = 0; prec < num_prec; prec++) pq->q[prec].max = pq->max; } void * pktq_deq(struct pktq *pq, int *prec_out) { struct pktq_prec *q; void *p; int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; pq->len--; if (prec_out) *prec_out = prec; PKTSETLINK(p, NULL); return p; } void * pktq_deq_tail(struct pktq *pq, int *prec_out) { struct pktq_prec *q; void *p, *prev; int prec; if (pq->len == 0) return NULL; for (prec = 0; prec < pq->hi_prec; prec++) if (pq->q[prec].head) break; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; for (prev = NULL; p != q->tail; p = PKTLINK(p)) prev = p; if (prev) PKTSETLINK(prev, NULL); else q->head = NULL; q->tail = prev; q->len--; pq->len--; if (prec_out) *prec_out = prec; PKTSETLINK(p, NULL); return p; } void * pktq_peek(struct pktq *pq, int *prec_out) { int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; if (prec_out) *prec_out = prec; return (pq->q[prec].head); } void * pktq_peek_tail(struct pktq *pq, int *prec_out) { int prec; if (pq->len == 0) return NULL; for (prec = 0; prec < pq->hi_prec; prec++) if (pq->q[prec].head) break; if (prec_out) *prec_out = prec; return (pq->q[prec].tail); } void pktq_flush(osl_t *osh, struct pktq *pq, bool dir) { int prec; for (prec = 0; prec < pq->num_prec; prec++) pktq_pflush(osh, pq, prec, dir); ASSERT(pq->len == 0); } /* Return sum of lengths of a specific set of precedences */ int pktq_mlen(struct pktq *pq, uint prec_bmp) { int prec, len; len = 0; for (prec = 0; prec <= pq->hi_prec; prec++) if (prec_bmp & (1 << prec)) len += pq->q[prec].len; return len; } /* Priority dequeue from a specific set of precedences */ void * pktq_mdeq(struct pktq *pq, uint prec_bmp, int *prec_out) { struct pktq_prec *q; void *p; int prec; if (pq->len == 0) return NULL; while ((prec = pq->hi_prec) > 0 && pq->q[prec].head == NULL) pq->hi_prec--; while ((prec_bmp & (1 << prec)) == 0 || pq->q[prec].head == NULL) if (prec-- == 0) return NULL; q = &pq->q[prec]; if ((p = q->head) == NULL) return NULL; if ((q->head = PKTLINK(p)) == NULL) q->tail = NULL; q->len--; if (prec_out) *prec_out = prec; pq->len--; PKTSETLINK(p, NULL); return p; } #endif /* BCMDRIVER */ const unsigned char bcm_ctype[] = { _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 0-7 */ _BCM_C, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C|_BCM_S, _BCM_C, _BCM_C, /* 8-15 */ _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 16-23 */ _BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C,_BCM_C, /* 24-31 */ _BCM_S|_BCM_SP,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 32-39 */ _BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 40-47 */ _BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D,_BCM_D, /* 48-55 */ _BCM_D,_BCM_D,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 56-63 */ _BCM_P, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U|_BCM_X, _BCM_U, /* 64-71 */ _BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 72-79 */ _BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U,_BCM_U, /* 80-87 */ _BCM_U,_BCM_U,_BCM_U,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_P, /* 88-95 */ _BCM_P, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L|_BCM_X, _BCM_L, /* 96-103 */ _BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 104-111 */ _BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L,_BCM_L, /* 112-119 */ _BCM_L,_BCM_L,_BCM_L,_BCM_P,_BCM_P,_BCM_P,_BCM_P,_BCM_C, /* 120-127 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 128-143 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 144-159 */ _BCM_S|_BCM_SP, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 160-175 */ _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, _BCM_P, /* 176-191 */ _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, /* 192-207 */ _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_P, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_U, _BCM_L, /* 208-223 */ _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, /* 224-239 */ _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_P, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L, _BCM_L /* 240-255 */ }; ulong bcm_strtoul(char *cp, char **endp, uint base) { ulong result, last_result = 0, value; bool minus; minus = FALSE; while (bcm_isspace(*cp)) cp++; if (cp[0] == '+') cp++; else if (cp[0] == '-') { minus = TRUE; cp++; } if (base == 0) { if (cp[0] == '0') { if ((cp[1] == 'x') || (cp[1] == 'X')) { base = 16; cp = &cp[2]; } else { base = 8; cp = &cp[1]; } } else base = 10; } else if (base == 16 && (cp[0] == '0') && ((cp[1] == 'x') || (cp[1] == 'X'))) { cp = &cp[2]; } result = 0; while (bcm_isxdigit(*cp) && (value = bcm_isdigit(*cp) ? *cp-'0' : bcm_toupper(*cp)-'A'+10) < base) { result = result*base + value; /* Detected overflow */ if (result < last_result && !minus) return (ulong)-1; last_result = result; cp++; } if (minus) result = (ulong)(-(long)result); if (endp) *endp = (char *)cp; return (result); } int bcm_atoi(char *s) { return (int)bcm_strtoul(s, NULL, 10); } /* return pointer to location of substring 'needle' in 'haystack' */ char* bcmstrstr(char *haystack, char *needle) { int len, nlen; int i; if ((haystack == NULL) || (needle == NULL)) return (haystack); nlen = strlen(needle); len = strlen(haystack) - nlen + 1; for (i = 0; i < len; i++) if (memcmp(needle, &haystack[i], nlen) == 0) return (&haystack[i]); return (NULL); } char* bcmstrcat(char *dest, const char *src) { char *p; p = dest + strlen(dest); while ((*p++ = *src++) != '\0') ; return (dest); } char* bcmstrncat(char *dest, const char *src, uint size) { char *endp; char *p; p = dest + strlen(dest); endp = p + size; while (p != endp && (*p++ = *src++) != '\0') ; return (dest); } /**************************************************************************** * Function: bcmstrtok * * Purpose: * Tokenizes a string. This function is conceptually similiar to ANSI C strtok(), * but allows strToken() to be used by different strings or callers at the same * time. Each call modifies '*string' by substituting a NULL character for the * first delimiter that is encountered, and updates 'string' to point to the char * after the delimiter. Leading delimiters are skipped. * * Parameters: * string (mod) Ptr to string ptr, updated by token. * delimiters (in) Set of delimiter characters. * tokdelim (out) Character that delimits the returned token. (May * be set to NULL if token delimiter is not required). * * Returns: Pointer to the next token found. NULL when no more tokens are found. ***************************************************************************** */ char * bcmstrtok(char **string, const char *delimiters, char *tokdelim) { unsigned char *str; unsigned long map[8]; int count; char *nextoken; if (tokdelim != NULL) { /* Prime the token delimiter */ *tokdelim = '\0'; } /* Clear control map */ for (count = 0; count < 8; count++) { map[count] = 0; } /* Set bits in delimiter table */ do { map[*delimiters >> 5] |= (1 << (*delimiters & 31)); } while (*delimiters++); str = (unsigned char*)*string; /* Find beginning of token (skip over leading delimiters). Note that * there is no token iff this loop sets str to point to the terminal * null (*str == '\0') */ while (((map[*str >> 5] & (1 << (*str & 31))) && *str) || (*str == ' ')) { str++; } nextoken = (char*)str; /* Find the end of the token. If it is not the end of the string, * put a null there. */ for (; *str; str++) { if (map[*str >> 5] & (1 << (*str & 31))) { if (tokdelim != NULL) { *tokdelim = *str; } *str++ = '\0'; break; } } *string = (char*)str; /* Determine if a token has been found. */ if (nextoken == (char *) str) { return NULL; } else { return nextoken; } } #define xToLower(C) \ ((C >= 'A' && C <= 'Z') ? (char)((int)C - (int)'A' + (int)'a') : C) /**************************************************************************** * Function: bcmstricmp * * Purpose: Compare to strings case insensitively. * * Parameters: s1 (in) First string to compare. * s2 (in) Second string to compare. * * Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if * t1 > t2, when ignoring case sensitivity. ***************************************************************************** */ int bcmstricmp(const char *s1, const char *s2) { char dc, sc; while (*s2 && *s1) { dc = xToLower(*s1); sc = xToLower(*s2); if (dc < sc) return -1; if (dc > sc) return 1; s1++; s2++; } if (*s1 && !*s2) return 1; if (!*s1 && *s2) return -1; return 0; } /**************************************************************************** * Function: bcmstrnicmp * * Purpose: Compare to strings case insensitively, upto a max of 'cnt' * characters. * * Parameters: s1 (in) First string to compare. * s2 (in) Second string to compare. * cnt (in) Max characters to compare. * * Returns: Return 0 if the two strings are equal, -1 if t1 < t2 and 1 if * t1 > t2, when ignoring case sensitivity. ***************************************************************************** */ int bcmstrnicmp(const char* s1, const char* s2, int cnt) { char dc, sc; while (*s2 && *s1 && cnt) { dc = xToLower(*s1); sc = xToLower(*s2); if (dc < sc) return -1; if (dc > sc) return 1; s1++; s2++; cnt--; } if (!cnt) return 0; if (*s1 && !*s2) return 1; if (!*s1 && *s2) return -1; return 0; } /* parse a xx:xx:xx:xx:xx:xx format ethernet address */ int bcm_ether_atoe(char *p, struct ether_addr *ea) { int i = 0; for (;;) { ea->octet[i++] = (char) bcm_strtoul(p, &p, 16); if (!*p++ || i == 6) break; } return (i == 6); } #if defined(CONFIG_USBRNDIS_RETAIL) || defined(NDIS_MINIPORT_DRIVER) /* registry routine buffer preparation utility functions: * parameter order is like strncpy, but returns count * of bytes copied. Minimum bytes copied is null char(1)/wchar(2) */ ulong wchar2ascii(char *abuf, ushort *wbuf, ushort wbuflen, ulong abuflen) { ulong copyct = 1; ushort i; if (abuflen == 0) return 0; /* wbuflen is in bytes */ wbuflen /= sizeof(ushort); for (i = 0; i < wbuflen; ++i) { if (--abuflen == 0) break; *abuf++ = (char) *wbuf++; ++copyct; } *abuf = '\0'; return copyct; } #endif /* CONFIG_USBRNDIS_RETAIL || NDIS_MINIPORT_DRIVER */ char * bcm_ether_ntoa(const struct ether_addr *ea, char *buf) { static const char template[] = "%02x:%02x:%02x:%02x:%02x:%02x"; snprintf(buf, 18, template, ea->octet[0]&0xff, ea->octet[1]&0xff, ea->octet[2]&0xff, ea->octet[3]&0xff, ea->octet[4]&0xff, ea->octet[5]&0xff); return (buf); } char * bcm_ip_ntoa(struct ipv4_addr *ia, char *buf) { snprintf(buf, 16, "%d.%d.%d.%d", ia->addr[0], ia->addr[1], ia->addr[2], ia->addr[3]); return (buf); } #ifdef BCMDRIVER void bcm_mdelay(uint ms) { uint i; for (i = 0; i < ms; i++) { OSL_DELAY(1000); } } #if defined(DHD_DEBUG) /* pretty hex print a pkt buffer chain */ void prpkt(const char *msg, osl_t *osh, void *p0) { void *p; if (msg && (msg[0] != '\0')) printf("%s:\n", msg); for (p = p0; p; p = PKTNEXT(osh, p)) prhex(NULL, PKTDATA(osh, p), PKTLEN(osh, p)); } #endif /* Takes an Ethernet frame and sets out-of-bound PKTPRIO. * Also updates the inplace vlan tag if requested. * For debugging, it returns an indication of what it did. */ uint pktsetprio(void *pkt, bool update_vtag) { struct ether_header *eh; struct ethervlan_header *evh; uint8 *pktdata; int priority = 0; int rc = 0; pktdata = (uint8 *) PKTDATA(NULL, pkt); ASSERT(ISALIGNED((uintptr)pktdata, sizeof(uint16))); eh = (struct ether_header *) pktdata; if (ntoh16(eh->ether_type) == ETHER_TYPE_8021Q) { uint16 vlan_tag; int vlan_prio, dscp_prio = 0; evh = (struct ethervlan_header *)eh; vlan_tag = ntoh16(evh->vlan_tag); vlan_prio = (int) (vlan_tag >> VLAN_PRI_SHIFT) & VLAN_PRI_MASK; if (ntoh16(evh->ether_type) == ETHER_TYPE_IP) { uint8 *ip_body = pktdata + sizeof(struct ethervlan_header); uint8 tos_tc = IP_TOS(ip_body); /* FMC fix */ uint8 tos = tos_tc >> 2; if (tos == 0x2E) { dscp_prio = 6; } else if (tos == 0x1A) { dscp_prio = 4; } else { dscp_prio = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT); } } /* DSCP priority gets precedence over 802.1P (vlan tag) */ if (dscp_prio != 0) { priority = dscp_prio; rc |= PKTPRIO_VDSCP; } else { priority = vlan_prio; rc |= PKTPRIO_VLAN; } /* * If the DSCP priority is not the same as the VLAN priority, * then overwrite the priority field in the vlan tag, with the * DSCP priority value. This is required for Linux APs because * the VLAN driver on Linux, overwrites the skb->priority field * with the priority value in the vlan tag */ if (update_vtag && (priority != vlan_prio)) { vlan_tag &= ~(VLAN_PRI_MASK << VLAN_PRI_SHIFT); vlan_tag |= (uint16)priority << VLAN_PRI_SHIFT; evh->vlan_tag = hton16(vlan_tag); rc |= PKTPRIO_UPD; } } else if (ntoh16(eh->ether_type) == ETHER_TYPE_IP) { uint8 *ip_body = pktdata + sizeof(struct ether_header); uint8 tos_tc = IP_TOS(ip_body); /* FMC fix */ uint8 tos = tos_tc >> 2; if (tos == 0x2E) { priority = 6; } else if (tos == 0x1A) { priority = 4; } else { priority = (int)(tos_tc >> IPV4_TOS_PREC_SHIFT); } rc |= PKTPRIO_DSCP; } ASSERT(priority >= 0 && priority <= MAXPRIO); PKTSETPRIO(pkt, priority); return (rc | priority); } static char bcm_undeferrstr[BCME_STRLEN]; static const char *bcmerrorstrtable[] = BCMERRSTRINGTABLE; /* Convert the error codes into related error strings */ const char * bcmerrorstr(int bcmerror) { /* check if someone added a bcmerror code but forgot to add errorstring */ ASSERT(ABS(BCME_LAST) == (ARRAYSIZE(bcmerrorstrtable) - 1)); if (bcmerror > 0 || bcmerror < BCME_LAST) { snprintf(bcm_undeferrstr, BCME_STRLEN, "Undefined error %d", bcmerror); return bcm_undeferrstr; } ASSERT(strlen(bcmerrorstrtable[-bcmerror]) < BCME_STRLEN); return bcmerrorstrtable[-bcmerror]; } /* iovar table lookup */ const bcm_iovar_t* bcm_iovar_lookup(const bcm_iovar_t *table, const char *name) { const bcm_iovar_t *vi; const char *lookup_name; /* skip any ':' delimited option prefixes */ lookup_name = strrchr(name, ':'); if (lookup_name != NULL) lookup_name++; else lookup_name = name; ASSERT(table != NULL); for (vi = table; vi->name; vi++) { if (!strcmp(vi->name, lookup_name)) return vi; } /* ran to end of table */ return NULL; /* var name not found */ } int bcm_iovar_lencheck(const bcm_iovar_t *vi, void *arg, int len, bool set) { int bcmerror = 0; /* length check on io buf */ switch (vi->type) { case IOVT_BOOL: case IOVT_INT8: case IOVT_INT16: case IOVT_INT32: case IOVT_UINT8: case IOVT_UINT16: case IOVT_UINT32: /* all integers are int32 sized args at the ioctl interface */ if (len < (int)sizeof(int)) { bcmerror = BCME_BUFTOOSHORT; } break; case IOVT_BUFFER: /* buffer must meet minimum length requirement */ if (len < vi->minlen) { bcmerror = BCME_BUFTOOSHORT; } break; case IOVT_VOID: if (!set) { /* Cannot return nil... */ bcmerror = BCME_UNSUPPORTED; } else if (len) { /* Set is an action w/o parameters */ bcmerror = BCME_BUFTOOLONG; } break; default: /* unknown type for length check in iovar info */ ASSERT(0); bcmerror = BCME_UNSUPPORTED; } return bcmerror; } #endif /* BCMDRIVER */ /******************************************************************************* * crc8 * * Computes a crc8 over the input data using the polynomial: * * x^8 + x^7 +x^6 + x^4 + x^2 + 1 * * The caller provides the initial value (either CRC8_INIT_VALUE * or the previous returned value) to allow for processing of * discontiguous blocks of data. When generating the CRC the * caller is responsible for complementing the final return value * and inserting it into the byte stream. When checking, a final * return value of CRC8_GOOD_VALUE indicates a valid CRC. * * Reference: Dallas Semiconductor Application Note 27 * Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms", * ver 3, Aug 1993, [email protected], Rocksoft Pty Ltd., * ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt * * **************************************************************************** */ STATIC const uint8 crc8_table[256] = { 0x00, 0xF7, 0xB9, 0x4E, 0x25, 0xD2, 0x9C, 0x6B, 0x4A, 0xBD, 0xF3, 0x04, 0x6F, 0x98, 0xD6, 0x21, 0x94, 0x63, 0x2D, 0xDA, 0xB1, 0x46, 0x08, 0xFF, 0xDE, 0x29, 0x67, 0x90, 0xFB, 0x0C, 0x42, 0xB5, 0x7F, 0x88, 0xC6, 0x31, 0x5A, 0xAD, 0xE3, 0x14, 0x35, 0xC2, 0x8C, 0x7B, 0x10, 0xE7, 0xA9, 0x5E, 0xEB, 0x1C, 0x52, 0xA5, 0xCE, 0x39, 0x77, 0x80, 0xA1, 0x56, 0x18, 0xEF, 0x84, 0x73, 0x3D, 0xCA, 0xFE, 0x09, 0x47, 0xB0, 0xDB, 0x2C, 0x62, 0x95, 0xB4, 0x43, 0x0D, 0xFA, 0x91, 0x66, 0x28, 0xDF, 0x6A, 0x9D, 0xD3, 0x24, 0x4F, 0xB8, 0xF6, 0x01, 0x20, 0xD7, 0x99, 0x6E, 0x05, 0xF2, 0xBC, 0x4B, 0x81, 0x76, 0x38, 0xCF, 0xA4, 0x53, 0x1D, 0xEA, 0xCB, 0x3C, 0x72, 0x85, 0xEE, 0x19, 0x57, 0xA0, 0x15, 0xE2, 0xAC, 0x5B, 0x30, 0xC7, 0x89, 0x7E, 0x5F, 0xA8, 0xE6, 0x11, 0x7A, 0x8D, 0xC3, 0x34, 0xAB, 0x5C, 0x12, 0xE5, 0x8E, 0x79, 0x37, 0xC0, 0xE1, 0x16, 0x58, 0xAF, 0xC4, 0x33, 0x7D, 0x8A, 0x3F, 0xC8, 0x86, 0x71, 0x1A, 0xED, 0xA3, 0x54, 0x75, 0x82, 0xCC, 0x3B, 0x50, 0xA7, 0xE9, 0x1E, 0xD4, 0x23, 0x6D, 0x9A, 0xF1, 0x06, 0x48, 0xBF, 0x9E, 0x69, 0x27, 0xD0, 0xBB, 0x4C, 0x02, 0xF5, 0x40, 0xB7, 0xF9, 0x0E, 0x65, 0x92, 0xDC, 0x2B, 0x0A, 0xFD, 0xB3, 0x44, 0x2F, 0xD8, 0x96, 0x61, 0x55, 0xA2, 0xEC, 0x1B, 0x70, 0x87, 0xC9, 0x3E, 0x1F, 0xE8, 0xA6, 0x51, 0x3A, 0xCD, 0x83, 0x74, 0xC1, 0x36, 0x78, 0x8F, 0xE4, 0x13, 0x5D, 0xAA, 0x8B, 0x7C, 0x32, 0xC5, 0xAE, 0x59, 0x17, 0xE0, 0x2A, 0xDD, 0x93, 0x64, 0x0F, 0xF8, 0xB6, 0x41, 0x60, 0x97, 0xD9, 0x2E, 0x45, 0xB2, 0xFC, 0x0B, 0xBE, 0x49, 0x07, 0xF0, 0x9B, 0x6C, 0x22, 0xD5, 0xF4, 0x03, 0x4D, 0xBA, 0xD1, 0x26, 0x68, 0x9F }; #define CRC_INNER_LOOP(n, c, x) \ (c) = ((c) >> 8) ^ crc##n##_table[((c) ^ (x)) & 0xff] uint8 hndcrc8( uint8 *pdata, /* pointer to array of data to process */ uint nbytes, /* number of input data bytes to process */ uint8 crc /* either CRC8_INIT_VALUE or previous return value */ ) { /* hard code the crc loop instead of using CRC_INNER_LOOP macro * to avoid the undefined and unnecessary (uint8 >> 8) operation. */ while (nbytes-- > 0) crc = crc8_table[(crc ^ *pdata++) & 0xff]; return crc; } /******************************************************************************* * crc16 * * Computes a crc16 over the input data using the polynomial: * * x^16 + x^12 +x^5 + 1 * * The caller provides the initial value (either CRC16_INIT_VALUE * or the previous returned value) to allow for processing of * discontiguous blocks of data. When generating the CRC the * caller is responsible for complementing the final return value * and inserting it into the byte stream. When checking, a final * return value of CRC16_GOOD_VALUE indicates a valid CRC. * * Reference: Dallas Semiconductor Application Note 27 * Williams, Ross N., "A Painless Guide to CRC Error Detection Algorithms", * ver 3, Aug 1993, [email protected], Rocksoft Pty Ltd., * ftp://ftp.rocksoft.com/clients/rocksoft/papers/crc_v3.txt * * **************************************************************************** */ static const uint16 crc16_table[256] = { 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78 }; uint16 hndcrc16( uint8 *pdata, /* pointer to array of data to process */ uint nbytes, /* number of input data bytes to process */ uint16 crc /* either CRC16_INIT_VALUE or previous return value */ ) { while (nbytes-- > 0) CRC_INNER_LOOP(16, crc, *pdata++); return crc; } STATIC const uint32 crc32_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; uint32 hndcrc32( uint8 *pdata, /* pointer to array of data to process */ uint nbytes, /* number of input data bytes to process */ uint32 crc /* either CRC32_INIT_VALUE or previous return value */ ) { uint8 *pend; #ifdef __mips__ uint8 tmp[4]; ulong *tptr = (ulong *)tmp; /* in case the beginning of the buffer isn't aligned */ pend = (uint8 *)((uint)(pdata + 3) & 0xfffffffc); nbytes -= (pend - pdata); while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); /* handle bulk of data as 32-bit words */ pend = pdata + (nbytes & 0xfffffffc); while (pdata < pend) { *tptr = *(ulong *)pdata; pdata += sizeof(ulong *); CRC_INNER_LOOP(32, crc, tmp[0]); CRC_INNER_LOOP(32, crc, tmp[1]); CRC_INNER_LOOP(32, crc, tmp[2]); CRC_INNER_LOOP(32, crc, tmp[3]); } /* 1-3 bytes at end of buffer */ pend = pdata + (nbytes & 0x03); while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); #else pend = pdata + nbytes; while (pdata < pend) CRC_INNER_LOOP(32, crc, *pdata++); #endif /* __mips__ */ return crc; } #ifdef notdef #define CLEN 1499 /* CRC Length */ #define CBUFSIZ (CLEN+4) #define CNBUFS 5 /* # of bufs */ void testcrc32(void) { uint j, k, l; uint8 *buf; uint len[CNBUFS]; uint32 crcr; uint32 crc32tv[CNBUFS] = {0xd2cb1faa, 0xd385c8fa, 0xf5b4f3f3, 0x55789e20, 0x00343110}; ASSERT((buf = MALLOC(CBUFSIZ*CNBUFS)) != NULL); /* step through all possible alignments */ for (l = 0; l <= 4; l++) { for (j = 0; j < CNBUFS; j++) { len[j] = CLEN; for (k = 0; k < len[j]; k++) *(buf + j*CBUFSIZ + (k+l)) = (j+k) & 0xff; } for (j = 0; j < CNBUFS; j++) { crcr = crc32(buf + j*CBUFSIZ + l, len[j], CRC32_INIT_VALUE); ASSERT(crcr == crc32tv[j]); } } MFREE(buf, CBUFSIZ*CNBUFS); return; } #endif /* notdef */ /* * Advance from the current 1-byte tag/1-byte length/variable-length value * triple, to the next, returning a pointer to the next. * If the current or next TLV is invalid (does not fit in given buffer length), * NULL is returned. * *buflen is not modified if the TLV elt parameter is invalid, or is decremented * by the TLV parameter's length if it is valid. */ bcm_tlv_t * bcm_next_tlv(bcm_tlv_t *elt, int *buflen) { int len; /* validate current elt */ if (!bcm_valid_tlv(elt, *buflen)) return NULL; /* advance to next elt */ len = elt->len; elt = (bcm_tlv_t*)(elt->data + len); *buflen -= (2 + len); /* validate next elt */ if (!bcm_valid_tlv(elt, *buflen)) return NULL; return elt; } /* * Traverse a string of 1-byte tag/1-byte length/variable-length value * triples, returning a pointer to the substring whose first element * matches tag */ bcm_tlv_t * bcm_parse_tlvs(void *buf, int buflen, uint key) { bcm_tlv_t *elt; int totlen; elt = (bcm_tlv_t*)buf; totlen = buflen; /* find tagged parameter */ while (totlen >= 2) { int len = elt->len; /* validate remaining totlen */ if ((elt->id == key) && (totlen >= (len + 2))) return (elt); elt = (bcm_tlv_t*)((uint8*)elt + (len + 2)); totlen -= (len + 2); } return NULL; } /* * Traverse a string of 1-byte tag/1-byte length/variable-length value * triples, returning a pointer to the substring whose first element * matches tag. Stop parsing when we see an element whose ID is greater * than the target key. */ bcm_tlv_t * bcm_parse_ordered_tlvs(void *buf, int buflen, uint key) { bcm_tlv_t *elt; int totlen; elt = (bcm_tlv_t*)buf; totlen = buflen; /* find tagged parameter */ while (totlen >= 2) { uint id = elt->id; int len = elt->len; /* Punt if we start seeing IDs > than target key */ if (id > key) return (NULL); /* validate remaining totlen */ if ((id == key) && (totlen >= (len + 2))) return (elt); elt = (bcm_tlv_t*)((uint8*)elt + (len + 2)); totlen -= (len + 2); } return NULL; } #if defined(WLMSG_PRHDRS) || defined(WLMSG_PRPKT) || defined(WLMSG_ASSOC) || \ defined(DHD_DEBUG) int bcm_format_flags(const bcm_bit_desc_t *bd, uint32 flags, char* buf, int len) { int i; char* p = buf; char hexstr[16]; int slen = 0; uint32 bit; const char* name; if (len < 2 || !buf) return 0; buf[0] = '\0'; len -= 1; for (i = 0; flags != 0; i++) { bit = bd[i].bit; name = bd[i].name; if (bit == 0 && flags) { /* print any unnamed bits */ sprintf(hexstr, "0x%X", flags); name = hexstr; flags = 0; /* exit loop */ } else if ((flags & bit) == 0) continue; slen += strlen(name); if (len < slen) break; if (p != buf) p += sprintf(p, " "); /* btwn flag space */ strcat(p, name); p += strlen(name); flags &= ~bit; len -= slen; slen = 1; /* account for btwn flag space */ } /* indicate the str was too short */ if (flags != 0) { if (len == 0) p--; /* overwrite last char */ p += sprintf(p, ">"); } return (int)(p - buf); } /* print bytes formatted as hex to a string. return the resulting string length */ int bcm_format_hex(char *str, const void *bytes, int len) { int i; char *p = str; const uint8 *src = (const uint8*)bytes; for (i = 0; i < len; i++) { p += sprintf(p, "%02X", *src); src++; } return (int)(p - str); } /* pretty hex print a contiguous buffer */ void prhex(const char *msg, uchar *buf, uint nbytes) { char line[128], *p; uint i; if (msg && (msg[0] != '\0')) printf("%s:\n", msg); p = line; for (i = 0; i < nbytes; i++) { if (i % 16 == 0) { p += sprintf(p, " %04d: ", i); /* line prefix */ } p += sprintf(p, "%02x ", buf[i]); if (i % 16 == 15) { printf("%s\n", line); /* flush line */ p = line; } } /* flush last partial line */ if (p != line) printf("%s\n", line); } #endif /* Produce a human-readable string for boardrev */ char * bcm_brev_str(uint32 brev, char *buf) { if (brev < 0x100) snprintf(buf, 8, "%d.%d", (brev & 0xf0) >> 4, brev & 0xf); else snprintf(buf, 8, "%c%03x", ((brev & 0xf000) == 0x1000) ? 'P' : 'A', brev & 0xfff); return (buf); } #define BUFSIZE_TODUMP_ATONCE 512 /* Buffer size */ /* dump large strings to console */ void printbig(char *buf) { uint len, max_len; char c; len = strlen(buf); max_len = BUFSIZE_TODUMP_ATONCE; while (len > max_len) { c = buf[max_len]; buf[max_len] = '\0'; printf("%s", buf); buf[max_len] = c; buf += max_len; len -= max_len; } /* print the remaining string */ printf("%s\n", buf); return; } /* routine to dump fields in a fileddesc structure */ uint bcmdumpfields(bcmutl_rdreg_rtn read_rtn, void *arg0, uint arg1, struct fielddesc *fielddesc_array, char *buf, uint32 bufsize) { uint filled_len; int len; struct fielddesc *cur_ptr; filled_len = 0; cur_ptr = fielddesc_array; while (bufsize > 1) { if (cur_ptr->nameandfmt == NULL) break; len = snprintf(buf, bufsize, cur_ptr->nameandfmt, read_rtn(arg0, arg1, cur_ptr->offset)); /* check for snprintf overflow or error */ if (len < 0 || (uint32)len >= bufsize) len = bufsize - 1; buf += len; bufsize -= len; filled_len += len; cur_ptr++; } return filled_len; } uint bcm_mkiovar(char *name, char *data, uint datalen, char *buf, uint buflen) { uint len; len = strlen(name) + 1; if ((len + datalen) > buflen) return 0; strncpy(buf, name, buflen); /* append data onto the end of the name string */ memcpy(&buf[len], data, datalen); len += datalen; return len; } /* Quarter dBm units to mW * Table starts at QDBM_OFFSET, so the first entry is mW for qdBm=153 * Table is offset so the last entry is largest mW value that fits in * a uint16. */ #define QDBM_OFFSET 153 /* Offset for first entry */ #define QDBM_TABLE_LEN 40 /* Table size */ /* Smallest mW value that will round up to the first table entry, QDBM_OFFSET. * Value is ( mW(QDBM_OFFSET - 1) + mW(QDBM_OFFSET) ) / 2 */ #define QDBM_TABLE_LOW_BOUND 6493 /* Low bound */ /* Largest mW value that will round down to the last table entry, * QDBM_OFFSET + QDBM_TABLE_LEN-1. * Value is ( mW(QDBM_OFFSET + QDBM_TABLE_LEN - 1) + mW(QDBM_OFFSET + QDBM_TABLE_LEN) ) / 2. */ #define QDBM_TABLE_HIGH_BOUND 64938 /* High bound */ static const uint16 nqdBm_to_mW_map[QDBM_TABLE_LEN] = { /* qdBm: +0 +1 +2 +3 +4 +5 +6 +7 */ /* 153: */ 6683, 7079, 7499, 7943, 8414, 8913, 9441, 10000, /* 161: */ 10593, 11220, 11885, 12589, 13335, 14125, 14962, 15849, /* 169: */ 16788, 17783, 18836, 19953, 21135, 22387, 23714, 25119, /* 177: */ 26607, 28184, 29854, 31623, 33497, 35481, 37584, 39811, /* 185: */ 42170, 44668, 47315, 50119, 53088, 56234, 59566, 63096 }; uint16 bcm_qdbm_to_mw(uint8 qdbm) { uint factor = 1; int idx = qdbm - QDBM_OFFSET; if (idx >= QDBM_TABLE_LEN) { /* clamp to max uint16 mW value */ return 0xFFFF; } /* scale the qdBm index up to the range of the table 0-40 * where an offset of 40 qdBm equals a factor of 10 mW. */ while (idx < 0) { idx += 40; factor *= 10; } /* return the mW value scaled down to the correct factor of 10, * adding in factor/2 to get proper rounding. */ return ((nqdBm_to_mW_map[idx] + factor/2) / factor); } uint8 bcm_mw_to_qdbm(uint16 mw) { uint8 qdbm; int offset; uint mw_uint = mw; uint boundary; /* handle boundary case */ if (mw_uint <= 1) return 0; offset = QDBM_OFFSET; /* move mw into the range of the table */ while (mw_uint < QDBM_TABLE_LOW_BOUND) { mw_uint *= 10; offset -= 40; } for (qdbm = 0; qdbm < QDBM_TABLE_LEN-1; qdbm++) { boundary = nqdBm_to_mW_map[qdbm] + (nqdBm_to_mW_map[qdbm+1] - nqdBm_to_mW_map[qdbm])/2; if (mw_uint < boundary) break; } qdbm += (uint8)offset; return (qdbm); } uint bcm_bitcount(uint8 *bitmap, uint length) { uint bitcount = 0, i; uint8 tmp; for (i = 0; i < length; i++) { tmp = bitmap[i]; while (tmp) { bitcount++; tmp &= (tmp - 1); } } return bitcount; } #ifdef BCMDRIVER /* Initialization of bcmstrbuf structure */ void bcm_binit(struct bcmstrbuf *b, char *buf, uint size) { b->origsize = b->size = size; b->origbuf = b->buf = buf; } /* Buffer sprintf wrapper to guard against buffer overflow */ int bcm_bprintf(struct bcmstrbuf *b, const char *fmt, ...) { va_list ap; int r; va_start(ap, fmt); r = vsnprintf(b->buf, b->size, fmt, ap); /* Non Ansi C99 compliant returns -1, * Ansi compliant return r >= b->size, * bcmstdlib returns 0, handle all */ if ((r == -1) || (r >= (int)b->size) || (r == 0)) { b->size = 0; } else { b->size -= r; b->buf += r; } va_end(ap); return r; } void bcm_inc_bytes(uchar *num, int num_bytes, uint8 amount) { int i; for (i = 0; i < num_bytes; i++) { num[i] += amount; if (num[i] >= amount) break; amount = 1; } } int bcm_cmp_bytes(uchar *arg1, uchar *arg2, uint8 nbytes) { int i; for (i = nbytes - 1; i >= 0; i--) { if (arg1[i] != arg2[i]) return (arg1[i] - arg2[i]); } return 0; } void bcm_print_bytes(char *name, const uchar *data, int len) { int i; int per_line = 0; printf("%s: %d \n", name ? name : "", len); for (i = 0; i < len; i++) { printf("%02x ", *data++); per_line++; if (per_line == 16) { per_line = 0; printf("\n"); } } printf("\n"); } /* * buffer length needed for wlc_format_ssid * 32 SSID chars, max of 4 chars for each SSID char "\xFF", plus NULL. */ #if defined(WLTINYDUMP) || defined(WLMSG_INFORM) || defined(WLMSG_ASSOC) || \ defined(WLMSG_PRPKT) || defined(WLMSG_WSEC) int bcm_format_ssid(char* buf, const uchar ssid[], uint ssid_len) { uint i, c; char *p = buf; char *endp = buf + SSID_FMT_BUF_LEN; if (ssid_len > DOT11_MAX_SSID_LEN) ssid_len = DOT11_MAX_SSID_LEN; for (i = 0; i < ssid_len; i++) { c = (uint)ssid[i]; if (c == '\\') { *p++ = '\\'; *p++ = '\\'; } else if (bcm_isprint((uchar)c)) { *p++ = (char)c; } else { p += snprintf(p, (endp - p), "\\x%02X", c); } } *p = '\0'; ASSERT(p < endp); return (int)(p - buf); } #endif #endif /* BCMDRIVER */
sktjdgns1189/android_kernel_samsung_SHW-M130L
drivers/net/wireless/bcm4329/src/shared/bcmutils.c
C
gpl-2.0
44,532
/*************************************************************************** qgsogcutils.cpp --------------------- begin : March 2013 copyright : (C) 2013 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsogcutils.h" #include "qgsexpression.h" #include "qgsexpressionnodeimpl.h" #include "qgsexpressionfunction.h" #include "qgsexpressionprivate.h" #include "qgsgeometry.h" #include "qgswkbptr.h" #include "qgscoordinatereferencesystem.h" #include "qgsrectangle.h" #include "qgsvectorlayer.h" #include "qgsexpressioncontextutils.h" #include <QColor> #include <QStringList> #include <QTextStream> #include <QObject> #ifndef Q_OS_WIN #include <netinet/in.h> #else #include <winsock.h> #endif static const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" ); static const QString GML32_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml/3.2" ); static const QString OGC_NAMESPACE = QStringLiteral( "http://www.opengis.net/ogc" ); static const QString FES_NAMESPACE = QStringLiteral( "http://www.opengis.net/fes/2.0" ); QgsOgcUtilsExprToFilter::QgsOgcUtilsExprToFilter( QDomDocument &doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation ) : mDoc( doc ) , mGMLUsed( false ) , mGMLVersion( gmlVersion ) , mFilterVersion( filterVersion ) , mGeometryName( geometryName ) , mSrsName( srsName ) , mInvertAxisOrientation( invertAxisOrientation ) , mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" ) , mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" ) , mGeomId( 1 ) { QgsCoordinateReferenceSystem crs; if ( !mSrsName.isEmpty() ) crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mSrsName ); if ( crs.isValid() ) { if ( honourAxisOrientation && crs.hasAxisInverted() ) { mInvertAxisOrientation = !mInvertAxisOrientation; } } } QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode &geometryNode ) { QDomElement geometryTypeElement = geometryNode.toElement(); QString geomType = geometryTypeElement.tagName(); if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) { QDomNode geometryChild = geometryNode.firstChild(); if ( geometryChild.isNull() ) { return QgsGeometry(); } geometryTypeElement = geometryChild.toElement(); geomType = geometryTypeElement.tagName(); } if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) return QgsGeometry(); if ( geomType == QLatin1String( "Point" ) ) { return geometryFromGMLPoint( geometryTypeElement ); } else if ( geomType == QLatin1String( "LineString" ) ) { return geometryFromGMLLineString( geometryTypeElement ); } else if ( geomType == QLatin1String( "Polygon" ) ) { return geometryFromGMLPolygon( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiPoint" ) ) { return geometryFromGMLMultiPoint( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiLineString" ) ) { return geometryFromGMLMultiLineString( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiPolygon" ) ) { return geometryFromGMLMultiPolygon( geometryTypeElement ); } else if ( geomType == QLatin1String( "Box" ) ) { return QgsGeometry::fromRect( rectangleFromGMLBox( geometryTypeElement ) ); } else if ( geomType == QLatin1String( "Envelope" ) ) { return QgsGeometry::fromRect( rectangleFromGMLEnvelope( geometryTypeElement ) ); } else //unknown type { return QgsGeometry(); } } QgsGeometry QgsOgcUtils::geometryFromGML( const QString &xmlString ) { // wrap the string into a root tag to have "gml" namespace (and also as a default namespace) QString xml = QStringLiteral( "<tmp xmlns=\"%1\" xmlns:gml=\"%1\">%2</tmp>" ).arg( GML_NAMESPACE, xmlString ); QDomDocument doc; if ( !doc.setContent( xml, true ) ) return QgsGeometry(); return geometryFromGML( doc.documentElement().firstChildElement() ); } QgsGeometry QgsOgcUtils::geometryFromGMLPoint( const QDomElement &geometryElement ) { QgsPolylineXY pointCoordinate; QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { QDomElement coordElement = coordList.at( 0 ).toElement(); if ( readGMLCoordinates( pointCoordinate, coordElement ) != 0 ) { return QgsGeometry(); } } else { QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); } QDomElement posElement = posList.at( 0 ).toElement(); if ( readGMLPositions( pointCoordinate, posElement ) != 0 ) { return QgsGeometry(); } } if ( pointCoordinate.empty() ) { return QgsGeometry(); } QgsPolylineXY::const_iterator point_it = pointCoordinate.constBegin(); char e = htonl( 1 ) != 1; double x = point_it->x(); double y = point_it->y(); int size = 1 + sizeof( int ) + 2 * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::Point; unsigned char *wkb = new unsigned char[size]; int wkbPosition = 0; //current offset from wkb beginning (in bytes) memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLLineString( const QDomElement &geometryElement ) { QgsPolylineXY lineCoordinates; QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { QDomElement coordElement = coordList.at( 0 ).toElement(); if ( readGMLCoordinates( lineCoordinates, coordElement ) != 0 ) { return QgsGeometry(); } } else { QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); } QDomElement posElement = posList.at( 0 ).toElement(); if ( readGMLPositions( lineCoordinates, posElement ) != 0 ) { return QgsGeometry(); } } char e = htonl( 1 ) != 1; int size = 1 + 2 * sizeof( int ) + lineCoordinates.size() * 2 * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::LineString; unsigned char *wkb = new unsigned char[size]; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; int nPoints = lineCoordinates.size(); //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); QgsPolylineXY::const_iterator iter; for ( iter = lineCoordinates.constBegin(); iter != lineCoordinates.constEnd(); ++iter ) { x = iter->x(); y = iter->y(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement &geometryElement ) { //read all the coordinates (as QgsPoint) into memory. Each linear ring has an entry in the vector QgsMultiPolylineXY ringCoordinates; //read coordinates for outer boundary QgsPolylineXY exteriorPointList; QDomNodeList outerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) //outer ring is necessary { QDomElement coordinatesElement = outerBoundaryList.at( 0 ).firstChild().firstChild().toElement(); if ( coordinatesElement.isNull() ) { return QgsGeometry(); } if ( readGMLCoordinates( exteriorPointList, coordinatesElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary QDomNodeList innerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int i = 0; i < innerBoundaryList.size(); ++i ) { QgsPolylineXY interiorPointList; coordinatesElement = innerBoundaryList.at( i ).firstChild().firstChild().toElement(); if ( coordinatesElement.isNull() ) { return QgsGeometry(); } if ( readGMLCoordinates( interiorPointList, coordinatesElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( interiorPointList ); } } else { //read coordinates for exterior QDomNodeList exteriorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) //outer ring is necessary { return QgsGeometry(); } QDomElement posElement = exteriorList.at( 0 ).firstChild().firstChild().toElement(); if ( posElement.isNull() ) { return QgsGeometry(); } if ( readGMLPositions( exteriorPointList, posElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary QDomNodeList interiorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int i = 0; i < interiorList.size(); ++i ) { QgsPolylineXY interiorPointList; QDomElement posElement = interiorList.at( i ).firstChild().firstChild().toElement(); if ( posElement.isNull() ) { return QgsGeometry(); } if ( readGMLPositions( interiorPointList, posElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( interiorPointList ); } } //calculate number of bytes to allocate int nrings = ringCoordinates.size(); if ( nrings < 1 ) return QgsGeometry(); int npoints = 0;//total number of points for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it ) { npoints += it->size(); } int size = 1 + 2 * sizeof( int ) + nrings * sizeof( int ) + 2 * npoints * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::Polygon; unsigned char *wkb = new unsigned char[size]; //char e = QgsApplication::endian(); char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) int nPointsInRing = 0; double x, y; //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nrings, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it ) { nPointsInRing = it->size(); memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) ); wkbPosition += sizeof( int ); //iterate through the string list converting the strings to x-/y- doubles QgsPolylineXY::const_iterator iter; for ( iter = it->begin(); iter != it->end(); ++iter ) { x = iter->x(); y = iter->y(); //qWarning("currentCoordinate: " + QString::number(x) + " // " + QString::number(y)); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement &geometryElement ) { QgsPolylineXY pointList; QgsPolylineXY currentPoint; QDomNodeList pointMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pointMember" ) ); if ( pointMemberList.size() < 1 ) { return QgsGeometry(); } QDomNodeList pointNodeList; // coordinates or pos element QDomNodeList coordinatesList; QDomNodeList posList; for ( int i = 0; i < pointMemberList.size(); ++i ) { //<Point> element pointNodeList = pointMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Point" ) ); if ( pointNodeList.size() < 1 ) { continue; } //<coordinates> element coordinatesList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordinatesList.isEmpty() ) { currentPoint.clear(); if ( readGMLCoordinates( currentPoint, coordinatesList.at( 0 ).toElement() ) != 0 ) { continue; } if ( currentPoint.empty() ) { continue; } pointList.push_back( ( *currentPoint.begin() ) ); continue; } else { //<pos> element posList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { continue; } currentPoint.clear(); if ( readGMLPositions( currentPoint, posList.at( 0 ).toElement() ) != 0 ) { continue; } if ( currentPoint.empty() ) { continue; } pointList.push_back( ( *currentPoint.begin() ) ); } } int nPoints = pointList.size(); //number of points if ( nPoints < 1 ) return QgsGeometry(); //calculate the required wkb size int size = 1 + 2 * sizeof( int ) + pointList.size() * ( 2 * sizeof( double ) + 1 + sizeof( int ) ); QgsWkbTypes::Type type = QgsWkbTypes::MultiPoint; unsigned char *wkb = new unsigned char[size]; //fill the wkb content char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::Point; for ( QgsPolylineXY::const_iterator it = pointList.constBegin(); it != pointList.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); x = it->x(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); y = it->y(); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement &geometryElement ) { //geoserver has //<gml:MultiLineString> //<gml:lineStringMember> //<gml:LineString> //mapserver has directly //<gml:MultiLineString //<gml:LineString QList< QgsPolylineXY > lineCoordinates; //first list: lines, second list: points of one line QDomElement currentLineStringElement; QDomNodeList currentCoordList; QDomNodeList currentPosList; QDomNodeList lineStringMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lineStringMember" ) ); if ( !lineStringMemberList.isEmpty() ) //geoserver { for ( int i = 0; i < lineStringMemberList.size(); ++i ) { QDomNodeList lineStringNodeList = lineStringMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( lineStringNodeList.size() < 1 ) { return QgsGeometry(); } currentLineStringElement = lineStringNodeList.at( 0 ).toElement(); currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolylineXY currentPointList; if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } else { currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); } QgsPolylineXY currentPointList; if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } } } else { QDomNodeList lineStringList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( !lineStringList.isEmpty() ) //mapserver { for ( int i = 0; i < lineStringList.size(); ++i ) { currentLineStringElement = lineStringList.at( i ).toElement(); currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolylineXY currentPointList; if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); return QgsGeometry(); } else { currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); } QgsPolylineXY currentPointList; if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } } } else { return QgsGeometry(); } } int nLines = lineCoordinates.size(); if ( nLines < 1 ) return QgsGeometry(); //calculate the required wkb size int size = ( lineCoordinates.size() + 1 ) * ( 1 + 2 * sizeof( int ) ); for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it ) { size += it->size() * 2 * sizeof( double ); } QgsWkbTypes::Type type = QgsWkbTypes::MultiLineString; unsigned char *wkb = new unsigned char[size]; //fill the wkb content char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) int nPoints; //number of points in a line double x, y; memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nLines, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::LineString; for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); nPoints = it->size(); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolylineXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { x = iter->x(); y = iter->y(); // QgsDebugMsg( QStringLiteral( "x, y is %1,%2" ).arg( x, 'f' ).arg( y, 'f' ) ); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement &geometryElement ) { //first list: different polygons, second list: different rings, third list: different points QgsMultiPolygonXY multiPolygonPoints; QDomElement currentPolygonMemberElement; QDomNodeList polygonList; QDomElement currentPolygonElement; // rings in GML2 QDomNodeList outerBoundaryList; QDomElement currentOuterBoundaryElement; QDomNodeList innerBoundaryList; QDomElement currentInnerBoundaryElement; // rings in GML3 QDomNodeList exteriorList; QDomElement currentExteriorElement; QDomElement currentInteriorElement; QDomNodeList interiorList; // lienar ring QDomNodeList linearRingNodeList; QDomElement currentLinearRingElement; // Coordinates or position list QDomNodeList currentCoordinateList; QDomNodeList currentPosList; QDomNodeList polygonMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "polygonMember" ) ); QgsPolygonXY currentPolygonList; for ( int i = 0; i < polygonMemberList.size(); ++i ) { currentPolygonList.resize( 0 ); // preserve capacity - don't use clear currentPolygonMemberElement = polygonMemberList.at( i ).toElement(); polygonList = currentPolygonMemberElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Polygon" ) ); if ( polygonList.size() < 1 ) { continue; } currentPolygonElement = polygonList.at( 0 ).toElement(); //find exterior ring outerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) { currentOuterBoundaryElement = outerBoundaryList.at( 0 ).toElement(); QgsPolylineXY ringCoordinates; linearRingNodeList = currentOuterBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; } if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringCoordinates ); //find interior rings QDomNodeList innerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int j = 0; j < innerBoundaryList.size(); ++j ) { QgsPolylineXY ringCoordinates; currentInnerBoundaryElement = innerBoundaryList.at( j ).toElement(); linearRingNodeList = currentInnerBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; } if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringCoordinates ); } } else { //find exterior ring exteriorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) { continue; } currentExteriorElement = exteriorList.at( 0 ).toElement(); QgsPolylineXY ringPositions; linearRingNodeList = currentExteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; } if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringPositions ); //find interior rings QDomNodeList interiorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int j = 0; j < interiorList.size(); ++j ) { QgsPolylineXY ringPositions; currentInteriorElement = interiorList.at( j ).toElement(); linearRingNodeList = currentInteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; } if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringPositions ); } } multiPolygonPoints.push_back( currentPolygonList ); } int nPolygons = multiPolygonPoints.size(); if ( nPolygons < 1 ) return QgsGeometry(); int size = 1 + 2 * sizeof( int ); //calculate the wkb size for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it ) { size += 1 + 2 * sizeof( int ); for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { size += sizeof( int ) + 2 * iter->size() * sizeof( double ); } } QgsWkbTypes::Type type = QgsWkbTypes::MultiPolygon; unsigned char *wkb = new unsigned char[size]; char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; int nRings; int nPointsInRing; //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPolygons, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::Polygon; for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); nRings = it->size(); memcpy( &( wkb )[wkbPosition], &nRings, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { nPointsInRing = iter->size(); memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolylineXY::const_iterator iterator = iter->begin(); iterator != iter->end(); ++iterator ) { x = iterator->x(); y = iterator->y(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } bool QgsOgcUtils::readGMLCoordinates( QgsPolylineXY &coords, const QDomElement &elem ) { QString coordSeparator = QStringLiteral( "," ); QString tupelSeparator = QStringLiteral( " " ); //"decimal" has to be "." coords.clear(); if ( elem.hasAttribute( QStringLiteral( "cs" ) ) ) { coordSeparator = elem.attribute( QStringLiteral( "cs" ) ); } if ( elem.hasAttribute( QStringLiteral( "ts" ) ) ) { tupelSeparator = elem.attribute( QStringLiteral( "ts" ) ); } QStringList tupels = elem.text().split( tupelSeparator, QString::SkipEmptyParts ); QStringList tuple_coords; double x, y; bool conversionSuccess; QStringList::const_iterator it; for ( it = tupels.constBegin(); it != tupels.constEnd(); ++it ) { tuple_coords = ( *it ).split( coordSeparator, QString::SkipEmptyParts ); if ( tuple_coords.size() < 2 ) { continue; } x = tuple_coords.at( 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } y = tuple_coords.at( 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } coords.push_back( QgsPointXY( x, y ) ); } return false; } QgsRectangle QgsOgcUtils::rectangleFromGMLBox( const QDomNode &boxNode ) { QgsRectangle rect; QDomElement boxElem = boxNode.toElement(); if ( boxElem.tagName() != QLatin1String( "Box" ) ) return rect; QDomElement bElem = boxElem.firstChild().toElement(); QString coordSeparator = QStringLiteral( "," ); QString tupelSeparator = QStringLiteral( " " ); if ( bElem.hasAttribute( QStringLiteral( "cs" ) ) ) { coordSeparator = bElem.attribute( QStringLiteral( "cs" ) ); } if ( bElem.hasAttribute( QStringLiteral( "ts" ) ) ) { tupelSeparator = bElem.attribute( QStringLiteral( "ts" ) ); } QString bString = bElem.text(); bool ok1, ok2, ok3, ok4; double xmin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 0, 0 ).toDouble( &ok1 ); double ymin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 1, 1 ).toDouble( &ok2 ); double xmax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 0, 0 ).toDouble( &ok3 ); double ymax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 1, 1 ).toDouble( &ok4 ); if ( ok1 && ok2 && ok3 && ok4 ) { rect = QgsRectangle( xmin, ymin, xmax, ymax ); rect.normalize(); } return rect; } bool QgsOgcUtils::readGMLPositions( QgsPolylineXY &coords, const QDomElement &elem ) { coords.clear(); QStringList pos = elem.text().split( ' ', QString::SkipEmptyParts ); double x, y; bool conversionSuccess; int posSize = pos.size(); int srsDimension = 2; if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } for ( int i = 0; i < posSize / srsDimension; i++ ) { x = pos.at( i * srsDimension ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } y = pos.at( i * srsDimension + 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } coords.push_back( QgsPointXY( x, y ) ); } return false; } QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode &envelopeNode ) { QgsRectangle rect; QDomElement envelopeElem = envelopeNode.toElement(); if ( envelopeElem.tagName() != QLatin1String( "Envelope" ) ) return rect; QDomNodeList lowerCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lowerCorner" ) ); if ( lowerCornerList.size() < 1 ) return rect; QDomNodeList upperCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "upperCorner" ) ); if ( upperCornerList.size() < 1 ) return rect; bool conversionSuccess; int srsDimension = 2; QDomElement elem = lowerCornerList.at( 0 ).toElement(); if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } QString bString = elem.text(); double xmin = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; double ymin = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; elem = upperCornerList.at( 0 ).toElement(); if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } Q_UNUSED( srsDimension ) bString = elem.text(); double xmax = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; double ymax = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; rect = QgsRectangle( xmin, ymin, xmax, ymax ); rect.normalize(); return rect; } QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc, int precision ) { return rectangleToGMLBox( box, doc, QString(), false, precision ); } QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc, const QString &srsName, bool invertAxisOrientation, int precision ) { if ( !box ) { return QDomElement(); } QDomElement boxElem = doc.createElement( QStringLiteral( "gml:Box" ) ); if ( !srsName.isEmpty() ) { boxElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; coordString += qgsDoubleToString( invertAxisOrientation ? box->yMinimum() : box->xMinimum(), precision ); coordString += ','; coordString += qgsDoubleToString( invertAxisOrientation ? box->xMinimum() : box->yMinimum(), precision ); coordString += ' '; coordString += qgsDoubleToString( invertAxisOrientation ? box->yMaximum() : box->xMaximum(), precision ); coordString += ','; coordString += qgsDoubleToString( invertAxisOrientation ? box->xMaximum() : box->yMaximum(), precision ); QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); boxElem.appendChild( coordElem ); return boxElem; } QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc, int precision ) { return rectangleToGMLEnvelope( env, doc, QString(), false, precision ); } QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc, const QString &srsName, bool invertAxisOrientation, int precision ) { if ( !env ) { return QDomElement(); } QDomElement envElem = doc.createElement( QStringLiteral( "gml:Envelope" ) ); if ( !srsName.isEmpty() ) { envElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } QString posList; QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "gml:lowerCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMinimum() : env->xMinimum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMinimum() : env->yMinimum(), precision ); QDomText lowerCornerText = doc.createTextNode( posList ); lowerCornerElem.appendChild( lowerCornerText ); envElem.appendChild( lowerCornerElem ); QDomElement upperCornerElem = doc.createElement( QStringLiteral( "gml:upperCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMaximum() : env->xMaximum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMaximum() : env->yMaximum(), precision ); QDomText upperCornerText = doc.createTextNode( posList ); upperCornerElem.appendChild( upperCornerText ); envElem.appendChild( upperCornerElem ); return envElem; } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, const QString &format, int precision ) { return geometryToGML( geometry, doc, ( format == QLatin1String( "GML2" ) ) ? GML_2_1_2 : GML_3_2_1, QString(), false, QString(), precision ); } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, GMLVersion gmlVersion, const QString &srsName, bool invertAxisOrientation, const QString &gmlIdBase, int precision ) { if ( geometry.isNull() ) return QDomElement(); // coordinate separator QString cs = QStringLiteral( "," ); // tuple separator QString ts = QStringLiteral( " " ); // coord element tagname QDomElement baseCoordElem; bool hasZValue = false; QByteArray wkb( geometry.asWkb() ); QgsConstWkbPtr wkbPtr( wkb ); try { wkbPtr.readHeader(); } catch ( const QgsWkbException &e ) { Q_UNUSED( e ) // WKB exception while reading header return QDomElement(); } if ( gmlVersion != GML_2_1_2 ) { switch ( geometry.wkbType() ) { case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: case QgsWkbTypes::MultiPoint25D: case QgsWkbTypes::MultiPoint: baseCoordElem = doc.createElement( QStringLiteral( "gml:pos" ) ); break; default: baseCoordElem = doc.createElement( QStringLiteral( "gml:posList" ) ); break; } baseCoordElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); cs = ' '; } else { baseCoordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); baseCoordElem.setAttribute( QStringLiteral( "cs" ), cs ); baseCoordElem.setAttribute( QStringLiteral( "ts" ), ts ); } try { switch ( geometry.wkbType() ) { case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: { QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) pointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) ); coordElem.appendChild( coordText ); pointElem.appendChild( coordElem ); return pointElem; } case QgsWkbTypes::MultiPoint25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiPoint: { QDomElement multiPointElem = doc.createElement( QStringLiteral( "gml:MultiPoint" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiPointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiPointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; ++idx ) { QDomElement pointMemberElem = doc.createElement( QStringLiteral( "gml:pointMember" ) ); QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( idx + 1 ) ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); wkbPtr.readHeader(); double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) ); coordElem.appendChild( coordText ); pointElem.appendChild( coordElem ); if ( hasZValue ) { wkbPtr += sizeof( double ); } pointMemberElem.appendChild( pointElem ); multiPointElem.appendChild( pointMemberElem ); } return multiPointElem; } case QgsWkbTypes::LineString25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::LineString: { QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of points in the line int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int idx = 0; idx < nPoints; ++idx ) { if ( idx != 0 ) { coordString += ts; } double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); lineStringElem.appendChild( coordElem ); return lineStringElem; } case QgsWkbTypes::MultiLineString25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiLineString: { QDomElement multiLineStringElem = doc.createElement( QStringLiteral( "gml:MultiLineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiLineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiLineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { QDomElement lineStringMemberElem = doc.createElement( QStringLiteral( "gml:lineStringMember" ) ); QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( jdx + 1 ) ); wkbPtr.readHeader(); int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int idx = 0; idx < nPoints; idx++ ) { if ( idx != 0 ) { coordString += ts; } double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); lineStringElem.appendChild( coordElem ); lineStringMemberElem.appendChild( lineStringElem ); multiLineStringElem.appendChild( lineStringMemberElem ); } return multiLineStringElem; } case QgsWkbTypes::Polygon25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::Polygon: { QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of rings in the polygon int numRings; wkbPtr >> numRings; if ( numRings == 0 ) // sanity check for zero rings in polygon return QDomElement(); int *ringNumPoints = new int[numRings]; // number of points in each ring for ( int idx = 0; idx < numRings; idx++ ) { QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior"; if ( idx != 0 ) { boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); // get number of points in the ring int nPoints; wkbPtr >> nPoints; ringNumPoints[idx] = nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) { coordString += ts; } double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); ringElem.appendChild( coordElem ); boundaryElem.appendChild( ringElem ); polygonElem.appendChild( boundaryElem ); } delete [] ringNumPoints; return polygonElem; } case QgsWkbTypes::MultiPolygon25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiPolygon: { QDomElement multiPolygonElem = doc.createElement( QStringLiteral( "gml:MultiPolygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiPolygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiPolygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int numPolygons; wkbPtr >> numPolygons; for ( int kdx = 0; kdx < numPolygons; kdx++ ) { QDomElement polygonMemberElem = doc.createElement( QStringLiteral( "gml:polygonMember" ) ); QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( kdx + 1 ) ); wkbPtr.readHeader(); int numRings; wkbPtr >> numRings; for ( int idx = 0; idx < numRings; idx++ ) { QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior"; if ( idx != 0 ) { boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) { coordString += ts; } double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); ringElem.appendChild( coordElem ); boundaryElem.appendChild( ringElem ); polygonElem.appendChild( boundaryElem ); polygonMemberElem.appendChild( polygonElem ); multiPolygonElem.appendChild( polygonMemberElem ); } } return multiPolygonElem; } default: return QDomElement(); } } catch ( const QgsWkbException &e ) { Q_UNUSED( e ) return QDomElement(); } } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, int precision ) { return geometryToGML( geometry, doc, QStringLiteral( "GML2" ), precision ); } QDomElement QgsOgcUtils::createGMLCoordinates( const QgsPolylineXY &points, QDomDocument &doc ) { QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; QVector<QgsPointXY>::const_iterator pointIt = points.constBegin(); for ( ; pointIt != points.constEnd(); ++pointIt ) { if ( pointIt != points.constBegin() ) { coordString += ' '; } coordString += qgsDoubleToString( pointIt->x() ); coordString += ','; coordString += qgsDoubleToString( pointIt->y() ); } QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); return coordElem; } QDomElement QgsOgcUtils::createGMLPositions( const QgsPolylineXY &points, QDomDocument &doc ) { QDomElement posElem = doc.createElement( QStringLiteral( "gml:pos" ) ); if ( points.size() > 1 ) posElem = doc.createElement( QStringLiteral( "gml:posList" ) ); posElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); QString coordString; QVector<QgsPointXY>::const_iterator pointIt = points.constBegin(); for ( ; pointIt != points.constEnd(); ++pointIt ) { if ( pointIt != points.constBegin() ) { coordString += ' '; } coordString += qgsDoubleToString( pointIt->x() ); coordString += ' '; coordString += qgsDoubleToString( pointIt->y() ); } QDomText coordText = doc.createTextNode( coordString ); posElem.appendChild( coordText ); return posElem; } // ----------------------------------------- QColor QgsOgcUtils::colorFromOgcFill( const QDomElement &fillElement ) { if ( fillElement.isNull() || !fillElement.hasChildNodes() ) { return QColor(); } QString cssName; QString elemText; QColor color; QDomElement cssElem = fillElement.firstChildElement( QStringLiteral( "CssParameter" ) ); while ( !cssElem.isNull() ) { cssName = cssElem.attribute( QStringLiteral( "name" ), QStringLiteral( "not_found" ) ); if ( cssName != QLatin1String( "not_found" ) ) { elemText = cssElem.text(); if ( cssName == QLatin1String( "fill" ) ) { color.setNamedColor( elemText ); } else if ( cssName == QLatin1String( "fill-opacity" ) ) { bool ok; double opacity = elemText.toDouble( &ok ); if ( ok ) { color.setAlphaF( opacity ); } } } cssElem = cssElem.nextSiblingElement( QStringLiteral( "CssParameter" ) ); } return color; } QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, QgsVectorLayer *layer ) { return expressionFromOgcFilter( element, QgsOgcUtils::FILTER_OGC_1_0, layer ); } QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, const FilterVersion version, QgsVectorLayer *layer ) { if ( element.isNull() || !element.hasChildNodes() ) return nullptr; QgsExpression *expr = new QgsExpression(); // check if it is a single string value not having DOM elements // that express OGC operators if ( element.firstChild().nodeType() == QDomNode::TextNode ) { expr->setExpression( element.firstChild().nodeValue() ); return expr; } QgsOgcUtilsExpressionFromFilter utils( version, layer ); // then check OGC DOM elements that contain OGC tags specifying // OGC operators. QDomElement childElem = element.firstChildElement(); while ( !childElem.isNull() ) { QgsExpressionNode *node = utils.nodeFromOgcFilter( childElem ); if ( !node ) { // invalid expression, parser error expr->d->mParserErrorString = utils.errorMessage(); return expr; } // use the concat binary operator to append to the root node if ( !expr->d->mRootNode ) { expr->d->mRootNode = node; } else { expr->d->mRootNode = new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, expr->d->mRootNode, node ); } childElem = childElem.nextSiblingElement(); } // update expression string expr->d->mExp = expr->dump(); return expr; } static const QMap<QString, int> BINARY_OPERATORS_TAG_NAMES_MAP { // logical { QStringLiteral( "Or" ), QgsExpressionNodeBinaryOperator::boOr }, { QStringLiteral( "And" ), QgsExpressionNodeBinaryOperator::boAnd }, // comparison { QStringLiteral( "PropertyIsEqualTo" ), QgsExpressionNodeBinaryOperator::boEQ }, { QStringLiteral( "PropertyIsNotEqualTo" ), QgsExpressionNodeBinaryOperator::boNE }, { QStringLiteral( "PropertyIsLessThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boLE }, { QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boGE }, { QStringLiteral( "PropertyIsLessThan" ), QgsExpressionNodeBinaryOperator::boLT }, { QStringLiteral( "PropertyIsGreaterThan" ), QgsExpressionNodeBinaryOperator::boGT }, { QStringLiteral( "PropertyIsLike" ), QgsExpressionNodeBinaryOperator::boLike }, // arithmetic { QStringLiteral( "Add" ), QgsExpressionNodeBinaryOperator::boPlus }, { QStringLiteral( "Sub" ), QgsExpressionNodeBinaryOperator::boMinus }, { QStringLiteral( "Mul" ), QgsExpressionNodeBinaryOperator::boMul }, { QStringLiteral( "Div" ), QgsExpressionNodeBinaryOperator::boDiv }, }; static int binaryOperatorFromTagName( const QString &tagName ) { return BINARY_OPERATORS_TAG_NAMES_MAP.value( tagName, -1 ); } static QString binaryOperatorToTagName( QgsExpressionNodeBinaryOperator::BinaryOperator op ) { if ( op == QgsExpressionNodeBinaryOperator::boILike ) { return QStringLiteral( "PropertyIsLike" ); } return BINARY_OPERATORS_TAG_NAMES_MAP.key( op, QString() ); } static bool isBinaryOperator( const QString &tagName ) { return binaryOperatorFromTagName( tagName ) >= 0; } static bool isSpatialOperator( const QString &tagName ) { static QStringList spatialOps; if ( spatialOps.isEmpty() ) { spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); } return spatialOps.contains( tagName ); } QgsExpressionNode *QgsOgcUtils::nodeFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNode *node = utils.nodeFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNodeBinaryOperator *node = utils.nodeBinaryOperatorFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeFunction *QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeFunction *node = utils.nodeSpatialOperatorFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeUnaryOperator *QgsOgcUtils::nodeNotFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeUnaryOperator *node = utils.nodeNotFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeFunction *QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeFunction *node = utils.nodeFunctionFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNode *QgsOgcUtils::nodeLiteralFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNode *node = utils.nodeLiteralFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeColumnRef *QgsOgcUtils::nodeColumnRefFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeColumnRef *node = utils.nodeColumnRefFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNode *QgsOgcUtils::nodeIsBetweenFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNode *node = utils.nodeIsBetweenFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodePropertyIsNullFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeBinaryOperator *node = utils.nodePropertyIsNullFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } ///////////////// QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage ) { return expressionToOgcFilter( exp, doc, GML_2_1_2, FILTER_OGC_1_0, QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage ) { return expressionToOgcExpression( exp, doc, GML_2_1_2, FILTER_OGC_1_0, QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &expression, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation, QString *errorMessage ) { if ( !expression.rootNode() ) return QDomElement(); QgsExpression exp = expression; QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope(); QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation ); QDomElement exprRootElem = utils.expressionNodeToOgcFilter( exp.rootNode(), &exp, &context ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( exprRootElem.isNull() ) return QDomElement(); QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else attr.setValue( GML_NAMESPACE ); filterElem.setAttributeNode( attr ); } filterElem.appendChild( exprRootElem ); return filterElem; } QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &expression, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation, QString *errorMessage ) { QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope(); QgsExpression exp = expression; const QgsExpressionNode *node = exp.rootNode(); if ( !node ) return QDomElement(); switch ( node->nodeType() ) { case QgsExpressionNode::ntFunction: case QgsExpressionNode::ntLiteral: case QgsExpressionNode::ntColumnRef: { QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation ); QDomElement exprRootElem = utils.expressionNodeToOgcFilter( node, &exp, &context ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( !exprRootElem.isNull() ) { return exprRootElem; } break; } default: { if ( errorMessage ) *errorMessage = QObject::tr( "Node type not supported in expression translation: %1" ).arg( node->nodeType() ); } } // got an error return QDomElement(); } QDomElement QgsOgcUtils::SQLStatementToOgcFilter( const QgsSQLStatement &statement, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QList<LayerProperties> &layerProperties, bool honourAxisOrientation, bool invertAxisOrientation, const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename, QString *errorMessage ) { if ( !statement.rootNode() ) return QDomElement(); QgsOgcUtilsSQLStatementToFilter utils( doc, gmlVersion, filterVersion, layerProperties, honourAxisOrientation, invertAxisOrientation, mapUnprefixedTypenameToPrefixedTypename ); QDomElement exprRootElem = utils.toOgcFilter( statement.rootNode() ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( exprRootElem.isNull() ) return QDomElement(); QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else attr.setValue( GML_NAMESPACE ); filterElem.setAttributeNode( attr ); } filterElem.appendChild( exprRootElem ); return filterElem; } // QDomElement QgsOgcUtilsExprToFilter::expressionNodeToOgcFilter( const QgsExpressionNode *node, QgsExpression *expression, const QgsExpressionContext *context ) { switch ( node->nodeType() ) { case QgsExpressionNode::ntUnaryOperator: return expressionUnaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeUnaryOperator *>( node ), expression, context ); case QgsExpressionNode::ntBinaryOperator: return expressionBinaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeBinaryOperator *>( node ), expression, context ); case QgsExpressionNode::ntInOperator: return expressionInOperatorToOgcFilter( static_cast<const QgsExpressionNodeInOperator *>( node ), expression, context ); case QgsExpressionNode::ntFunction: return expressionFunctionToOgcFilter( static_cast<const QgsExpressionNodeFunction *>( node ), expression, context ); case QgsExpressionNode::ntLiteral: return expressionLiteralToOgcFilter( static_cast<const QgsExpressionNodeLiteral *>( node ), expression, context ); case QgsExpressionNode::ntColumnRef: return expressionColumnRefToOgcFilter( static_cast<const QgsExpressionNodeColumnRef *>( node ), expression, context ); default: mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() ); return QDomElement(); } } QDomElement QgsOgcUtilsExprToFilter::expressionUnaryOperatorToOgcFilter( const QgsExpressionNodeUnaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { QDomElement operandElem = expressionNodeToOgcFilter( node->operand(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement uoElem; switch ( node->op() ) { case QgsExpressionNodeUnaryOperator::uoMinus: uoElem = mDoc.createElement( mFilterPrefix + ":Literal" ); if ( node->operand()->nodeType() == QgsExpressionNode::ntLiteral ) { // operand expression already created a Literal node: // take the literal value, prepend - and remove old literal node uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) ); mDoc.removeChild( operandElem ); } else { mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" ); return QDomElement(); } break; case QgsExpressionNodeUnaryOperator::uoNot: uoElem = mDoc.createElement( mFilterPrefix + ":Not" ); uoElem.appendChild( operandElem ); break; default: mErrorMessage = QObject::tr( "Unary operator '%1' not implemented yet" ).arg( node->text() ); return QDomElement(); } return uoElem; } QDomElement QgsOgcUtilsExprToFilter::expressionBinaryOperatorToOgcFilter( const QgsExpressionNodeBinaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { QDomElement leftElem = expressionNodeToOgcFilter( node->opLeft(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QgsExpressionNodeBinaryOperator::BinaryOperator op = node->op(); // before right operator is parsed: to allow NULL handling if ( op == QgsExpressionNodeBinaryOperator::boIs || op == QgsExpressionNodeBinaryOperator::boIsNot ) { if ( node->opRight()->nodeType() == QgsExpressionNode::ntLiteral ) { const QgsExpressionNodeLiteral *rightLit = static_cast<const QgsExpressionNodeLiteral *>( node->opRight() ); if ( rightLit->value().isNull() ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" ); elem.appendChild( leftElem ); if ( op == QgsExpressionNodeBinaryOperator::boIsNot ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } // continue with equal / not equal operator once the null case is handled op = ( op == QgsExpressionNodeBinaryOperator::boIs ? QgsExpressionNodeBinaryOperator::boEQ : QgsExpressionNodeBinaryOperator::boNE ); } } QDomElement rightElem = expressionNodeToOgcFilter( node->opRight(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QString opText = binaryOperatorToTagName( op ); if ( opText.isEmpty() ) { // not implemented binary operators // TODO: regex, % (mod), ^ (pow) are not supported yet mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( node->text() ); return QDomElement(); } QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText ); if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike ) { if ( op == QgsExpressionNodeBinaryOperator::boILike ) boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to <ogc:PropertyIsLike> boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); boElem.appendChild( rightElem ); return boElem; } QDomElement QgsOgcUtilsExprToFilter::expressionLiteralToOgcFilter( const QgsExpressionNodeLiteral *node, QgsExpression *expression, const QgsExpressionContext *context ) { Q_UNUSED( expression ) Q_UNUSED( context ) QString value; switch ( node->value().type() ) { case QVariant::Int: value = QString::number( node->value().toInt() ); break; case QVariant::Double: value = qgsDoubleToString( node->value().toDouble() ); break; case QVariant::String: value = node->value().toString(); break; case QVariant::Date: value = node->value().toDate().toString( Qt::ISODate ); break; case QVariant::DateTime: value = node->value().toDateTime().toString( Qt::ISODate ); break; default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() ); return QDomElement(); } QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" ); litElem.appendChild( mDoc.createTextNode( value ) ); return litElem; } QDomElement QgsOgcUtilsExprToFilter::expressionColumnRefToOgcFilter( const QgsExpressionNodeColumnRef *node, QgsExpression *expression, const QgsExpressionContext *context ) { Q_UNUSED( expression ) Q_UNUSED( context ) QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem.appendChild( mDoc.createTextNode( node->name() ) ); return propElem; } QDomElement QgsOgcUtilsExprToFilter::expressionInOperatorToOgcFilter( const QgsExpressionNodeInOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { if ( node->list()->list().size() == 1 ) return expressionNodeToOgcFilter( node->list()->list()[0], expression, context ); QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" ); QDomElement leftNode = expressionNodeToOgcFilter( node->node(), expression, context ); const auto constList = node->list()->list(); for ( QgsExpressionNode *n : constList ) { QDomElement listNode = expressionNodeToOgcFilter( n, expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); eqElem.appendChild( leftNode.cloneNode() ); eqElem.appendChild( listNode ); orElem.appendChild( eqElem ); } if ( node->isNotIn() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( orElem ); return notElem; } return orElem; } static const QMap<QString, QString> BINARY_SPATIAL_OPS_MAP { { QStringLiteral( "disjoint" ), QStringLiteral( "Disjoint" ) }, { QStringLiteral( "intersects" ), QStringLiteral( "Intersects" )}, { QStringLiteral( "touches" ), QStringLiteral( "Touches" ) }, { QStringLiteral( "crosses" ), QStringLiteral( "Crosses" ) }, { QStringLiteral( "contains" ), QStringLiteral( "Contains" ) }, { QStringLiteral( "overlaps" ), QStringLiteral( "Overlaps" ) }, { QStringLiteral( "within" ), QStringLiteral( "Within" ) } }; static bool isBinarySpatialOperator( const QString &fnName ) { return BINARY_SPATIAL_OPS_MAP.contains( fnName ); } static QString tagNameForSpatialOperator( const QString &fnName ) { return BINARY_SPATIAL_OPS_MAP.value( fnName ); } static bool isGeometryColumn( const QgsExpressionNode *node ) { if ( node->nodeType() != QgsExpressionNode::ntFunction ) return false; const QgsExpressionNodeFunction *fn = static_cast<const QgsExpressionNodeFunction *>( node ); QgsExpressionFunction *fd = QgsExpression::Functions()[fn->fnIndex()]; return fd->name() == QLatin1String( "$geometry" ); } static QgsGeometry geometryFromConstExpr( const QgsExpressionNode *node ) { // Right now we support only geomFromWKT(' ..... ') // Ideally we should support any constant sub-expression (not dependent on feature's geometry or attributes) if ( node->nodeType() == QgsExpressionNode::ntFunction ) { const QgsExpressionNodeFunction *fnNode = static_cast<const QgsExpressionNodeFunction *>( node ); QgsExpressionFunction *fnDef = QgsExpression::Functions()[fnNode->fnIndex()]; if ( fnDef->name() == QLatin1String( "geom_from_wkt" ) ) { const QList<QgsExpressionNode *> &args = fnNode->args()->list(); if ( args[0]->nodeType() == QgsExpressionNode::ntLiteral ) { QString wkt = static_cast<const QgsExpressionNodeLiteral *>( args[0] )->value().toString(); return QgsGeometry::fromWkt( wkt ); } } } return QgsGeometry(); } QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExpressionNodeFunction *node, QgsExpression *expression, const QgsExpressionContext *context ) { QgsExpressionFunction *fd = QgsExpression::Functions()[node->fnIndex()]; if ( fd->name() == QLatin1String( "intersects_bbox" ) ) { QList<QgsExpressionNode *> argNodes = node->args()->list(); Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args QgsGeometry geom = geometryFromConstExpr( argNodes[1] ); if ( !geom.isNull() && isGeometryColumn( argNodes[0] ) ) { QgsRectangle rect = geom.boundingBox(); mGMLUsed = true; QDomElement elemBox = ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ? QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, mSrsName, mInvertAxisOrientation ) : QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, mSrsName, mInvertAxisOrientation ); QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) ); QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":BBOX" ); funcElem.appendChild( geomProperty ); funcElem.appendChild( elemBox ); return funcElem; } else { mErrorMessage = QObject::tr( "<BBOX> is currently supported only in form: bbox($geometry, geomFromWKT('…'))" ); return QDomElement(); } } if ( isBinarySpatialOperator( fd->name() ) ) { QList<QgsExpressionNode *> argNodes = node->args()->list(); Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args QgsExpressionNode *otherNode = nullptr; if ( isGeometryColumn( argNodes[0] ) ) otherNode = argNodes[1]; else if ( isGeometryColumn( argNodes[1] ) ) otherNode = argNodes[0]; else { mErrorMessage = QObject::tr( "Unable to translate spatial operator: at least one must refer to geometry." ); return QDomElement(); } QDomElement otherGeomElem; // the other node must be a geometry constructor if ( otherNode->nodeType() != QgsExpressionNode::ntFunction ) { mErrorMessage = QObject::tr( "spatial operator: the other operator must be a geometry constructor function" ); return QDomElement(); } const QgsExpressionNodeFunction *otherFn = static_cast<const QgsExpressionNodeFunction *>( otherNode ); QgsExpressionFunction *otherFnDef = QgsExpression::Functions()[otherFn->fnIndex()]; if ( otherFnDef->name() == QLatin1String( "geom_from_wkt" ) ) { QgsExpressionNode *firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral ) { mErrorMessage = QObject::tr( "geom_from_wkt: argument must be string literal" ); return QDomElement(); } QString wkt = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString(); QgsGeometry geom = QgsGeometry::fromWkt( wkt ); otherGeomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, mSrsName, mInvertAxisOrientation, QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; } else if ( otherFnDef->name() == QLatin1String( "geom_from_gml" ) ) { QgsExpressionNode *firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral ) { mErrorMessage = QObject::tr( "geom_from_gml: argument must be string literal" ); return QDomElement(); } QDomDocument geomDoc; QString gml = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString(); if ( !geomDoc.setContent( gml, true ) ) { mErrorMessage = QObject::tr( "geom_from_gml: unable to parse XML" ); return QDomElement(); } QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true ); otherGeomElem = geomNode.toElement(); } else { mErrorMessage = QObject::tr( "spatial operator: unknown geometry constructor function" ); return QDomElement(); } mGMLUsed = true; QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + tagNameForSpatialOperator( fd->name() ) ); QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) ); funcElem.appendChild( geomProperty ); funcElem.appendChild( otherGeomElem ); return funcElem; } if ( fd->isStatic( node, expression, context ) ) { QVariant result = fd->run( node->args(), context, expression, node ); QgsExpressionNodeLiteral literal( result ); return expressionLiteralToOgcFilter( &literal, expression, context ); } if ( fd->params() == 0 ) { mErrorMessage = QObject::tr( "Special columns/constants are not supported." ); return QDomElement(); } // this is somehow wrong - we are just hoping that the other side supports the same functions as we do... QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); funcElem.setAttribute( QStringLiteral( "name" ), fd->name() ); const auto constList = node->args()->list(); for ( QgsExpressionNode *n : constList ) { QDomElement childElem = expressionNodeToOgcFilter( n, expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); funcElem.appendChild( childElem ); } return funcElem; } // QgsOgcUtilsSQLStatementToFilter::QgsOgcUtilsSQLStatementToFilter( QDomDocument &doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, const QList<QgsOgcUtils::LayerProperties> &layerProperties, bool honourAxisOrientation, bool invertAxisOrientation, const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename ) : mDoc( doc ) , mGMLUsed( false ) , mGMLVersion( gmlVersion ) , mFilterVersion( filterVersion ) , mLayerProperties( layerProperties ) , mHonourAxisOrientation( honourAxisOrientation ) , mInvertAxisOrientation( invertAxisOrientation ) , mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" ) , mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" ) , mGeomId( 1 ) , mMapUnprefixedTypenameToPrefixedTypename( mapUnprefixedTypenameToPrefixedTypename ) { } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::Node *node ) { switch ( node->nodeType() ) { case QgsSQLStatement::ntUnaryOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeUnaryOperator *>( node ) ); case QgsSQLStatement::ntBinaryOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeBinaryOperator *>( node ) ); case QgsSQLStatement::ntInOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeInOperator *>( node ) ); case QgsSQLStatement::ntBetweenOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeBetweenOperator *>( node ) ); case QgsSQLStatement::ntFunction: return toOgcFilter( static_cast<const QgsSQLStatement::NodeFunction *>( node ) ); case QgsSQLStatement::ntLiteral: return toOgcFilter( static_cast<const QgsSQLStatement::NodeLiteral *>( node ) ); case QgsSQLStatement::ntColumnRef: return toOgcFilter( static_cast<const QgsSQLStatement::NodeColumnRef *>( node ) ); case QgsSQLStatement::ntSelect: return toOgcFilter( static_cast<const QgsSQLStatement::NodeSelect *>( node ) ); default: mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() ); return QDomElement(); } } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeUnaryOperator *node ) { QDomElement operandElem = toOgcFilter( node->operand() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement uoElem; switch ( node->op() ) { case QgsSQLStatement::uoMinus: uoElem = mDoc.createElement( mFilterPrefix + ":Literal" ); if ( node->operand()->nodeType() == QgsSQLStatement::ntLiteral ) { // operand expression already created a Literal node: // take the literal value, prepend - and remove old literal node uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) ); mDoc.removeChild( operandElem ); } else { mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" ); return QDomElement(); } break; case QgsSQLStatement::uoNot: uoElem = mDoc.createElement( mFilterPrefix + ":Not" ); uoElem.appendChild( operandElem ); break; default: mErrorMessage = QObject::tr( "Unary operator %1 not implemented yet" ).arg( QgsSQLStatement::UNARY_OPERATOR_TEXT[node->op()] ); return QDomElement(); } return uoElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBinaryOperator *node ) { QDomElement leftElem = toOgcFilter( node->opLeft() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QgsSQLStatement::BinaryOperator op = node->op(); // before right operator is parsed: to allow NULL handling if ( op == QgsSQLStatement::boIs || op == QgsSQLStatement::boIsNot ) { if ( node->opRight()->nodeType() == QgsSQLStatement::ntLiteral ) { const QgsSQLStatement::NodeLiteral *rightLit = static_cast<const QgsSQLStatement::NodeLiteral *>( node->opRight() ); if ( rightLit->value().isNull() ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" ); elem.appendChild( leftElem ); if ( op == QgsSQLStatement::boIsNot ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } // continue with equal / not equal operator once the null case is handled op = ( op == QgsSQLStatement::boIs ? QgsSQLStatement::boEQ : QgsSQLStatement::boNE ); } } QDomElement rightElem = toOgcFilter( node->opRight() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QString opText; if ( op == QgsSQLStatement::boOr ) opText = QStringLiteral( "Or" ); else if ( op == QgsSQLStatement::boAnd ) opText = QStringLiteral( "And" ); else if ( op == QgsSQLStatement::boEQ ) opText = QStringLiteral( "PropertyIsEqualTo" ); else if ( op == QgsSQLStatement::boNE ) opText = QStringLiteral( "PropertyIsNotEqualTo" ); else if ( op == QgsSQLStatement::boLE ) opText = QStringLiteral( "PropertyIsLessThanOrEqualTo" ); else if ( op == QgsSQLStatement::boGE ) opText = QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ); else if ( op == QgsSQLStatement::boLT ) opText = QStringLiteral( "PropertyIsLessThan" ); else if ( op == QgsSQLStatement::boGT ) opText = QStringLiteral( "PropertyIsGreaterThan" ); else if ( op == QgsSQLStatement::boLike ) opText = QStringLiteral( "PropertyIsLike" ); else if ( op == QgsSQLStatement::boILike ) opText = QStringLiteral( "PropertyIsLike" ); if ( opText.isEmpty() ) { // not implemented binary operators mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( QgsSQLStatement::BINARY_OPERATOR_TEXT[op] ); return QDomElement(); } QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText ); if ( op == QgsSQLStatement::boLike || op == QgsSQLStatement::boILike ) { if ( op == QgsSQLStatement::boILike ) boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to <ogc:PropertyIsLike> boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); boElem.appendChild( rightElem ); return boElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeLiteral *node ) { QString value; switch ( node->value().type() ) { case QVariant::Int: value = QString::number( node->value().toInt() ); break; case QVariant::LongLong: value = QString::number( node->value().toLongLong() ); break; case QVariant::Double: value = qgsDoubleToString( node->value().toDouble() ); break; case QVariant::String: value = node->value().toString(); break; default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() ); return QDomElement(); } QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" ); litElem.appendChild( mDoc.createTextNode( value ) ); return litElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeColumnRef *node ) { QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); if ( node->tableName().isEmpty() || mLayerProperties.size() == 1 ) propElem.appendChild( mDoc.createTextNode( node->name() ) ); else { QString tableName( mMapTableAliasToNames[node->tableName()] ); if ( mMapUnprefixedTypenameToPrefixedTypename.contains( tableName ) ) tableName = mMapUnprefixedTypenameToPrefixedTypename[tableName]; propElem.appendChild( mDoc.createTextNode( tableName + "/" + node->name() ) ); } return propElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeInOperator *node ) { if ( node->list()->list().size() == 1 ) return toOgcFilter( node->list()->list()[0] ); QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" ); QDomElement leftNode = toOgcFilter( node->node() ); const auto constList = node->list()->list(); for ( QgsSQLStatement::Node *n : constList ) { QDomElement listNode = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); eqElem.appendChild( leftNode.cloneNode() ); eqElem.appendChild( listNode ); orElem.appendChild( eqElem ); } if ( node->isNotIn() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( orElem ); return notElem; } return orElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBetweenOperator *node ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsBetween" ); elem.appendChild( toOgcFilter( node->node() ) ); QDomElement lowerBoundary = mDoc.createElement( mFilterPrefix + ":LowerBoundary" ); lowerBoundary.appendChild( toOgcFilter( node->minVal() ) ); elem.appendChild( lowerBoundary ); QDomElement upperBoundary = mDoc.createElement( mFilterPrefix + ":UpperBoundary" ); upperBoundary.appendChild( toOgcFilter( node->maxVal() ) ); elem.appendChild( upperBoundary ); if ( node->isNotBetween() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } static QString mapBinarySpatialToOgc( const QString &name ) { QString nameCompare( name ); if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); QStringList spatialOps; spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); const auto constSpatialOps = spatialOps; for ( QString op : constSpatialOps ) { if ( nameCompare.compare( op, Qt::CaseInsensitive ) == 0 ) return op; } return QString(); } static QString mapTernarySpatialToOgc( const QString &name ) { QString nameCompare( name ); if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); if ( nameCompare.compare( QLatin1String( "DWithin" ), Qt::CaseInsensitive ) == 0 ) return QStringLiteral( "DWithin" ); if ( nameCompare.compare( QLatin1String( "Beyond" ), Qt::CaseInsensitive ) == 0 ) return QStringLiteral( "Beyond" ); return QString(); } QString QgsOgcUtilsSQLStatementToFilter::getGeometryColumnSRSName( const QgsSQLStatement::Node *node ) { if ( node->nodeType() != QgsSQLStatement::ntColumnRef ) return QString(); const QgsSQLStatement::NodeColumnRef *col = static_cast<const QgsSQLStatement::NodeColumnRef *>( node ); if ( !col->tableName().isEmpty() ) { const auto constMLayerProperties = mLayerProperties; for ( QgsOgcUtils::LayerProperties prop : constMLayerProperties ) { if ( prop.mName.compare( mMapTableAliasToNames[col->tableName()], Qt::CaseInsensitive ) == 0 && prop.mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 ) { return prop.mSRSName; } } } if ( !mLayerProperties.empty() && mLayerProperties.at( 0 ).mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 ) { return mLayerProperties.at( 0 ).mSRSName; } return QString(); } bool QgsOgcUtilsSQLStatementToFilter::processSRSName( const QgsSQLStatement::NodeFunction *mainNode, QList<QgsSQLStatement::Node *> args, bool lastArgIsSRSName, QString &srsName, bool &axisInversion ) { srsName = mCurrentSRSName; axisInversion = mInvertAxisOrientation; if ( lastArgIsSRSName ) { QgsSQLStatement::Node *lastArg = args[ args.size() - 1 ]; if ( lastArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Last argument must be string or integer literal" ).arg( mainNode->name() ); return false; } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( lastArg ); if ( lit->value().type() == QVariant::Int ) { if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) { srsName = "EPSG:" + QString::number( lit->value().toInt() ); } else { srsName = "urn:ogc:def:crs:EPSG::" + QString::number( lit->value().toInt() ); } } else { srsName = lit->value().toString(); if ( srsName.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ) return true; } } QgsCoordinateReferenceSystem crs; if ( !srsName.isEmpty() ) crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( srsName ); if ( crs.isValid() ) { if ( mHonourAxisOrientation && crs.hasAxisInverted() ) { axisInversion = !axisInversion; } } return true; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeFunction *node ) { // ST_GeometryFromText if ( node->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 1 && args.size() != 2 ) { mErrorMessage = QObject::tr( "Function %1 should have 1 or 2 arguments" ).arg( node->name() ); return QDomElement(); } QgsSQLStatement::Node *firstFnArg = args[0]; if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: First argument must be string literal" ).arg( node->name() ); return QDomElement(); } QString srsName; bool axisInversion; if ( ! processSRSName( node, args, args.size() == 2, srsName, axisInversion ) ) { return QDomElement(); } QString wkt = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString(); QgsGeometry geom = QgsGeometry::fromWkt( wkt ); QDomElement geomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, srsName, axisInversion, QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; if ( geomElem.isNull() ) { mErrorMessage = QObject::tr( "%1: invalid WKT" ).arg( node->name() ); return QDomElement(); } mGMLUsed = true; return geomElem; } // ST_MakeEnvelope if ( node->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 4 && args.size() != 5 ) { mErrorMessage = QObject::tr( "Function %1 should have 4 or 5 arguments" ).arg( node->name() ); return QDomElement(); } QgsRectangle rect; for ( int i = 0; i < 4; i++ ) { QgsSQLStatement::Node *arg = args[i]; if ( arg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 ); return QDomElement(); } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( arg ); double val = 0.0; if ( lit->value().type() == QVariant::Int ) val = lit->value().toInt(); else if ( lit->value().type() == QVariant::LongLong ) val = lit->value().toLongLong(); else if ( lit->value().type() == QVariant::Double ) val = lit->value().toDouble(); else { mErrorMessage = QObject::tr( "%1 Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 ); return QDomElement(); } if ( i == 0 ) rect.setXMinimum( val ); else if ( i == 1 ) rect.setYMinimum( val ); else if ( i == 2 ) rect.setXMaximum( val ); else rect.setYMaximum( val ); } QString srsName; bool axisInversion; if ( ! processSRSName( node, args, args.size() == 5, srsName, axisInversion ) ) { return QDomElement(); } mGMLUsed = true; return ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ? QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, srsName, axisInversion, 15 ) : QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, srsName, axisInversion, 15 ); } // ST_GeomFromGML if ( node->name().compare( QLatin1String( "ST_GeomFromGML" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 1 ) { mErrorMessage = QObject::tr( "Function %1 should have 1 argument" ).arg( node->name() ); return QDomElement(); } QgsSQLStatement::Node *firstFnArg = args[0]; if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Argument must be string literal" ).arg( node->name() ); return QDomElement(); } QDomDocument geomDoc; QString gml = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString(); if ( !geomDoc.setContent( gml, true ) ) { mErrorMessage = QObject::tr( "ST_GeomFromGML: unable to parse XML" ); return QDomElement(); } QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true ); mGMLUsed = true; return geomNode.toElement(); } // Binary geometry operators QString ogcName( mapBinarySpatialToOgc( node->name() ) ); if ( !ogcName.isEmpty() ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 2 ) { mErrorMessage = QObject::tr( "Function %1 should have 2 arguments" ).arg( node->name() ); return QDomElement(); } for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && ( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] ); break; } } //if( ogcName == "Intersects" && mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) // ogcName = "Intersect"; QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + ogcName ); const auto constArgs = args; for ( QgsSQLStatement::Node *n : constArgs ) { QDomElement childElem = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) { mCurrentSRSName.clear(); return QDomElement(); } funcElem.appendChild( childElem ); } mCurrentSRSName.clear(); return funcElem; } ogcName = mapTernarySpatialToOgc( node->name() ); if ( !ogcName.isEmpty() ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 3 ) { mErrorMessage = QObject::tr( "Function %1 should have 3 arguments" ).arg( node->name() ); return QDomElement(); } for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && ( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] ); break; } } QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + node->name().mid( 3 ) ); for ( int i = 0; i < 2; i++ ) { QDomElement childElem = toOgcFilter( args[i] ); if ( !mErrorMessage.isEmpty() ) { mCurrentSRSName.clear(); return QDomElement(); } funcElem.appendChild( childElem ); } mCurrentSRSName.clear(); QgsSQLStatement::Node *distanceNode = args[2]; if ( distanceNode->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() ); return QDomElement(); } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( distanceNode ); if ( lit->value().isNull() ) { mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() ); return QDomElement(); } QString distance; QString unit( QStringLiteral( "m" ) ); switch ( lit->value().type() ) { case QVariant::Int: distance = QString::number( lit->value().toInt() ); break; case QVariant::LongLong: distance = QString::number( lit->value().toLongLong() ); break; case QVariant::Double: distance = qgsDoubleToString( lit->value().toDouble() ); break; case QVariant::String: { distance = lit->value().toString(); for ( int i = 0; i < distance.size(); i++ ) { if ( !( ( distance[i] >= '0' && distance[i] <= '9' ) || distance[i] == '-' || distance[i] == '.' || distance[i] == 'e' || distance[i] == 'E' ) ) { unit = distance.mid( i ).trimmed(); distance = distance.mid( 0, i ); break; } } break; } default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( lit->value().type() ); return QDomElement(); } QDomElement distanceElem = mDoc.createElement( mFilterPrefix + ":Distance" ); if ( mFilterVersion == QgsOgcUtils::FILTER_FES_2_0 ) distanceElem.setAttribute( QStringLiteral( "uom" ), unit ); else distanceElem.setAttribute( QStringLiteral( "unit" ), unit ); distanceElem.appendChild( mDoc.createTextNode( distance ) ); funcElem.appendChild( distanceElem ); return funcElem; } // Other function QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); funcElem.setAttribute( QStringLiteral( "name" ), node->name() ); const auto constList = node->args()->list(); for ( QgsSQLStatement::Node *n : constList ) { QDomElement childElem = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); funcElem.appendChild( childElem ); } return funcElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeJoin *node, const QString &leftTable ) { QgsSQLStatement::Node *onExpr = node->onExpr(); if ( onExpr ) { return toOgcFilter( onExpr ); } QList<QDomElement> listElem; const auto constUsingColumns = node->usingColumns(); for ( const QString &columnName : constUsingColumns ) { QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); QDomElement propElem1 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem1.appendChild( mDoc.createTextNode( leftTable + "/" + columnName ) ); eqElem.appendChild( propElem1 ); QDomElement propElem2 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem2.appendChild( mDoc.createTextNode( node->tableDef()->name() + "/" + columnName ) ); eqElem.appendChild( propElem2 ); listElem.append( eqElem ); } if ( listElem.size() == 1 ) { return listElem[0]; } else if ( listElem.size() > 1 ) { QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" ); const auto constListElem = listElem; for ( const QDomElement &elem : constListElem ) { andElem.appendChild( elem ); } return andElem; } return QDomElement(); } void QgsOgcUtilsSQLStatementToFilter::visit( const QgsSQLStatement::NodeTableDef *node ) { if ( node->alias().isEmpty() ) { mMapTableAliasToNames[ node->name()] = node->name(); } else { mMapTableAliasToNames[ node->alias()] = node->name(); } } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeSelect *node ) { QList<QDomElement> listElem; if ( mFilterVersion != QgsOgcUtils::FILTER_FES_2_0 && ( node->tables().size() != 1 || !node->joins().empty() ) ) { mErrorMessage = QObject::tr( "Joins are only supported with WFS 2.0" ); return QDomElement(); } // Register all table name aliases const auto constTables = node->tables(); for ( QgsSQLStatement::NodeTableDef *table : constTables ) { visit( table ); } const auto constJoins = node->joins(); for ( QgsSQLStatement::NodeJoin *join : constJoins ) { visit( join->tableDef() ); } // Process JOIN conditions QList< QgsSQLStatement::NodeTableDef *> nodeTables = node->tables(); QString leftTable = nodeTables.at( nodeTables.length() - 1 )->name(); for ( QgsSQLStatement::NodeJoin *join : constJoins ) { QDomElement joinElem = toOgcFilter( join, leftTable ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); listElem.append( joinElem ); leftTable = join->tableDef()->name(); } // Process WHERE conditions if ( node->where() ) { QDomElement whereElem = toOgcFilter( node->where() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); listElem.append( whereElem ); } // Concatenate all conditions if ( listElem.size() == 1 ) { return listElem[0]; } else if ( listElem.size() > 1 ) { QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" ); const auto constListElem = listElem; for ( const QDomElement &elem : constListElem ) { andElem.appendChild( elem ); } return andElem; } return QDomElement(); } QgsOgcUtilsExpressionFromFilter::QgsOgcUtilsExpressionFromFilter( const QgsOgcUtils::FilterVersion version, const QgsVectorLayer *layer ) : mLayer( layer ) { mPropertyName = QStringLiteral( "PropertyName" ); mPrefix = QStringLiteral( "ogc" ); if ( version == QgsOgcUtils::FILTER_FES_2_0 ) { mPropertyName = QStringLiteral( "ValueReference" ); mPrefix = QStringLiteral( "fes" ); } } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeFromOgcFilter( const QDomElement &element ) { if ( element.isNull() ) return nullptr; // check for binary operators if ( isBinaryOperator( element.tagName() ) ) { return nodeBinaryOperatorFromOgcFilter( element ); } // check for spatial operators if ( isSpatialOperator( element.tagName() ) ) { return nodeSpatialOperatorFromOgcFilter( element ); } // check for other OGC operators, convert them to expressions if ( element.tagName() == QLatin1String( "Not" ) ) { return nodeNotFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "PropertyIsNull" ) ) { return nodePropertyIsNullFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "Literal" ) ) { return nodeLiteralFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "Function" ) ) { return nodeFunctionFromOgcFilter( element ); } else if ( element.tagName() == mPropertyName ) { return nodeColumnRefFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "PropertyIsBetween" ) ) { return nodeIsBetweenFromOgcFilter( element ); } mErrorMessage += QObject::tr( "unable to convert '%1' element to a valid expression: it is not supported yet or it has invalid arguments" ).arg( element.tagName() ); return nullptr; } QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodeBinaryOperatorFromOgcFilter( const QDomElement &element ) { if ( element.isNull() ) return nullptr; int op = binaryOperatorFromTagName( element.tagName() ); if ( op < 0 ) { mErrorMessage = QObject::tr( "'%1' binary operator not supported." ).arg( element.tagName() ); return nullptr; } if ( op == QgsExpressionNodeBinaryOperator::boLike && element.hasAttribute( QStringLiteral( "matchCase" ) ) && element.attribute( QStringLiteral( "matchCase" ) ) == QLatin1String( "false" ) ) { op = QgsExpressionNodeBinaryOperator::boILike; } QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> expr( nodeFromOgcFilter( operandElem ) ); if ( !expr ) { mErrorMessage = QObject::tr( "invalid left operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } std::unique_ptr<QgsExpressionNode> leftOp( expr->clone() ); for ( operandElem = operandElem.nextSiblingElement(); !operandElem.isNull(); operandElem = operandElem.nextSiblingElement() ) { std::unique_ptr<QgsExpressionNode> opRight( nodeFromOgcFilter( operandElem ) ); if ( !opRight ) { mErrorMessage = QObject::tr( "invalid right operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike ) { QString wildCard; if ( element.hasAttribute( QStringLiteral( "wildCard" ) ) ) { wildCard = element.attribute( QStringLiteral( "wildCard" ) ); } QString singleChar; if ( element.hasAttribute( QStringLiteral( "singleChar" ) ) ) { singleChar = element.attribute( QStringLiteral( "singleChar" ) ); } QString escape = QStringLiteral( "\\" ); if ( element.hasAttribute( QStringLiteral( "escape" ) ) ) { escape = element.attribute( QStringLiteral( "escape" ) ); } if ( element.hasAttribute( QStringLiteral( "escapeChar" ) ) ) { escape = element.attribute( QStringLiteral( "escapeChar" ) ); } // replace QString oprValue = static_cast<const QgsExpressionNodeLiteral *>( opRight.get() )->value().toString(); if ( !wildCard.isEmpty() && wildCard != QLatin1String( "%" ) ) { oprValue.replace( '%', QLatin1String( "\\%" ) ); if ( oprValue.startsWith( wildCard ) ) { oprValue.replace( 0, 1, QStringLiteral( "%" ) ); } QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( wildCard ) + ")" ); int pos = 0; while ( ( pos = rx.indexIn( oprValue, pos ) ) != -1 ) { oprValue.replace( pos + 1, 1, QStringLiteral( "%" ) ); pos += 1; } oprValue.replace( escape + wildCard, wildCard ); } if ( !singleChar.isEmpty() && singleChar != QLatin1String( "_" ) ) { oprValue.replace( '_', QLatin1String( "\\_" ) ); if ( oprValue.startsWith( singleChar ) ) { oprValue.replace( 0, 1, QStringLiteral( "_" ) ); } QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( singleChar ) + ")" ); int pos = 0; while ( ( pos = rx.indexIn( oprValue, pos ) ) != -1 ) { oprValue.replace( pos + 1, 1, QStringLiteral( "_" ) ); pos += 1; } oprValue.replace( escape + singleChar, singleChar ); } if ( !escape.isEmpty() && escape != QLatin1String( "\\" ) ) { oprValue.replace( escape + escape, escape ); } opRight.reset( new QgsExpressionNodeLiteral( oprValue ) ); } expr.reset( new QgsExpressionNodeBinaryOperator( static_cast< QgsExpressionNodeBinaryOperator::BinaryOperator >( op ), expr.release(), opRight.release() ) ); } if ( expr == leftOp ) { mErrorMessage = QObject::tr( "only one operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } return dynamic_cast< QgsExpressionNodeBinaryOperator * >( expr.release() ); } QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeSpatialOperatorFromOgcFilter( const QDomElement &element ) { // we are exploiting the fact that our function names are the same as the XML tag names const int opIdx = QgsExpression::functionIndex( element.tagName().toLower() ); std::unique_ptr<QgsExpressionNode::NodeList> gml2Args( new QgsExpressionNode::NodeList() ); QDomElement childElem = element.firstChildElement(); QString gml2Str; while ( !childElem.isNull() && gml2Str.isEmpty() ) { if ( childElem.tagName() != mPropertyName ) { QTextStream gml2Stream( &gml2Str ); childElem.save( gml2Stream, 0 ); } childElem = childElem.nextSiblingElement(); } if ( !gml2Str.isEmpty() ) { gml2Args->append( new QgsExpressionNodeLiteral( QVariant( gml2Str.remove( '\n' ) ) ) ); } else { mErrorMessage = QObject::tr( "No OGC Geometry found" ); return nullptr; } std::unique_ptr<QgsExpressionNode::NodeList> opArgs( new QgsExpressionNode::NodeList() ); opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "$geometry" ) ), new QgsExpressionNode::NodeList() ) ); opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "geomFromGML" ) ), gml2Args.release() ) ); return new QgsExpressionNodeFunction( opIdx, opArgs.release() ); } QgsExpressionNodeColumnRef *QgsOgcUtilsExpressionFromFilter::nodeColumnRefFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != mPropertyName ) { mErrorMessage = QObject::tr( "%1:PropertyName expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } return new QgsExpressionNodeColumnRef( element.firstChild().nodeValue() ); } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeLiteralFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != QLatin1String( "Literal" ) ) { mErrorMessage = QObject::tr( "%1:Literal expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } std::unique_ptr<QgsExpressionNode> root; // the literal content can have more children (e.g. CDATA section, text, ...) QDomNode childNode = element.firstChild(); while ( !childNode.isNull() ) { std::unique_ptr<QgsExpressionNode> operand; if ( childNode.nodeType() == QDomNode::ElementNode ) { // found a element node (e.g. PropertyName), convert it const QDomElement operandElem = childNode.toElement(); operand.reset( nodeFromOgcFilter( operandElem ) ); if ( !operand ) { mErrorMessage = QObject::tr( "'%1' is an invalid or not supported content for %2:Literal" ).arg( operandElem.tagName(), mPrefix ); return nullptr; } } else { // probably a text/CDATA node QVariant value = childNode.nodeValue(); bool converted = false; // try to convert the node content to corresponding field type if possible if ( mLayer ) { QDomElement propertyNameElement = element.previousSiblingElement( mPropertyName ); if ( propertyNameElement.isNull() || propertyNameElement.tagName() != mPropertyName ) { propertyNameElement = element.nextSiblingElement( mPropertyName ); } if ( !propertyNameElement.isNull() || propertyNameElement.tagName() == mPropertyName ) { const int fieldIndex = mLayer->fields().indexOf( propertyNameElement.firstChild().nodeValue() ); if ( fieldIndex != -1 ) { QgsField field = mLayer->fields().field( propertyNameElement.firstChild().nodeValue() ); field.convertCompatible( value ); converted = true; } } } if ( !converted ) { // try to convert the node content to number if possible, // otherwise let's use it as string bool ok; const double d = value.toDouble( &ok ); if ( ok ) value = d; } operand.reset( new QgsExpressionNodeLiteral( value ) ); if ( !operand ) continue; } // use the concat operator to merge the ogc:Literal children if ( !root ) { root = std::move( operand ); } else { root.reset( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, root.release(), operand.release() ) ); } childNode = childNode.nextSibling(); } if ( root ) return root.release(); return nullptr; } QgsExpressionNodeUnaryOperator *QgsOgcUtilsExpressionFromFilter::nodeNotFromOgcFilter( const QDomElement &element ) { if ( element.tagName() != QLatin1String( "Not" ) ) return nullptr; const QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> operand( nodeFromOgcFilter( operandElem ) ); if ( !operand ) { mErrorMessage = QObject::tr( "invalid operand for '%1' unary operator" ).arg( element.tagName() ); return nullptr; } return new QgsExpressionNodeUnaryOperator( QgsExpressionNodeUnaryOperator::uoNot, operand.release() ); } QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodePropertyIsNullFromOgcFilter( const QDomElement &element ) { // convert ogc:PropertyIsNull to IS operator with NULL right operand if ( element.tagName() != QLatin1String( "PropertyIsNull" ) ) { return nullptr; } const QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> opLeft( nodeFromOgcFilter( operandElem ) ); if ( !opLeft ) return nullptr; std::unique_ptr<QgsExpressionNode> opRight( new QgsExpressionNodeLiteral( QVariant() ) ); return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boIs, opLeft.release(), opRight.release() ); } QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeFunctionFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != QLatin1String( "Function" ) ) { mErrorMessage = QObject::tr( "%1:Function expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } for ( int i = 0; i < QgsExpression::Functions().size(); i++ ) { const QgsExpressionFunction *funcDef = QgsExpression::Functions()[i]; if ( element.attribute( QStringLiteral( "name" ) ) != funcDef->name() ) continue; std::unique_ptr<QgsExpressionNode::NodeList> args( new QgsExpressionNode::NodeList() ); QDomElement operandElem = element.firstChildElement(); while ( !operandElem.isNull() ) { std::unique_ptr<QgsExpressionNode> op( nodeFromOgcFilter( operandElem ) ); if ( !op ) { return nullptr; } args->append( op.release() ); operandElem = operandElem.nextSiblingElement(); } return new QgsExpressionNodeFunction( i, args.release() ); } return nullptr; } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeIsBetweenFromOgcFilter( const QDomElement &element ) { // <ogc:PropertyIsBetween> encode a Range check std::unique_ptr<QgsExpressionNode> operand; std::unique_ptr<QgsExpressionNode> lowerBound; std::unique_ptr<QgsExpressionNode> upperBound; QDomElement operandElem = element.firstChildElement(); while ( !operandElem.isNull() ) { if ( operandElem.tagName() == QLatin1String( "LowerBoundary" ) ) { QDomElement lowerBoundElem = operandElem.firstChildElement(); lowerBound.reset( nodeFromOgcFilter( lowerBoundElem ) ); } else if ( operandElem.tagName() == QLatin1String( "UpperBoundary" ) ) { QDomElement upperBoundElem = operandElem.firstChildElement(); upperBound.reset( nodeFromOgcFilter( upperBoundElem ) ); } else { // <ogc:expression> operand.reset( nodeFromOgcFilter( operandElem ) ); } if ( operand && lowerBound && upperBound ) break; operandElem = operandElem.nextSiblingElement(); } if ( !operand || !lowerBound || !upperBound ) { mErrorMessage = QObject::tr( "missing some required sub-elements in %1:PropertyIsBetween" ).arg( mPrefix ); return nullptr; } std::unique_ptr<QgsExpressionNode> leOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boLE, operand->clone(), upperBound.release() ) ); std::unique_ptr<QgsExpressionNode> geOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boGE, operand.release(), lowerBound.release() ) ); return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boAnd, geOperator.release(), leOperator.release() ); } QString QgsOgcUtilsExpressionFromFilter::errorMessage() const { return mErrorMessage; }
tudorbarascu/QGIS
src/core/qgsogcutils.cpp
C++
gpl-2.0
122,763
{# This file was generated with the ext-templateevents:generate command. #} {%- if marttiphpbb_templateevents.enable -%} <a class="templateevents" title="3.1.0-a1&#10;navbar_header.html" href="https://github.com/phpbb/phpbb/tree/prep-release-3.2.2/phpBB/styles/prosilver/template/navbar_header.html#L86">overall_header_navigation_append</a> {%- endif -%}
marttiphpbb/phpbb-ext-templateevents
styles/all/template/event/overall_header_navigation_append.html
HTML
gpl-2.0
355
<?php /** *------------------------------------------------------------------------------ * @package T3 Framework for Joomla! *------------------------------------------------------------------------------ * @copyright Copyright (C) 2004-2013 JoomlArt.com. All Rights Reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @authors JoomlArt, JoomlaBamboo, (contribute to this project at github * & Google group to become co-author) * @Google group: https://groups.google.com/forum/#!forum/t3fw * @Link: http://t3-framework.org *------------------------------------------------------------------------------ */ // No direct access defined('_JEXEC') or die(); /** * T3Action class * * @package T3 */ class T3Action { public static function run ($action) { if (method_exists('T3Action', $action)) { $option = preg_replace('/[^A-Z0-9_\.-]/i', '', JFactory::getApplication()->input->getCmd('view')); if(!defined('JPATH_COMPONENT')){ define('JPATH_COMPONENT', JPATH_BASE . '/components/' . $option); } if(!defined('JPATH_COMPONENT_SITE')){ define('JPATH_COMPONENT_SITE', JPATH_SITE . '/components/' . $option); } if(!defined('JPATH_COMPONENT_ADMINISTRATOR')){ define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR . '/components/' . $option); } T3Action::$action(); } exit; } public static function lessc () { $path = JFactory::getApplication()->input->getString ('s'); T3::import ('core/less'); $t3less = new T3Less; $css = $t3less->getCss($path); header("Content-Type: text/css"); header("Content-length: ".strlen($css)); echo $css; } public static function lesscall(){ T3::import ('core/less'); $result = array(); try{ T3Less::compileAll(); $result['successful'] = JText::_('T3_MSG_COMPILE_SUCCESS'); }catch(Exception $e){ $result['error'] = JText::sprintf('T3_MSG_COMPILE_FAILURE', $e->getMessage()); } echo json_encode($result); } public static function theme(){ JFactory::getLanguage()->load('tpl_' . T3_TEMPLATE, JPATH_SITE); if(!defined('T3')) { die(json_encode(array( 'error' => JText::_('T3_MSG_PLUGIN_NOT_READY') ))); } $user = JFactory::getUser(); $action = JFactory::getApplication()->input->getCmd('t3task', ''); if ($action != 'thememagic' && !$user->authorise('core.manage', 'com_templates')) { die(json_encode(array( 'error' => JText::_('T3_MSG_NO_PERMISSION') ))); } if(empty($action)){ die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } T3::import('admin/theme'); if(method_exists('T3AdminTheme', $action)){ T3AdminTheme::$action(T3_TEMPLATE_PATH); } else { die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } } public static function layout(){ self::cloneParam('t3layout'); if(!defined('T3')) { die(json_encode(array( 'error' => JText::_('T3_MSG_PLUGIN_NOT_READY') ))); } $action = JFactory::getApplication()->input->get('t3task', ''); if(empty($action)){ die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } if($action != 'display'){ $user = JFactory::getUser(); if (!$user->authorise('core.manage', 'com_templates')) { die(json_encode(array( 'error' => JText::_('T3_MSG_NO_PERMISSION') ))); } } T3::import('admin/layout'); if(method_exists('T3AdminLayout', $action)){ T3AdminLayout::$action(T3_TEMPLATE_PATH); } else { die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } } public static function megamenu() { self::cloneParam('t3menu'); if(!defined('T3')) { die(json_encode(array( 'error' => JText::_('T3_MSG_PLUGIN_NOT_READY') ))); } $action = JFactory::getApplication()->input->get('t3task', ''); if(empty($action)){ die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } if($action != 'display'){ $user = JFactory::getUser(); if (!$user->authorise('core.manage', 'com_templates')) { die(json_encode(array( 'error' => JText::_('T3_MSG_NO_PERMISSION') ))); } } T3::import('admin/megamenu'); if(method_exists('T3AdminMegamenu', $action)){ T3AdminMegamenu::$action(); exit; } else { die(json_encode(array( 'error' => JText::_('T3_MSG_UNKNOW_ACTION') ))); } } public static function module () { $input = JFactory::getApplication()->input; $id = $input->getInt ('mid'); $module = null; if ($id) { // load module $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params') ->from('#__modules AS m') ->where('m.id = '.$id) ->where('m.published = 1'); $db->setQuery($query); $module = $db->loadObject (); } if (!empty ($module)) { $style = $input->getCmd ('style', 'T3Xhtml'); $buffer = JModuleHelper::renderModule($module, array('style'=>$style)); // replace relative images url $base = JURI::base(true).'/'; $protocols = '[a-zA-Z0-9]+:'; //To check for all unknown protocals (a protocol must contain at least one alpahnumeric fillowed by : $regex = '#(src)="(?!/|' . $protocols . '|\#|\')([^"]*)"#m'; $buffer = preg_replace($regex, "$1=\"$base\$2\"", $buffer); } //remove invisibile content, there are more ... but ... $buffer = preg_replace(array( '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu'), array('', ''), $buffer); echo $buffer; } //translate param name to new name, from jvalue => to desired param name public static function cloneParam($param = '', $from = 'jvalue'){ $input = JFactory::getApplication()->input; if(!empty($param) && $input->getWord($param, '') == ''){ $input->set($param, $input->getCmd($from)); } } }
Sophist-UK/Sophist_t3framework
source/plg_system_t3/includes/core/action.php
PHP
gpl-2.0
5,926
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef _INC_NLDEF #define _INC_NLDEF typedef enum _NL_ADDRESS_TYPE { NlatUnspecified, NlatUnicast, NlatAnycast, NlatMulticast, NlatBroadcast, NlatInvalid } NL_ADDRESS_TYPE, *PNL_ADDRESS_TYPE; typedef enum _NL_DAD_STATE { NldsInvalid = 0, NldsTentative, NldsDuplicate, NldsDeprecated, NldsPreferred, IpDadStateInvalid = 0, IpDadStateTentative, IpDadStateDuplicate, IpDadStateDeprecated, IpDadStatePreferred } NL_DAD_STATE; typedef enum _NL_LINK_LOCAL_ADDRESS_BEHAVIOR { LinkLocalAlwaysOff = 0, LinkLocalDelayed, LinkLocalAlwaysOn, LinkLocalUnchanged = -1 } NL_LINK_LOCAL_ADDRESS_BEHAVIOR; typedef enum _NL_NEIGHBOR_STATE { NlnsUnreachable, NlnsIncomplete, NlnsProbe, NlnsDelay, NlnsStale, NlnsReachable, NlnsPermanent, NlnsMaximum } NL_NEIGHBOR_STATE, *PNL_NEIGHBOR_STATE; typedef enum _tag_NL_PREFIX_ORIGIN { IpPrefixOriginOther = 0, IpPrefixOriginManual, IpPrefixOriginWellKnown, IpPrefixOriginDhcp, IpPrefixOriginRouterAdvertisement, IpPrefixOriginUnchanged = 1 << 4 } NL_PREFIX_ORIGIN; typedef enum _NL_ROUTE_ORIGIN { NlroManual, NlroWellKnown, NlroDHCP, NlroRouterAdvertisement, Nlro6to4 } NL_ROUTE_ORIGIN, *PNL_ROUTE_ORIGIN; typedef enum _NL_ROUTE_PROTOCOL { RouteProtocolOther = 1, RouteProtocolLocal, RouteProtocolNetMgmt, RouteProtocolIcmp, RouteProtocolEgp, RouteProtocolGgp, RouteProtocolHello, RouteProtocolRip, RouteProtocolIsIs, RouteProtocolEsIs, RouteProtocolCisco, RouteProtocolBbn, RouteProtocolOspf, RouteProtocolBgp, MIB_IPPROTO_OTHER = 1, PROTO_IP_OTHER = 1, MIB_IPPROTO_LOCAL = 2, PROTO_IP_LOCAL = 2, MIB_IPPROTO_NETMGMT = 3, PROTO_IP_NETMGMT = 3, MIB_IPPROTO_ICMP = 4, PROTO_IP_ICMP = 4, MIB_IPPROTO_EGP = 5, PROTO_IP_EGP = 5, MIB_IPPROTO_GGP = 6, PROTO_IP_GGP = 6, MIB_IPPROTO_HELLO = 7, PROTO_IP_HELLO = 7, MIB_IPPROTO_RIP = 8, PROTO_IP_RIP = 8, MIB_IPPROTO_IS_IS = 9, PROTO_IP_IS_IS = 9, MIB_IPPROTO_ES_IS = 10, PROTO_IP_ES_IS = 10, MIB_IPPROTO_CISCO = 11, PROTO_IP_CISCO = 11, MIB_IPPROTO_BBN = 12, PROTO_IP_BBN = 12, MIB_IPPROTO_OSPF = 13, PROTO_IP_OSPF = 13, MIB_IPPROTO_BGP = 14, PROTO_IP_BGP = 14, MIB_IPPROTO_NT_AUTOSTATIC = 10002, PROTO_IP_NT_AUTOSTATIC = 10002, MIB_IPPROTO_NT_STATIC = 10006, PROTO_IP_NT_STATIC = 10006, MIB_IPPROTO_NT_STATIC_NON_DOD = 10007, PROTO_IP_NT_STATIC_NON_DOD = 10007 } NL_ROUTE_PROTOCOL, *PNL_ROUTE_PROTOCOL; typedef enum _NL_ROUTER_DISCOVERY_BEHAVIOR { RouterDiscoveryDisabled = 0, RouterDiscoveryEnabled, RouterDiscoveryDhcp, RouterDiscoveryUnchanged = -1 } NL_ROUTER_DISCOVERY_BEHAVIOR; typedef enum _tag_NL_SUFFIX_ORIGIN { NlsoOther = 0, NlsoManual, NlsoWellKnown, NlsoDhcp, NlsoLinkLayerAddress, NlsoRandom, IpSuffixOriginOther = 0, IpSuffixOriginManual, IpSuffixOriginWellKnown, IpSuffixOriginDhcp, IpSuffixOriginLinkLayerAddress, IpSuffixOriginRandom, IpSuffixOriginUnchanged = 1 << 4 } NL_SUFFIX_ORIGIN; typedef struct _NL_INTERFACE_OFFLOAD_ROD { BOOLEAN NlChecksumSupported :1; BOOLEAN NlOptionsSupported :1; BOOLEAN TlDatagramChecksumSupported :1; BOOLEAN TlStreamChecksumSupported :1; BOOLEAN TlStreamOptionsSupported :1; BOOLEAN FastPathCompatible : 1; BOOLEAN TlLargeSendOffloadSupported :1; BOOLEAN TlGiantSendOffloadSupported :1; } NL_INTERFACE_OFFLOAD_ROD, *PNL_INTERFACE_OFFLOAD_ROD; #endif /*_INC_NLDEF*/
mishin/dwimperl-windows
strawberry-perl-5.20.0.1-32bit-portable/c/i686-w64-mingw32/include/nldef.h
C
gpl-2.0
4,189
/* Copyright (C) 2003 - 2018 by David White <[email protected]> Part of the Battle for Wesnoth Project https://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Fighting. */ #include "actions/attack.hpp" #include "actions/advancement.hpp" #include "actions/vision.hpp" #include "ai/lua/aspect_advancements.hpp" #include "formula/callable_objects.hpp" #include "formula/formula.hpp" #include "game_config.hpp" #include "game_data.hpp" #include "game_events/pump.hpp" #include "gettext.hpp" #include "log.hpp" #include "map/map.hpp" #include "mouse_handler_base.hpp" #include "play_controller.hpp" #include "preferences/game.hpp" #include "random.hpp" #include "replay.hpp" #include "resources.hpp" #include "statistics.hpp" #include "synced_checkup.hpp" #include "synced_user_choice.hpp" #include "team.hpp" #include "tod_manager.hpp" #include "units/abilities.hpp" #include "units/animation_component.hpp" #include "units/helper.hpp" #include "units/filter.hpp" #include "units/map.hpp" #include "units/udisplay.hpp" #include "units/unit.hpp" #include "whiteboard/manager.hpp" #include "wml_exception.hpp" static lg::log_domain log_engine("engine"); #define DBG_NG LOG_STREAM(debug, log_engine) #define LOG_NG LOG_STREAM(info, log_engine) #define WRN_NG LOG_STREAM(err, log_engine) #define ERR_NG LOG_STREAM(err, log_engine) static lg::log_domain log_attack("engine/attack"); #define DBG_AT LOG_STREAM(debug, log_attack) #define LOG_AT LOG_STREAM(info, log_attack) #define WRN_AT LOG_STREAM(err, log_attack) #define ERR_AT LOG_STREAM(err, log_attack) static lg::log_domain log_config("config"); #define LOG_CF LOG_STREAM(info, log_config) // ================================================================================== // BATTLE CONTEXT UNIT STATS // ================================================================================== battle_context_unit_stats::battle_context_unit_stats(const unit& u, const map_location& u_loc, int u_attack_num, bool attacking, const unit& opp, const map_location& opp_loc, const_attack_ptr opp_weapon, const unit_map& units) : weapon(nullptr) , attack_num(u_attack_num) , is_attacker(attacking) , is_poisoned(u.get_state(unit::STATE_POISONED)) , is_slowed(u.get_state(unit::STATE_SLOWED)) , slows(false) , drains(false) , petrifies(false) , plagues(false) , poisons(false) , backstab_pos(false) , swarm(false) , firststrike(false) , disable(false) , experience(u.experience()) , max_experience(u.max_experience()) , level(u.level()) , rounds(1) , hp(0) , max_hp(u.max_hitpoints()) , chance_to_hit(0) , damage(0) , slow_damage(0) , drain_percent(0) , drain_constant(0) , num_blows(0) , swarm_min(0) , swarm_max(0) , plague_type() { // Get the current state of the unit. if(attack_num >= 0) { weapon = u.attacks()[attack_num].shared_from_this(); } if(u.hitpoints() < 0) { LOG_CF << "Unit with " << u.hitpoints() << " hitpoints found, set to 0 for damage calculations\n"; hp = 0; } else if(u.hitpoints() > u.max_hitpoints()) { // If a unit has more hp than its maximum, the engine will fail with an // assertion failure due to accessing the prob_matrix out of bounds. hp = u.max_hitpoints(); } else { hp = u.hitpoints(); } // Exit if no weapon. if(!weapon) { return; } // Get the weapon characteristics as appropriate. auto ctx = weapon->specials_context(&u, &opp, u_loc, opp_loc, attacking, opp_weapon); boost::optional<decltype(ctx)> opp_ctx; if(opp_weapon) { opp_ctx.emplace(opp_weapon->specials_context(&opp, &u, opp_loc, u_loc, !attacking, weapon)); } slows = weapon->bool_ability("slow"); drains = !opp.get_state("undrainable") && weapon->bool_ability("drains"); petrifies = weapon->bool_ability("petrifies"); poisons = !opp.get_state("unpoisonable") && weapon->bool_ability("poison") && !opp.get_state(unit::STATE_POISONED); backstab_pos = is_attacker && backstab_check(u_loc, opp_loc, units, resources::gameboard->teams()); rounds = weapon->get_specials("berserk").highest("value", 1).first; if(weapon->combat_ability("berserk", 1).second) { rounds = weapon->combat_ability("berserk", 1).first; } firststrike = weapon->bool_ability("firststrike"); { const int distance = distance_between(u_loc, opp_loc); const bool out_of_range = distance > weapon->max_range() || distance < weapon->min_range(); disable = weapon->get_special_bool("disable") || out_of_range; } // Handle plague. unit_ability_list plague_specials = weapon->get_specials("plague"); plagues = !opp.get_state("unplagueable") && !plague_specials.empty() && opp.undead_variation() != "null" && !resources::gameboard->map().is_village(opp_loc); if(plagues) { plague_type = (*plague_specials.front().first)["type"].str(); if(plague_type.empty()) { plague_type = u.type().base_id(); } } // Compute chance to hit. signed int cth = opp.defense_modifier(resources::gameboard->map().get_terrain(opp_loc)) + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0); cth = utils::clamp(cth, 0, 100); unit_ability_list cth_specials = weapon->get_specials("chance_to_hit"); unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos); cth = cth_effects.get_composite_value(); cth = utils::clamp(cth, 0, 100); cth = weapon->combat_ability("chance_to_hit", cth, backstab_pos).first; if(opp.get_state("invulnerable")) { cth = 0; } chance_to_hit = utils::clamp(cth, 0, 100); // Compute base damage done with the weapon. int base_damage = weapon->modified_damage(backstab_pos); // Get the damage multiplier applied to the base damage of the weapon. int damage_multiplier = 100; // Time of day bonus. damage_multiplier += combat_modifier( resources::gameboard->units(), resources::gameboard->map(), u_loc, u.alignment(), u.is_fearless()); // Leadership bonus. int leader_bonus = under_leadership(u, u_loc, weapon, opp_weapon); if(leader_bonus != 0) { damage_multiplier += leader_bonus; } // Resistance modifier. damage_multiplier *= opp.damage_from(*weapon, !attacking, opp_loc, opp_weapon); // Compute both the normal and slowed damage. damage = round_damage(base_damage, damage_multiplier, 10000); slow_damage = round_damage(base_damage, damage_multiplier, 20000); if(is_slowed) { damage = slow_damage; } // Compute drain amounts only if draining is possible. if(drains) { if (weapon->get_special_bool("drains")) { unit_ability_list drain_specials = weapon->get_specials("drains"); // Compute the drain percent (with 50% as the base for backward compatibility) unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos); drain_percent = drain_percent_effects.get_composite_value(); } if (weapon->combat_ability("drains", 50, backstab_pos).second) { drain_percent = weapon->combat_ability("drains", 50, backstab_pos).first; } } // Add heal_on_hit (the drain constant) unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit"); unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos); drain_constant += heal_on_hit_effects.get_composite_value(); drains = drain_constant || drain_percent; // Compute the number of blows and handle swarm. weapon->modified_attacks(backstab_pos, swarm_min, swarm_max); swarm = swarm_min != swarm_max; num_blows = calc_blows(hp); } battle_context_unit_stats::battle_context_unit_stats(const unit_type* u_type, const_attack_ptr att_weapon, bool attacking, const unit_type* opp_type, const_attack_ptr opp_weapon, unsigned int opp_terrain_defense, int lawful_bonus) : weapon(att_weapon) , attack_num(-2) // This is and stays invalid. Always use weapon when using this constructor. , is_attacker(attacking) , is_poisoned(false) , is_slowed(false) , slows(false) , drains(false) , petrifies(false) , plagues(false) , poisons(false) , backstab_pos(false) , swarm(false) , firststrike(false) , disable(false) , experience(0) , max_experience(0) , level(0) , rounds(1) , hp(0) , max_hp(0) , chance_to_hit(0) , damage(0) , slow_damage(0) , drain_percent(0) , drain_constant(0) , num_blows(0) , swarm_min(0) , swarm_max(0) , plague_type() { if(!u_type || !opp_type) { return; } // Get the current state of the unit. if(u_type->hitpoints() < 0) { hp = 0; } else { hp = u_type->hitpoints(); } max_experience = u_type->experience_needed(); level = (u_type->level()); max_hp = (u_type->hitpoints()); // Exit if no weapon. if(!weapon) { return; } // Get the weapon characteristics as appropriate. auto ctx = weapon->specials_context(*u_type, map_location::null_location(), attacking); boost::optional<decltype(ctx)> opp_ctx; if(opp_weapon) { opp_ctx.emplace(opp_weapon->specials_context(*opp_type, map_location::null_location(), !attacking)); } slows = weapon->get_special_bool("slow"); drains = !opp_type->musthave_status("undrainable") && weapon->get_special_bool("drains"); petrifies = weapon->get_special_bool("petrifies"); poisons = !opp_type->musthave_status("unpoisonable") && weapon->get_special_bool("poison"); rounds = weapon->get_specials("berserk").highest("value", 1).first; firststrike = weapon->get_special_bool("firststrike"); disable = weapon->get_special_bool("disable"); unit_ability_list plague_specials = weapon->get_specials("plague"); plagues = !opp_type->musthave_status("unplagueable") && !plague_specials.empty() && opp_type->undead_variation() != "null"; if(plagues) { plague_type = (*plague_specials.front().first)["type"].str(); if(plague_type.empty()) { plague_type = u_type->base_id(); } } signed int cth = 100 - opp_terrain_defense + weapon->accuracy() - (opp_weapon ? opp_weapon->parry() : 0); cth = utils::clamp(cth, 0, 100); unit_ability_list cth_specials = weapon->get_specials("chance_to_hit"); unit_abilities::effect cth_effects(cth_specials, cth, backstab_pos); cth = cth_effects.get_composite_value(); chance_to_hit = utils::clamp(cth, 0, 100); int base_damage = weapon->modified_damage(backstab_pos); int damage_multiplier = 100; damage_multiplier += generic_combat_modifier(lawful_bonus, u_type->alignment(), u_type->musthave_status("fearless"), 0); damage_multiplier *= opp_type->resistance_against(weapon->type(), !attacking); damage = round_damage(base_damage, damage_multiplier, 10000); slow_damage = round_damage(base_damage, damage_multiplier, 20000); if(drains) { unit_ability_list drain_specials = weapon->get_specials("drains"); // Compute the drain percent (with 50% as the base for backward compatibility) unit_abilities::effect drain_percent_effects(drain_specials, 50, backstab_pos); drain_percent = drain_percent_effects.get_composite_value(); } // Add heal_on_hit (the drain constant) unit_ability_list heal_on_hit_specials = weapon->get_specials("heal_on_hit"); unit_abilities::effect heal_on_hit_effects(heal_on_hit_specials, 0, backstab_pos); drain_constant += heal_on_hit_effects.get_composite_value(); drains = drain_constant || drain_percent; // Compute the number of blows and handle swarm. weapon->modified_attacks(backstab_pos, swarm_min, swarm_max); swarm = swarm_min != swarm_max; num_blows = calc_blows(hp); } // ================================================================================== // BATTLE CONTEXT // ================================================================================== battle_context::battle_context( const unit& attacker, const map_location& a_loc, int a_wep_index, const unit& defender, const map_location& d_loc, int d_wep_index, const unit_map& units) : attacker_stats_() , defender_stats_() , attacker_combatant_() , defender_combatant_() { size_t a_wep_uindex = static_cast<size_t>(a_wep_index); size_t d_wep_uindex = static_cast<size_t>(d_wep_index); const_attack_ptr a_wep(a_wep_uindex < attacker.attacks().size() ? attacker.attacks()[a_wep_index].shared_from_this() : nullptr); const_attack_ptr d_wep(d_wep_uindex < defender.attacks().size() ? defender.attacks()[d_wep_index].shared_from_this() : nullptr); attacker_stats_.reset(new battle_context_unit_stats(attacker, a_loc, a_wep_index, true , defender, d_loc, d_wep, units)); defender_stats_.reset(new battle_context_unit_stats(defender, d_loc, d_wep_index, false, attacker, a_loc, a_wep, units)); } void battle_context::simulate(const combatant* prev_def) { assert((attacker_combatant_.get() != nullptr) == (defender_combatant_.get() != nullptr)); assert(attacker_stats_); assert(defender_stats_); if(!attacker_combatant_) { attacker_combatant_.reset(new combatant(*attacker_stats_)); defender_combatant_.reset(new combatant(*defender_stats_, prev_def)); attacker_combatant_->fight(*defender_combatant_); } } // more like a factory method than a constructor, always calls one of the other constructors. battle_context::battle_context(const unit_map& units, const map_location& attacker_loc, const map_location& defender_loc, int attacker_weapon, int defender_weapon, double aggression, const combatant* prev_def, const unit* attacker_ptr, const unit* defender_ptr) : attacker_stats_(nullptr) , defender_stats_(nullptr) , attacker_combatant_(nullptr) , defender_combatant_(nullptr) { //TODO: maybe check before dereferencing units.find(attacker_loc),units.find(defender_loc) ? const unit& attacker = attacker_ptr ? *attacker_ptr : *units.find(attacker_loc); const unit& defender = defender_ptr ? *defender_ptr : *units.find(defender_loc); const double harm_weight = 1.0 - aggression; if(attacker_weapon == -1) { *this = choose_attacker_weapon( attacker, defender, units, attacker_loc, defender_loc, harm_weight, prev_def ); } else if(defender_weapon == -1) { *this = choose_defender_weapon( attacker, defender, attacker_weapon, units, attacker_loc, defender_loc, prev_def ); } else { *this = battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, defender_weapon, units); } assert(attacker_stats_); assert(defender_stats_); } battle_context::battle_context(const battle_context_unit_stats& att, const battle_context_unit_stats& def) : attacker_stats_(new battle_context_unit_stats(att)) , defender_stats_(new battle_context_unit_stats(def)) , attacker_combatant_(nullptr) , defender_combatant_(nullptr) { } /** @todo FIXME: better to initialize combatant initially (move into battle_context_unit_stats?), just do fight() when required. */ const combatant& battle_context::get_attacker_combatant(const combatant* prev_def) { // We calculate this lazily, since AI doesn't always need it. simulate(prev_def); return *attacker_combatant_; } const combatant& battle_context::get_defender_combatant(const combatant* prev_def) { // We calculate this lazily, since AI doesn't always need it. simulate(prev_def); return *defender_combatant_; } // Given this harm_weight, are we better than that other context? bool battle_context::better_attack(class battle_context& that, double harm_weight) { return better_combat( get_attacker_combatant(), get_defender_combatant(), that.get_attacker_combatant(), that.get_defender_combatant(), harm_weight ); } // Given this harm_weight, are we better than that other context? bool battle_context::better_defense(class battle_context& that, double harm_weight) { return better_combat( get_defender_combatant(), get_attacker_combatant(), that.get_defender_combatant(), that.get_attacker_combatant(), harm_weight ); } // Does combat A give us a better result than combat B? bool battle_context::better_combat(const combatant& us_a, const combatant& them_a, const combatant& us_b, const combatant& them_b, double harm_weight) { double a, b; // Compare: P(we kill them) - P(they kill us). a = them_a.hp_dist[0] - us_a.hp_dist[0] * harm_weight; b = them_b.hp_dist[0] - us_b.hp_dist[0] * harm_weight; if(a - b < -0.01) { return false; } if(a - b > 0.01) { return true; } // Add poison to calculations double poison_a_us = (us_a.poisoned) * game_config::poison_amount; double poison_a_them = (them_a.poisoned) * game_config::poison_amount; double poison_b_us = (us_b.poisoned) * game_config::poison_amount; double poison_b_them = (them_b.poisoned) * game_config::poison_amount; // Compare: damage to them - damage to us (average_hp replaces -damage) a = (us_a.average_hp() - poison_a_us) * harm_weight - (them_a.average_hp() - poison_a_them); b = (us_b.average_hp() - poison_b_us) * harm_weight - (them_b.average_hp() - poison_b_them); if(a - b < -0.01) { return false; } if(a - b > 0.01) { return true; } // All else equal: go for most damage. return them_a.average_hp() < them_b.average_hp(); } battle_context battle_context::choose_attacker_weapon(const unit& attacker, const unit& defender, const unit_map& units, const map_location& attacker_loc, const map_location& defender_loc, double harm_weight, const combatant* prev_def) { log_scope2(log_attack, "choose_attacker_weapon"); std::vector<battle_context> choices; // What options does attacker have? for(size_t i = 0; i < attacker.attacks().size(); ++i) { const attack_type& att = attacker.attacks()[i]; if(att.attack_weight() <= 0) { continue; } battle_context bc = choose_defender_weapon(attacker, defender, i, units, attacker_loc, defender_loc, prev_def); //choose_defender_weapon will always choose the weapon that disabels the attackers weapon if possible. if(bc.attacker_stats_->disable) { continue; } choices.emplace_back(std::move(bc)); } if(choices.empty()) { return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units); } if(choices.size() == 1) { return std::move(choices[0]); } // Multiple options: simulate them, save best. battle_context* best_choice = nullptr; for(auto& choice : choices) { // If choose_defender_weapon didn't simulate, do so now. choice.simulate(prev_def); if(!best_choice || choice.better_attack(*best_choice, harm_weight)) { best_choice = &choice; } } if(best_choice) { return std::move(*best_choice); } else { return battle_context(attacker, attacker_loc, -1, defender, defender_loc, -1, units); } } /** @todo FIXME: Hand previous defender unit in here. */ battle_context battle_context::choose_defender_weapon(const unit& attacker, const unit& defender, unsigned attacker_weapon, const unit_map& units, const map_location& attacker_loc, const map_location& defender_loc, const combatant* prev_def) { log_scope2(log_attack, "choose_defender_weapon"); VALIDATE(attacker_weapon < attacker.attacks().size(), _("An invalid attacker weapon got selected.")); const attack_type& att = attacker.attacks()[attacker_weapon]; auto no_weapon = [&]() { return battle_context(attacker, attacker_loc, attacker_weapon, defender, defender_loc, -1, units); }; std::vector<battle_context> choices; // What options does defender have? for(size_t i = 0; i < defender.attacks().size(); ++i) { const attack_type& def = defender.attacks()[i]; if(def.range() != att.range() || def.defense_weight() <= 0) { //no need to calculate the battle_context here. continue; } battle_context bc(attacker, attacker_loc, attacker_weapon, defender, defender_loc, i, units); if(bc.defender_stats_->disable) { continue; } if(bc.attacker_stats_->disable) { //the defenders attack disables the attakers attack: always choose this one. return bc; } choices.emplace_back(std::move(bc)); } if(choices.empty()) { return no_weapon(); } if(choices.size() == 1) { //only one usable weapon, don't simulate return std::move(choices[0]); } // Multiple options: // First pass : get the best weight and the minimum simple rating for this weight. // simple rating = number of blows * damage per blows (resistance taken in account) * cth * weight // Eligible attacks for defense should have a simple rating greater or equal to this weight. int min_rating = 0; { double max_weight = 0.0; for(const auto& choice : choices) { const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num]; if(def.defense_weight() >= max_weight) { const battle_context_unit_stats& def_stats = *choice.defender_stats_; max_weight = def.defense_weight(); int rating = static_cast<int>( def_stats.num_blows * def_stats.damage * def_stats.chance_to_hit * def.defense_weight()); if(def.defense_weight() > max_weight || rating < min_rating) { min_rating = rating; } } } } battle_context* best_choice = nullptr; // Multiple options: simulate them, save best. for(auto& choice : choices) { const attack_type& def = defender.attacks()[choice.defender_stats_->attack_num]; choice.simulate(prev_def); int simple_rating = static_cast<int>( choice.defender_stats_->num_blows * choice.defender_stats_->damage * choice.defender_stats_->chance_to_hit * def.defense_weight()); //FIXME: make sure there is no mostake in the better_combat call- if(simple_rating >= min_rating && (!best_choice || choice.better_defense(*best_choice, 1.0))) { best_choice = &choice; } } return best_choice ? std::move(*best_choice) : no_weapon(); } // ================================================================================== // HELPERS // ================================================================================== namespace { void refresh_weapon_index(int& weap_index, const std::string& weap_id, attack_itors attacks) { // No attacks to choose from. if(attacks.empty()) { weap_index = -1; return; } // The currently selected attack fits. if(weap_index >= 0 && weap_index < static_cast<int>(attacks.size()) && attacks[weap_index].id() == weap_id) { return; } // Look up the weapon by id. if(!weap_id.empty()) { for(int i = 0; i < static_cast<int>(attacks.size()); ++i) { if(attacks[i].id() == weap_id) { weap_index = i; return; } } } // Lookup has failed. weap_index = -1; return; } /** Helper class for performing an attack. */ class attack { public: attack(const map_location& attacker, const map_location& defender, int attack_with, int defend_with, bool update_display = true); void perform(); private: class attack_end_exception { }; bool perform_hit(bool, statistics::attack_context&); void fire_event(const std::string& n); void refresh_bc(); /** Structure holding unit info used in the attack action. */ struct unit_info { const map_location loc_; int weapon_; unit_map& units_; std::size_t id_; /**< unit.underlying_id() */ std::string weap_id_; int orig_attacks_; int n_attacks_; /**< Number of attacks left. */ int cth_; int damage_; int xp_; unit_info(const map_location& loc, int weapon, unit_map& units); unit& get_unit(); bool valid(); std::string dump(); }; /** * Used in perform_hit to confirm a replay is in sync. * Check OOS_error_ after this method, true if error detected. */ void check_replay_attack_result(bool&, int, int&, config, unit_info&); void unit_killed( unit_info&, unit_info&, const battle_context_unit_stats*&, const battle_context_unit_stats*&, bool); std::unique_ptr<battle_context> bc_; const battle_context_unit_stats* a_stats_; const battle_context_unit_stats* d_stats_; int abs_n_attack_, abs_n_defend_; // update_att_fog_ is not used, other than making some code simpler. bool update_att_fog_, update_def_fog_, update_minimap_; unit_info a_, d_; unit_map& units_; std::ostringstream errbuf_; bool update_display_; bool OOS_error_; bool use_prng_; std::vector<bool> prng_attacker_; std::vector<bool> prng_defender_; }; attack::unit_info::unit_info(const map_location& loc, int weapon, unit_map& units) : loc_(loc) , weapon_(weapon) , units_(units) , id_() , weap_id_() , orig_attacks_(0) , n_attacks_(0) , cth_(0) , damage_(0) , xp_(0) { unit_map::iterator i = units_.find(loc_); if(!i.valid()) { return; } id_ = i->underlying_id(); } unit& attack::unit_info::get_unit() { unit_map::iterator i = units_.find(loc_); assert(i.valid() && i->underlying_id() == id_); return *i; } bool attack::unit_info::valid() { unit_map::iterator i = units_.find(loc_); return i.valid() && i->underlying_id() == id_; } std::string attack::unit_info::dump() { std::stringstream s; s << get_unit().type_id() << " (" << loc_.wml_x() << ',' << loc_.wml_y() << ')'; return s.str(); } attack::attack(const map_location& attacker, const map_location& defender, int attack_with, int defend_with, bool update_display) : bc_(nullptr) , a_stats_(nullptr) , d_stats_(nullptr) , abs_n_attack_(0) , abs_n_defend_(0) , update_att_fog_(false) , update_def_fog_(false) , update_minimap_(false) , a_(attacker, attack_with, resources::gameboard->units()) , d_(defender, defend_with, resources::gameboard->units()) , units_(resources::gameboard->units()) , errbuf_() , update_display_(update_display) , OOS_error_(false) //new experimental prng mode. , use_prng_(preferences::get("use_prng") == "yes" && randomness::generator->is_networked() == false) { if(use_prng_) { std::cerr << "Using experimental PRNG for combat\n"; } } void attack::fire_event(const std::string& n) { LOG_NG << "attack: firing '" << n << "' event\n"; // prepare the event data for weapon filtering config ev_data; config& a_weapon_cfg = ev_data.add_child("first"); config& d_weapon_cfg = ev_data.add_child("second"); // Need these to ensure weapon filters work correctly boost::optional<attack_type::specials_context_t> a_ctx, d_ctx; if(a_stats_->weapon != nullptr && a_.valid()) { if(d_stats_->weapon != nullptr && d_.valid()) { a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, nullptr, a_.loc_, d_.loc_, true, d_stats_->weapon)); } else { a_ctx.emplace(a_stats_->weapon->specials_context(nullptr, a_.loc_, true)); } a_stats_->weapon->write(a_weapon_cfg); } if(d_stats_->weapon != nullptr && d_.valid()) { if(a_stats_->weapon != nullptr && a_.valid()) { d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, nullptr, d_.loc_, a_.loc_, false, a_stats_->weapon)); } else { d_ctx.emplace(d_stats_->weapon->specials_context(nullptr, d_.loc_, false)); } d_stats_->weapon->write(d_weapon_cfg); } if(a_weapon_cfg["name"].empty()) { a_weapon_cfg["name"] = "none"; } if(d_weapon_cfg["name"].empty()) { d_weapon_cfg["name"] = "none"; } if(n == "attack_end") { // We want to fire attack_end event in any case! Even if one of units was removed by WML. resources::game_events->pump().fire(n, a_.loc_, d_.loc_, ev_data); return; } // damage_inflicted is set in these two events. // TODO: should we set this value from unit_info::damage, or continue using the WML variable? if(n == "attacker_hits" || n == "defender_hits") { ev_data["damage_inflicted"] = resources::gamedata->get_variable("damage_inflicted"); } const int defender_side = d_.get_unit().side(); bool wml_aborted; std::tie(std::ignore, wml_aborted) = resources::game_events->pump().fire(n, game_events::entity_location(a_.loc_, a_.id_), game_events::entity_location(d_.loc_, d_.id_), ev_data); // The event could have killed either the attacker or // defender, so we have to make sure they still exist. refresh_bc(); if(wml_aborted || !a_.valid() || !d_.valid() || !resources::gameboard->get_team(a_.get_unit().side()).is_enemy(d_.get_unit().side()) ) { actions::recalculate_fog(defender_side); if(update_display_) { display::get_singleton()->redraw_minimap(); } fire_event("attack_end"); throw attack_end_exception(); } } void attack::refresh_bc() { // Fix index of weapons. if(a_.valid()) { refresh_weapon_index(a_.weapon_, a_.weap_id_, a_.get_unit().attacks()); } if(d_.valid()) { refresh_weapon_index(d_.weapon_, d_.weap_id_, d_.get_unit().attacks()); } if(!a_.valid() || !d_.valid()) { // Fix pointer to weapons. const_cast<battle_context_unit_stats*>(a_stats_)->weapon = a_.valid() && a_.weapon_ >= 0 ? a_.get_unit().attacks()[a_.weapon_].shared_from_this() : nullptr; const_cast<battle_context_unit_stats*>(d_stats_)->weapon = d_.valid() && d_.weapon_ >= 0 ? d_.get_unit().attacks()[d_.weapon_].shared_from_this() : nullptr; return; } bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_)); a_stats_ = &bc_->get_attacker_stats(); d_stats_ = &bc_->get_defender_stats(); a_.cth_ = a_stats_->chance_to_hit; d_.cth_ = d_stats_->chance_to_hit; a_.damage_ = a_stats_->damage; d_.damage_ = d_stats_->damage; } bool attack::perform_hit(bool attacker_turn, statistics::attack_context& stats) { unit_info& attacker = attacker_turn ? a_ : d_; unit_info& defender = attacker_turn ? d_ : a_; // NOTE: we need to use a reference-to-pointer here so a_stats_ and d_stats_ can be // modified without. Using a pointer directly would render them invalid when that happened. const battle_context_unit_stats*& attacker_stats = attacker_turn ? a_stats_ : d_stats_; const battle_context_unit_stats*& defender_stats = attacker_turn ? d_stats_ : a_stats_; int& abs_n = attacker_turn ? abs_n_attack_ : abs_n_defend_; bool& update_fog = attacker_turn ? update_def_fog_ : update_att_fog_; int ran_num; if(use_prng_) { std::vector<bool>& prng_seq = attacker_turn ? prng_attacker_ : prng_defender_; if(prng_seq.empty()) { const int ntotal = attacker.cth_*attacker.n_attacks_; int num_hits = ntotal/100; const int additional_hit_chance = ntotal%100; if(additional_hit_chance > 0 && randomness::generator->get_random_int(0, 99) < additional_hit_chance) { ++num_hits; } std::vector<int> indexes; for(int i = 0; i != attacker.n_attacks_; ++i) { prng_seq.push_back(false); indexes.push_back(i); } for(int i = 0; i != num_hits; ++i) { int n = randomness::generator->get_random_int(0, static_cast<int>(indexes.size())-1); prng_seq[indexes[n]] = true; indexes.erase(indexes.begin() + n); } } bool does_hit = prng_seq.back(); prng_seq.pop_back(); ran_num = does_hit ? 0 : 99; } else { ran_num = randomness::generator->get_random_int(0, 99); } bool hits = (ran_num < attacker.cth_); int damage = 0; if(hits) { damage = attacker.damage_; resources::gamedata->get_variable("damage_inflicted") = damage; } // Make sure that if we're serializing a game here, // we got the same results as the game did originally. const config local_results {"chance", attacker.cth_, "hits", hits, "damage", damage}; config replay_results; bool equals_replay = checkup_instance->local_checkup(local_results, replay_results); if(!equals_replay) { check_replay_attack_result(hits, ran_num, damage, replay_results, attacker); } // can do no more damage than the defender has hitpoints int damage_done = std::min<int>(defender.get_unit().hitpoints(), attacker.damage_); // expected damage = damage potential * chance to hit (as a percentage) double expected_damage = damage_done * attacker.cth_ * 0.01; if(attacker_turn) { stats.attack_expected_damage(expected_damage, 0); } else { stats.attack_expected_damage(0, expected_damage); } int drains_damage = 0; if(hits && attacker_stats->drains) { drains_damage = damage_done * attacker_stats->drain_percent / 100 + attacker_stats->drain_constant; // don't drain so much that the attacker gets more than his maximum hitpoints drains_damage = std::min<int>(drains_damage, attacker.get_unit().max_hitpoints() - attacker.get_unit().hitpoints()); // if drain is negative, don't allow drain to kill the attacker drains_damage = std::max<int>(drains_damage, 1 - attacker.get_unit().hitpoints()); } if(update_display_) { std::ostringstream float_text; std::vector<std::string> extra_hit_sounds; if(hits) { const unit& defender_unit = defender.get_unit(); if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) { float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^poisoned") : _("poisoned")) << '\n'; extra_hit_sounds.push_back(game_config::sounds::status::poisoned); } if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) { float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^slowed") : _("slowed")) << '\n'; extra_hit_sounds.push_back(game_config::sounds::status::slowed); } if(attacker_stats->petrifies) { float_text << (defender_unit.gender() == unit_race::FEMALE ? _("female^petrified") : _("petrified")) << '\n'; extra_hit_sounds.push_back(game_config::sounds::status::petrified); } } unit_display::unit_attack( game_display::get_singleton(), *resources::gameboard, attacker.loc_, defender.loc_, damage, *attacker_stats->weapon, defender_stats->weapon, abs_n, float_text.str(), drains_damage, "", &extra_hit_sounds ); } bool dies = defender.get_unit().take_hit(damage); LOG_NG << "defender took " << damage << (dies ? " and died\n" : "\n"); if(attacker_turn) { stats.attack_result(hits ? (dies ? statistics::attack_context::KILLS : statistics::attack_context::HITS) : statistics::attack_context::MISSES, attacker.cth_, damage_done, drains_damage ); } else { stats.defend_result(hits ? (dies ? statistics::attack_context::KILLS : statistics::attack_context::HITS) : statistics::attack_context::MISSES, attacker.cth_, damage_done, drains_damage ); } replay_results.clear(); // There was also a attribute cfg["unit_hit"] which was never used so i deleted. equals_replay = checkup_instance->local_checkup(config{"dies", dies}, replay_results); if(!equals_replay) { bool results_dies = replay_results["dies"].to_bool(); errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the " << (attacker_turn ? "defender" : "attacker") << ' ' << (results_dies ? "perished" : "survived") << " while in-game calculations show it " << (dies ? "perished" : "survived") << " (over-riding game calculations with data source results)\n"; dies = results_dies; // Set hitpoints to 0 so later checks don't invalidate the death. if(results_dies) { defender.get_unit().set_hitpoints(0); } OOS_error_ = true; } if(hits) { try { fire_event(attacker_turn ? "attacker_hits" : "defender_hits"); } catch(const attack_end_exception&) { refresh_bc(); return false; } } else { try { fire_event(attacker_turn ? "attacker_misses" : "defender_misses"); } catch(const attack_end_exception&) { refresh_bc(); return false; } } refresh_bc(); bool attacker_dies = false; if(drains_damage > 0) { attacker.get_unit().heal(drains_damage); } else if(drains_damage < 0) { attacker_dies = attacker.get_unit().take_hit(-drains_damage); } if(dies) { unit_killed(attacker, defender, attacker_stats, defender_stats, false); update_fog = true; } if(attacker_dies) { unit_killed(defender, attacker, defender_stats, attacker_stats, true); (attacker_turn ? update_att_fog_ : update_def_fog_) = true; } if(dies) { update_minimap_ = true; return false; } if(hits) { unit& defender_unit = defender.get_unit(); if(attacker_stats->poisons && !defender_unit.get_state(unit::STATE_POISONED)) { defender_unit.set_state(unit::STATE_POISONED, true); LOG_NG << "defender poisoned\n"; } if(attacker_stats->slows && !defender_unit.get_state(unit::STATE_SLOWED)) { defender_unit.set_state(unit::STATE_SLOWED, true); update_fog = true; defender.damage_ = defender_stats->slow_damage; LOG_NG << "defender slowed\n"; } // If the defender is petrified, the fight stops immediately if(attacker_stats->petrifies) { defender_unit.set_state(unit::STATE_PETRIFIED, true); update_fog = true; attacker.n_attacks_ = 0; defender.n_attacks_ = -1; // Petrified. resources::game_events->pump().fire("petrified", defender.loc_, attacker.loc_); refresh_bc(); } } // Delay until here so that poison and slow go through if(attacker_dies) { update_minimap_ = true; return false; } --attacker.n_attacks_; return true; } void attack::unit_killed(unit_info& attacker, unit_info& defender, const battle_context_unit_stats*& attacker_stats, const battle_context_unit_stats*& defender_stats, bool drain_killed) { attacker.xp_ = game_config::kill_xp(defender.get_unit().level()); defender.xp_ = 0; display::get_singleton()->invalidate(attacker.loc_); game_events::entity_location death_loc(defender.loc_, defender.id_); game_events::entity_location attacker_loc(attacker.loc_, attacker.id_); std::string undead_variation = defender.get_unit().undead_variation(); fire_event("attack_end"); refresh_bc(); // Get weapon info for last_breath and die events. config dat; config a_weapon_cfg = attacker_stats->weapon && attacker.valid() ? attacker_stats->weapon->to_config() : config(); config d_weapon_cfg = defender_stats->weapon && defender.valid() ? defender_stats->weapon->to_config() : config(); if(a_weapon_cfg["name"].empty()) { a_weapon_cfg["name"] = "none"; } if(d_weapon_cfg["name"].empty()) { d_weapon_cfg["name"] = "none"; } dat.add_child("first", d_weapon_cfg); dat.add_child("second", a_weapon_cfg); resources::game_events->pump().fire("last_breath", death_loc, attacker_loc, dat); refresh_bc(); // WML has invalidated the dying unit, abort. if(!defender.valid() || defender.get_unit().hitpoints() > 0) { return; } if(!attacker.valid()) { unit_display::unit_die( defender.loc_, defender.get_unit(), nullptr, defender_stats->weapon ); } else { unit_display::unit_die( defender.loc_, defender.get_unit(), attacker_stats->weapon, defender_stats->weapon, attacker.loc_, &attacker.get_unit() ); } resources::game_events->pump().fire("die", death_loc, attacker_loc, dat); refresh_bc(); if(!defender.valid() || defender.get_unit().hitpoints() > 0) { // WML has invalidated the dying unit, abort return; } units_.erase(defender.loc_); resources::whiteboard->on_kill_unit(); // Plague units make new units on the target hex. if(attacker.valid() && attacker_stats->plagues && !drain_killed) { LOG_NG << "trying to reanimate " << attacker_stats->plague_type << '\n'; if(const unit_type* reanimator = unit_types.find(attacker_stats->plague_type)) { LOG_NG << "found unit type:" << reanimator->id() << '\n'; unit_ptr newunit = unit::create(*reanimator, attacker.get_unit().side(), true, unit_race::MALE); newunit->set_attacks(0); newunit->set_movement(0, true); newunit->set_facing(map_location::get_opposite_dir(attacker.get_unit().facing())); // Apply variation if(undead_variation != "null") { config mod; config& variation = mod.add_child("effect"); variation["apply_to"] = "variation"; variation["name"] = undead_variation; newunit->add_modification("variation", mod); newunit->heal_fully(); } newunit->set_location(death_loc); units_.insert(newunit); game_events::entity_location reanim_loc(defender.loc_, newunit->underlying_id()); resources::game_events->pump().fire("unit_placed", reanim_loc); preferences::encountered_units().insert(newunit->type_id()); if(update_display_) { display::get_singleton()->invalidate(death_loc); } } } else { LOG_NG << "unit not reanimated\n"; } } void attack::perform() { // Stop the user from issuing any commands while the units are fighting. const events::command_disabler disable_commands; if(!a_.valid() || !d_.valid()) { return; } // no attack weapon => stop here and don't attack if(a_.weapon_ < 0) { a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1); a_.get_unit().set_movement(-1, true); return; } if(a_.get_unit().attacks_left() <= 0) { LOG_NG << "attack::perform(): not enough ap.\n"; return; } a_.get_unit().set_facing(a_.loc_.get_relative_dir(d_.loc_)); d_.get_unit().set_facing(d_.loc_.get_relative_dir(a_.loc_)); a_.get_unit().set_attacks(a_.get_unit().attacks_left() - 1); VALIDATE(a_.weapon_ < static_cast<int>(a_.get_unit().attacks().size()), _("An invalid attacker weapon got selected.")); a_.get_unit().set_movement(a_.get_unit().movement_left() - a_.get_unit().attacks()[a_.weapon_].movement_used(), true); a_.get_unit().set_state(unit::STATE_NOT_MOVED, false); a_.get_unit().set_resting(false); d_.get_unit().set_resting(false); // If the attacker was invisible, she isn't anymore! a_.get_unit().set_state(unit::STATE_UNCOVERED, true); bc_.reset(new battle_context(units_, a_.loc_, d_.loc_, a_.weapon_, d_.weapon_)); a_stats_ = &bc_->get_attacker_stats(); d_stats_ = &bc_->get_defender_stats(); if(a_stats_->disable) { LOG_NG << "attack::perform(): tried to attack with a disabled attack.\n"; return; } if(a_stats_->weapon) { a_.weap_id_ = a_stats_->weapon->id(); } if(d_stats_->weapon) { d_.weap_id_ = d_stats_->weapon->id(); } try { fire_event("attack"); } catch(const attack_end_exception&) { return; } refresh_bc(); DBG_NG << "getting attack statistics\n"; statistics::attack_context attack_stats( a_.get_unit(), d_.get_unit(), a_stats_->chance_to_hit, d_stats_->chance_to_hit); a_.orig_attacks_ = a_stats_->num_blows; d_.orig_attacks_ = d_stats_->num_blows; a_.n_attacks_ = a_.orig_attacks_; d_.n_attacks_ = d_.orig_attacks_; a_.xp_ = game_config::combat_xp(d_.get_unit().level()); d_.xp_ = game_config::combat_xp(a_.get_unit().level()); bool defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike); unsigned int rounds = std::max<unsigned int>(a_stats_->rounds, d_stats_->rounds) - 1; const int defender_side = d_.get_unit().side(); LOG_NG << "Fight: (" << a_.loc_ << ") vs (" << d_.loc_ << ") ATT: " << a_stats_->weapon->name() << " " << a_stats_->damage << "-" << a_stats_->num_blows << "(" << a_stats_->chance_to_hit << "%) vs DEF: " << (d_stats_->weapon ? d_stats_->weapon->name() : "none") << " " << d_stats_->damage << "-" << d_stats_->num_blows << "(" << d_stats_->chance_to_hit << "%)" << (defender_strikes_first ? " defender first-strike" : "") << "\n"; // Play the pre-fight animation unit_display::unit_draw_weapon(a_.loc_, a_.get_unit(), a_stats_->weapon, d_stats_->weapon, d_.loc_, &d_.get_unit()); for(;;) { DBG_NG << "start of attack loop...\n"; ++abs_n_attack_; if(a_.n_attacks_ > 0 && !defender_strikes_first) { if(!perform_hit(true, attack_stats)) { DBG_NG << "broke from attack loop on attacker turn\n"; break; } } // If the defender got to strike first, they use it up here. defender_strikes_first = false; ++abs_n_defend_; if(d_.n_attacks_ > 0) { if(!perform_hit(false, attack_stats)) { DBG_NG << "broke from attack loop on defender turn\n"; break; } } // Continue the fight to death; if one of the units got petrified, // either n_attacks or n_defends is -1 if(rounds > 0 && d_.n_attacks_ == 0 && a_.n_attacks_ == 0) { a_.n_attacks_ = a_.orig_attacks_; d_.n_attacks_ = d_.orig_attacks_; --rounds; defender_strikes_first = (d_stats_->firststrike && !a_stats_->firststrike); } if(a_.n_attacks_ <= 0 && d_.n_attacks_ <= 0) { fire_event("attack_end"); refresh_bc(); break; } } // Set by attacker_hits and defender_hits events. resources::gamedata->clear_variable("damage_inflicted"); if(update_def_fog_) { actions::recalculate_fog(defender_side); } // TODO: if we knew the viewing team, we could skip this display update if(update_minimap_ && update_display_) { display::get_singleton()->redraw_minimap(); } if(a_.valid()) { unit& u = a_.get_unit(); u.anim_comp().set_standing(); u.set_experience(u.experience() + a_.xp_); } if(d_.valid()) { unit& u = d_.get_unit(); u.anim_comp().set_standing(); u.set_experience(u.experience() + d_.xp_); } unit_display::unit_sheath_weapon(a_.loc_, a_.valid() ? &a_.get_unit() : nullptr, a_stats_->weapon, d_stats_->weapon, d_.loc_, d_.valid() ? &d_.get_unit() : nullptr); if(update_display_) { game_display::get_singleton()->invalidate_unit(); display::get_singleton()->invalidate(a_.loc_); display::get_singleton()->invalidate(d_.loc_); } if(OOS_error_) { replay::process_error(errbuf_.str()); } } void attack::check_replay_attack_result( bool& hits, int ran_num, int& damage, config replay_results, unit_info& attacker) { int results_chance = replay_results["chance"]; bool results_hits = replay_results["hits"].to_bool(); int results_damage = replay_results["damage"]; #if 0 errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << " replay data differs from local calculated data:" << " chance to hit in data source: " << results_chance << " chance to hit in calculated: " << attacker.cth_ << " chance to hit in data source: " << results_chance << " chance to hit in calculated: " << attacker.cth_ ; attacker.cth_ = results_chance; hits = results_hits; damage = results_damage; OOS_error_ = true; #endif if(results_chance != attacker.cth_) { errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": chance to hit is inconsistent. Data source: " << results_chance << "; Calculation: " << attacker.cth_ << " (over-riding game calculations with data source results)\n"; attacker.cth_ = results_chance; OOS_error_ = true; } if(results_hits != hits) { errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit was " << (results_hits ? "successful" : "unsuccessful") << ", while in-game calculations say the hit was " << (hits ? "successful" : "unsuccessful") << " random number: " << ran_num << " = " << (ran_num % 100) << "/" << results_chance << " (over-riding game calculations with data source results)\n"; hits = results_hits; OOS_error_ = true; } if(results_damage != damage) { errbuf_ << "SYNC: In attack " << a_.dump() << " vs " << d_.dump() << ": the data source says the hit did " << results_damage << " damage, while in-game calculations show the hit doing " << damage << " damage (over-riding game calculations with data source results)\n"; damage = results_damage; OOS_error_ = true; } } } // end anonymous namespace // ================================================================================== // FREE-STANDING FUNCTIONS // ================================================================================== void attack_unit(const map_location& attacker, const map_location& defender, int attack_with, int defend_with, bool update_display) { attack dummy(attacker, defender, attack_with, defend_with, update_display); dummy.perform(); } void attack_unit_and_advance(const map_location& attacker, const map_location& defender, int attack_with, int defend_with, bool update_display, const ai::unit_advancements_aspect& ai_advancement) { attack_unit(attacker, defender, attack_with, defend_with, update_display); unit_map::const_iterator atku = resources::gameboard->units().find(attacker); if(atku != resources::gameboard->units().end()) { advance_unit_at(advance_unit_params(attacker).ai_advancements(ai_advancement)); } unit_map::const_iterator defu = resources::gameboard->units().find(defender); if(defu != resources::gameboard->units().end()) { advance_unit_at(advance_unit_params(defender).ai_advancements(ai_advancement)); } } int under_leadership(const unit &u, const map_location& loc, const_attack_ptr weapon, const_attack_ptr opp_weapon) { unit_ability_list abil = u.get_abilities("leadership", loc, weapon, opp_weapon); unit_abilities::effect leader_effect(abil, 0, false); return leader_effect.get_composite_value(); } //begin of weapon emulates function. bool unit::abilities_filter_matches(const config& cfg, bool attacker, int res) const { if(!(cfg["active_on"].empty() || (attacker && cfg["active_on"] == "offense") || (!attacker && cfg["active_on"] == "defense"))) { return false; } if(!unit_abilities::filter_base_matches(cfg, res)) { return false; } return true; } //functions for emulate weapon specials. //filter opponent and affect self/opponent/both option. bool unit::ability_filter_fighter(const std::string& ability, const std::string& filter_attacker , const config& cfg, const map_location& loc, const unit& u2) const { const config &filter = cfg.child(filter_attacker); if(!filter) { return true; } return unit_filter(vconfig(filter)).set_use_flat_tod(ability == "illuminates").matches(*this, loc, u2); } static bool ability_apply_filter(const unit_map::const_iterator un, const unit_map::const_iterator up, const std::string& ability, const config& cfg, const map_location& loc, const map_location& opp_loc, bool attacker ) { if(!up->ability_filter_fighter(ability, "filter_opponent", cfg, opp_loc, *un)){ return true; } if(!un->ability_filter_fighter(ability, "filter_student", cfg, loc, *up)){ return true; } if((attacker && !un->ability_filter_fighter(ability, "filter_attacker", cfg, loc, *up)) || (!attacker && !up->ability_filter_fighter(ability, "filter_attacker", cfg, opp_loc, *un))){ return true; } if((!attacker && !un->ability_filter_fighter(ability, "filter_defender", cfg, loc, *up)) || (attacker && !up->ability_filter_fighter(ability, "filter_defender", cfg, opp_loc, *un))){ return true; } return false; } bool leadership_affects_self(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon) { const unit_map::const_iterator un = units.find(loc); if(un == units.end()) { return false; } unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon); for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) { const std::string& apply_to = (*i->first)["apply_to"]; if(apply_to.empty() || apply_to == "both" || apply_to == "self") { return true; } if(attacker && apply_to == "attacker") { return true; } if(!attacker && apply_to == "defender") { return true; } ++i; } return false; } bool leadership_affects_opponent(const std::string& ability,const unit_map& units, const map_location& loc, bool attacker, const_attack_ptr weapon,const_attack_ptr opp_weapon) { const unit_map::const_iterator un = units.find(loc); if(un == units.end()) { return false; } unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon); for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) { const std::string& apply_to = (*i->first)["apply_to"]; if(apply_to == "both" || apply_to == "opponent") { return true; } if(attacker && apply_to == "defender") { return true; } if(!attacker && apply_to == "attacker") { return true; } ++i; } return false; } //sub function for emulate chance_to_hit,damage drains and attacks special. std::pair<int, bool> ability_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, int abil_value, bool backstab_pos, const_attack_ptr weapon, const_attack_ptr opp_weapon) { const unit_map::const_iterator un = units.find(loc); const unit_map::const_iterator up = units.find(opp_loc); if(un == units.end()) { return {abil_value, false}; } unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon); for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) { const config &filter = (*i->first).child("filter_opponent"); const config &filter_student = (*i->first).child("filter_student"); const config &filter_attacker = (*i->first).child("filter_attacker"); const config &filter_defender = (*i->first).child("filter_defender"); bool show_result = false; if(up == units.end() && !filter_student && !filter && !filter_attacker && !filter_defender) { show_result = un->abilities_filter_matches(*i->first, attacker, abil_value); } else if(up == units.end() && (filter_student || filter || filter_attacker || filter_defender)) { return {abil_value, false}; } else { show_result = !(!un->abilities_filter_matches(*i->first, attacker, abil_value) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker)); } if(!show_result) { i = abil.erase(i); } else { ++i; } } if(!abil.empty()) { unit_abilities::effect leader_effect(abil, abil_value, backstab_pos); return {leader_effect.get_composite_value(), true}; } return {abil_value, false}; } //sub function for wmulate boolean special(slow, poison...) bool bool_leadership(const std::string& ability,const unit_map& units, const map_location& loc, const map_location& opp_loc, bool attacker, const_attack_ptr weapon, const_attack_ptr opp_weapon) { const unit_map::const_iterator un = units.find(loc); const unit_map::const_iterator up = units.find(opp_loc); if(un == units.end() || up == units.end()) { return false; } unit_ability_list abil = un->get_abilities(ability, weapon, opp_weapon); for(unit_ability_list::iterator i = abil.begin(); i != abil.end();) { const std::string& active_on = (*i->first)["active_on"]; if(!(active_on.empty() || (attacker && active_on == "offense") || (!attacker && active_on == "defense")) || ability_apply_filter(un, up, ability, *i->first, loc, opp_loc, attacker)) { i = abil.erase(i); } else { ++i; } } if(!abil.empty()) { return true; } return false; } //emulate boolean special for self/adjacent and/or opponent. bool attack_type::bool_ability(const std::string& ability) const { bool abil_bool= get_special_bool(ability); const unit_map& units = display::get_singleton()->get_units(); if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) { abil_bool = get_special_bool(ability) || bool_leadership(ability, units, self_loc_, other_loc_, is_attacker_, shared_from_this(), other_attack_); } if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) { abil_bool = get_special_bool(ability) || bool_leadership(ability, units, other_loc_, self_loc_, !is_attacker_, other_attack_, shared_from_this()); } return abil_bool; } //emulate numerical special for self/adjacent and/or opponent. std::pair<int, bool> attack_type::combat_ability(const std::string& ability, int abil_value, bool backstab_pos) const { const unit_map& units = display::get_singleton()->get_units(); if(leadership_affects_self(ability, units, self_loc_, is_attacker_, shared_from_this(), other_attack_)) { return ability_leadership(ability, units, self_loc_, other_loc_, is_attacker_, abil_value, backstab_pos, shared_from_this(), other_attack_); } if(leadership_affects_opponent(ability, units, other_loc_, !is_attacker_, other_attack_, shared_from_this())) { return ability_leadership(ability, units, other_loc_,self_loc_, !is_attacker_, abil_value, backstab_pos, other_attack_, shared_from_this()); } return {abil_value, false}; } //end of emulate weapon special functions. int combat_modifier(const unit_map& units, const gamemap& map, const map_location& loc, unit_type::ALIGNMENT alignment, bool is_fearless) { const tod_manager& tod_m = *resources::tod_manager; const time_of_day& effective_tod = tod_m.get_illuminated_time_of_day(units, map, loc); return combat_modifier(effective_tod, alignment, is_fearless); } int combat_modifier(const time_of_day& effective_tod, unit_type::ALIGNMENT alignment, bool is_fearless) { const tod_manager& tod_m = *resources::tod_manager; const int lawful_bonus = effective_tod.lawful_bonus; return generic_combat_modifier(lawful_bonus, alignment, is_fearless, tod_m.get_max_liminal_bonus()); } int generic_combat_modifier(int lawful_bonus, unit_type::ALIGNMENT alignment, bool is_fearless, int max_liminal_bonus) { int bonus; switch(alignment.v) { case unit_type::ALIGNMENT::LAWFUL: bonus = lawful_bonus; break; case unit_type::ALIGNMENT::NEUTRAL: bonus = 0; break; case unit_type::ALIGNMENT::CHAOTIC: bonus = -lawful_bonus; break; case unit_type::ALIGNMENT::LIMINAL: bonus = std::max(0, max_liminal_bonus-std::abs(lawful_bonus)); break; default: bonus = 0; } if(is_fearless) { bonus = std::max<int>(bonus, 0); } return bonus; } bool backstab_check(const map_location& attacker_loc, const map_location& defender_loc, const unit_map& units, const std::vector<team>& teams) { const unit_map::const_iterator defender = units.find(defender_loc); if(defender == units.end()) { return false; // No defender } adjacent_loc_array_t adj; get_adjacent_tiles(defender_loc, adj.data()); unsigned i; for(i = 0; i < adj.size(); ++i) { if(adj[i] == attacker_loc) { break; } } if(i >= 6) { return false; // Attack not from adjacent location } const unit_map::const_iterator opp = units.find(adj[(i + 3) % 6]); // No opposite unit. if(opp == units.end()) { return false; } if(opp->incapacitated()) { return false; } // If sides aren't valid teams, then they are enemies. if(std::size_t(defender->side() - 1) >= teams.size() || std::size_t(opp->side() - 1) >= teams.size()) { return true; } // Defender and opposite are enemies. if(teams[defender->side() - 1].is_enemy(opp->side())) { return true; } // Defender and opposite are friends. return false; }
spixi/wesnoth
src/actions/attack.cpp
C++
gpl-2.0
57,856
#!/usr/bin/env python2 import copy import Queue import os import socket import struct import subprocess import sys import threading import time import unittest import dns import dns.message import libnacl import libnacl.utils class DNSDistTest(unittest.TestCase): """ Set up a dnsdist instance and responder threads. Queries sent to dnsdist are relayed to the responder threads, who reply with the response provided by the tests themselves on a queue. Responder threads also queue the queries received from dnsdist on a separate queue, allowing the tests to check that the queries sent from dnsdist were as expected. """ _dnsDistPort = 5340 _dnsDistListeningAddr = "127.0.0.1" _testServerPort = 5350 _toResponderQueue = Queue.Queue() _fromResponderQueue = Queue.Queue() _queueTimeout = 1 _dnsdistStartupDelay = 2.0 _dnsdist = None _responsesCounter = {} _shutUp = True _config_template = """ """ _config_params = ['_testServerPort'] _acl = ['127.0.0.1/32'] _consolePort = 5199 _consoleKey = None @classmethod def startResponders(cls): print("Launching responders..") cls._UDPResponder = threading.Thread(name='UDP Responder', target=cls.UDPResponder, args=[cls._testServerPort]) cls._UDPResponder.setDaemon(True) cls._UDPResponder.start() cls._TCPResponder = threading.Thread(name='TCP Responder', target=cls.TCPResponder, args=[cls._testServerPort]) cls._TCPResponder.setDaemon(True) cls._TCPResponder.start() @classmethod def startDNSDist(cls, shutUp=True): print("Launching dnsdist..") conffile = 'dnsdist_test.conf' params = tuple([getattr(cls, param) for param in cls._config_params]) print(params) with open(conffile, 'w') as conf: conf.write("-- Autogenerated by dnsdisttests.py\n") conf.write(cls._config_template % params) dnsdistcmd = [os.environ['DNSDISTBIN'], '-C', conffile, '-l', '%s:%d' % (cls._dnsDistListeningAddr, cls._dnsDistPort) ] for acl in cls._acl: dnsdistcmd.extend(['--acl', acl]) print(' '.join(dnsdistcmd)) if shutUp: with open(os.devnull, 'w') as fdDevNull: cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True, stdout=fdDevNull) else: cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True) if 'DNSDIST_FAST_TESTS' in os.environ: delay = 0.5 else: delay = cls._dnsdistStartupDelay time.sleep(delay) if cls._dnsdist.poll() is not None: cls._dnsdist.kill() sys.exit(cls._dnsdist.returncode) @classmethod def setUpSockets(cls): print("Setting up UDP socket..") cls._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cls._sock.settimeout(2.0) cls._sock.connect(("127.0.0.1", cls._dnsDistPort)) @classmethod def setUpClass(cls): cls.startResponders() cls.startDNSDist(cls._shutUp) cls.setUpSockets() print("Launching tests..") @classmethod def tearDownClass(cls): if 'DNSDIST_FAST_TESTS' in os.environ: delay = 0.1 else: delay = 1.0 if cls._dnsdist: cls._dnsdist.terminate() if cls._dnsdist.poll() is None: time.sleep(delay) if cls._dnsdist.poll() is None: cls._dnsdist.kill() cls._dnsdist.wait() @classmethod def _ResponderIncrementCounter(cls): if threading.currentThread().name in cls._responsesCounter: cls._responsesCounter[threading.currentThread().name] += 1 else: cls._responsesCounter[threading.currentThread().name] = 1 @classmethod def _getResponse(cls, request): response = None if len(request.question) != 1: print("Skipping query with question count %d" % (len(request.question))) return None healthcheck = not str(request.question[0].name).endswith('tests.powerdns.com.') if not healthcheck: cls._ResponderIncrementCounter() if not cls._toResponderQueue.empty(): response = cls._toResponderQueue.get(True, cls._queueTimeout) if response: response = copy.copy(response) response.id = request.id cls._fromResponderQueue.put(request, True, cls._queueTimeout) if not response: # unexpected query, or health check response = dns.message.make_response(request) return response @classmethod def UDPResponder(cls, port, ignoreTrailing=False): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind(("127.0.0.1", port)) while True: data, addr = sock.recvfrom(4096) request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing) response = cls._getResponse(request) if not response: continue sock.settimeout(2.0) sock.sendto(response.to_wire(), addr) sock.settimeout(None) sock.close() @classmethod def TCPResponder(cls, port, ignoreTrailing=False, multipleResponses=False): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) try: sock.bind(("127.0.0.1", port)) except socket.error as e: print("Error binding in the TCP responder: %s" % str(e)) sys.exit(1) sock.listen(100) while True: (conn, _) = sock.accept() conn.settimeout(2.0) data = conn.recv(2) (datalen,) = struct.unpack("!H", data) data = conn.recv(datalen) request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing) response = cls._getResponse(request) if not response: conn.close() continue wire = response.to_wire() conn.send(struct.pack("!H", len(wire))) conn.send(wire) while multipleResponses: if cls._toResponderQueue.empty(): break response = cls._toResponderQueue.get(True, cls._queueTimeout) if not response: break response = copy.copy(response) response.id = request.id wire = response.to_wire() try: conn.send(struct.pack("!H", len(wire))) conn.send(wire) except socket.error as e: # some of the tests are going to close # the connection on us, just deal with it break conn.close() sock.close() @classmethod def sendUDPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False): if useQueue: cls._toResponderQueue.put(response, True, timeout) if timeout: cls._sock.settimeout(timeout) try: if not rawQuery: query = query.to_wire() cls._sock.send(query) data = cls._sock.recv(4096) except socket.timeout: data = None finally: if timeout: cls._sock.settimeout(None) receivedQuery = None message = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) if data: message = dns.message.from_wire(data) return (receivedQuery, message) @classmethod def openTCPConnection(cls, timeout=None): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect(("127.0.0.1", cls._dnsDistPort)) return sock @classmethod def sendTCPQueryOverConnection(cls, sock, query, rawQuery=False): if not rawQuery: wire = query.to_wire() else: wire = query sock.send(struct.pack("!H", len(wire))) sock.send(wire) @classmethod def recvTCPResponseOverConnection(cls, sock): message = None data = sock.recv(2) if data: (datalen,) = struct.unpack("!H", data) data = sock.recv(datalen) if data: message = dns.message.from_wire(data) return message @classmethod def sendTCPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False): message = None if useQueue: cls._toResponderQueue.put(response, True, timeout) sock = cls.openTCPConnection(timeout) try: cls.sendTCPQueryOverConnection(sock, query, rawQuery) message = cls.recvTCPResponseOverConnection(sock) except socket.timeout as e: print("Timeout: %s" % (str(e))) except socket.error as e: print("Network error: %s" % (str(e))) finally: sock.close() receivedQuery = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) return (receivedQuery, message) @classmethod def sendTCPQueryWithMultipleResponses(cls, query, responses, useQueue=True, timeout=2.0, rawQuery=False): if useQueue: for response in responses: cls._toResponderQueue.put(response, True, timeout) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect(("127.0.0.1", cls._dnsDistPort)) messages = [] try: if not rawQuery: wire = query.to_wire() else: wire = query sock.send(struct.pack("!H", len(wire))) sock.send(wire) while True: data = sock.recv(2) if not data: break (datalen,) = struct.unpack("!H", data) data = sock.recv(datalen) messages.append(dns.message.from_wire(data)) except socket.timeout as e: print("Timeout: %s" % (str(e))) except socket.error as e: print("Network error: %s" % (str(e))) finally: sock.close() receivedQuery = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) return (receivedQuery, messages) def setUp(self): # This function is called before every tests # Clear the responses counters for key in self._responsesCounter: self._responsesCounter[key] = 0 # Make sure the queues are empty, in case # a previous test failed while not self._toResponderQueue.empty(): self._toResponderQueue.get(False) while not self._fromResponderQueue.empty(): self._fromResponderQueue.get(False) @classmethod def clearToResponderQueue(cls): while not cls._toResponderQueue.empty(): cls._toResponderQueue.get(False) @classmethod def clearFromResponderQueue(cls): while not cls._fromResponderQueue.empty(): cls._fromResponderQueue.get(False) @classmethod def clearResponderQueues(cls): cls.clearToResponderQueue() cls.clearFromResponderQueue() @staticmethod def generateConsoleKey(): return libnacl.utils.salsa_key() @classmethod def _encryptConsole(cls, command, nonce): if cls._consoleKey is None: return command return libnacl.crypto_secretbox(command, nonce, cls._consoleKey) @classmethod def _decryptConsole(cls, command, nonce): if cls._consoleKey is None: return command return libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey) @classmethod def sendConsoleCommand(cls, command, timeout=1.0): ourNonce = libnacl.utils.rand_nonce() theirNonce = None sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect(("127.0.0.1", cls._consolePort)) sock.send(ourNonce) theirNonce = sock.recv(len(ourNonce)) halfNonceSize = len(ourNonce) / 2 readingNonce = ourNonce[0:halfNonceSize] + theirNonce[halfNonceSize:] writingNonce = theirNonce[0:halfNonceSize] + ourNonce[halfNonceSize:] msg = cls._encryptConsole(command, writingNonce) sock.send(struct.pack("!I", len(msg))) sock.send(msg) data = sock.recv(4) (responseLen,) = struct.unpack("!I", data) data = sock.recv(responseLen) response = cls._decryptConsole(data, readingNonce) return response
DrRemorse/pdns
regression-tests.dnsdist/dnsdisttests.py
Python
gpl-2.0
13,296
/* * Interface to libmp3lame for mp3 encoding * Copyright (c) 2002 Lennert Buytenhek <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file mp3lameaudio.c * Interface to libmp3lame for mp3 encoding. */ #include "avcodec.h" #include "mpegaudio.h" #include <lame/lame.h> #define BUFFER_SIZE (7200 + MPA_FRAME_SIZE + MPA_FRAME_SIZE/4) typedef struct Mp3AudioContext { lame_global_flags *gfp; int stereo; uint8_t buffer[BUFFER_SIZE]; int buffer_index; } Mp3AudioContext; static av_cold int MP3lame_encode_init(AVCodecContext *avctx) { Mp3AudioContext *s = avctx->priv_data; if (avctx->channels > 2) return -1; s->stereo = avctx->channels > 1 ? 1 : 0; if ((s->gfp = lame_init()) == NULL) goto err; lame_set_in_samplerate(s->gfp, avctx->sample_rate); lame_set_out_samplerate(s->gfp, avctx->sample_rate); lame_set_num_channels(s->gfp, avctx->channels); /* lame 3.91 dies on quality != 5 */ lame_set_quality(s->gfp, 5); /* lame 3.91 doesn't work in mono */ lame_set_mode(s->gfp, JOINT_STEREO); lame_set_brate(s->gfp, avctx->bit_rate/1000); if(avctx->flags & CODEC_FLAG_QSCALE) { lame_set_brate(s->gfp, 0); lame_set_VBR(s->gfp, vbr_default); lame_set_VBR_q(s->gfp, avctx->global_quality / (float)FF_QP2LAMBDA); } lame_set_bWriteVbrTag(s->gfp,0); lame_set_disable_reservoir(s->gfp, avctx->flags2 & CODEC_FLAG2_BIT_RESERVOIR ? 0 : 1); if (lame_init_params(s->gfp) < 0) goto err_close; avctx->frame_size = lame_get_framesize(s->gfp); avctx->coded_frame= avcodec_alloc_frame(); avctx->coded_frame->key_frame= 1; return 0; err_close: lame_close(s->gfp); err: return -1; } static const int sSampleRates[3] = { 44100, 48000, 32000 }; static const int sBitRates[2][3][15] = { { { 0, 32, 64, 96,128,160,192,224,256,288,320,352,384,416,448}, { 0, 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384}, { 0, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224,256,320} }, { { 0, 32, 48, 56, 64, 80, 96,112,128,144,160,176,192,224,256}, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160}, { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160} }, }; static const int sSamplesPerFrame[2][3] = { { 384, 1152, 1152 }, { 384, 1152, 576 } }; static const int sBitsPerSlot[3] = { 32, 8, 8 }; static int mp3len(void *data, int *samplesPerFrame, int *sampleRate) { uint32_t header = AV_RB32(data); int layerID = 3 - ((header >> 17) & 0x03); int bitRateID = ((header >> 12) & 0x0f); int sampleRateID = ((header >> 10) & 0x03); int bitsPerSlot = sBitsPerSlot[layerID]; int isPadded = ((header >> 9) & 0x01); static int const mode_tab[4]= {2,3,1,0}; int mode= mode_tab[(header >> 19) & 0x03]; int mpeg_id= mode>0; int temp0, temp1, bitRate; if ( (( header >> 21 ) & 0x7ff) != 0x7ff || mode == 3 || layerID==3 || sampleRateID==3) { return -1; } if(!samplesPerFrame) samplesPerFrame= &temp0; if(!sampleRate ) sampleRate = &temp1; // *isMono = ((header >> 6) & 0x03) == 0x03; *sampleRate = sSampleRates[sampleRateID]>>mode; bitRate = sBitRates[mpeg_id][layerID][bitRateID] * 1000; *samplesPerFrame = sSamplesPerFrame[mpeg_id][layerID]; //av_log(NULL, AV_LOG_DEBUG, "sr:%d br:%d spf:%d l:%d m:%d\n", *sampleRate, bitRate, *samplesPerFrame, layerID, mode); return *samplesPerFrame * bitRate / (bitsPerSlot * *sampleRate) + isPadded; } static int MP3lame_encode_frame(AVCodecContext *avctx, unsigned char *frame, int buf_size, void *data) { Mp3AudioContext *s = avctx->priv_data; int len; int lame_result; /* lame 3.91 dies on '1-channel interleaved' data */ if(data){ if (s->stereo) { lame_result = lame_encode_buffer_interleaved( s->gfp, data, avctx->frame_size, s->buffer + s->buffer_index, BUFFER_SIZE - s->buffer_index ); } else { lame_result = lame_encode_buffer( s->gfp, data, data, avctx->frame_size, s->buffer + s->buffer_index, BUFFER_SIZE - s->buffer_index ); } }else{ lame_result= lame_encode_flush( s->gfp, s->buffer + s->buffer_index, BUFFER_SIZE - s->buffer_index ); } if(lame_result==-1) { /* output buffer too small */ av_log(avctx, AV_LOG_ERROR, "lame: output buffer too small (buffer index: %d, free bytes: %d)\n", s->buffer_index, BUFFER_SIZE - s->buffer_index); return 0; } s->buffer_index += lame_result; if(s->buffer_index<4) return 0; len= mp3len(s->buffer, NULL, NULL); //av_log(avctx, AV_LOG_DEBUG, "in:%d packet-len:%d index:%d\n", avctx->frame_size, len, s->buffer_index); if(len <= s->buffer_index){ memcpy(frame, s->buffer, len); s->buffer_index -= len; memmove(s->buffer, s->buffer+len, s->buffer_index); //FIXME fix the audio codec API, so we do not need the memcpy() /*for(i=0; i<len; i++){ av_log(avctx, AV_LOG_DEBUG, "%2X ", frame[i]); }*/ return len; }else return 0; } static av_cold int MP3lame_encode_close(AVCodecContext *avctx) { Mp3AudioContext *s = avctx->priv_data; av_freep(&avctx->coded_frame); lame_close(s->gfp); return 0; } AVCodec libmp3lame_encoder = { "libmp3lame", CODEC_TYPE_AUDIO, CODEC_ID_MP3, sizeof(Mp3AudioContext), MP3lame_encode_init, MP3lame_encode_frame, MP3lame_encode_close, .capabilities= CODEC_CAP_DELAY, };
uwehermann/easybox-904-lte-firmware
package/ffmpeg/src/libavcodec/libmp3lame.c
C
gpl-2.0
6,658
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.unpack200.bytecode.forms; import org.apache.harmony.unpack200.SegmentConstantPool; import org.apache.harmony.unpack200.bytecode.ByteCode; import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef; import org.apache.harmony.unpack200.bytecode.OperandManager; /** * This class implements the byte code form for those bytecodes which have * IMethod references (and only IMethod references). */ public class IMethodRefForm extends ReferenceForm { public IMethodRefForm(int opcode, String name, int[] rewrite) { super(opcode, name, rewrite); } protected int getOffset(OperandManager operandManager) { return operandManager.nextIMethodRef(); } protected int getPoolID() { return SegmentConstantPool.CP_IMETHOD; } /* * (non-Javadoc) * * @see org.apache.harmony.unpack200.bytecode.forms.ByteCodeForm#setByteCodeOperands(org.apache.harmony.unpack200.bytecode.ByteCode, * org.apache.harmony.unpack200.bytecode.OperandTable, * org.apache.harmony.unpack200.Segment) */ public void setByteCodeOperands(ByteCode byteCode, OperandManager operandManager, int codeLength) { super.setByteCodeOperands(byteCode, operandManager, codeLength); final int count = ((CPInterfaceMethodRef) byteCode .getNestedClassFileEntries()[0]).invokeInterfaceCount(); byteCode.getRewrite()[3] = count; } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/pack200/src/main/java/org/apache/harmony/unpack200/bytecode/forms/IMethodRefForm.java
Java
gpl-2.0
2,333
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.pouyadr.ui; import android.animation.ObjectAnimator; import android.animation.StateListAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Outline; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.Html; import android.text.InputType; import android.text.Spannable; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.Base64; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.pouyadr.PhoneFormat.PhoneFormat; import org.pouyadr.Pouya.Helper.GhostPorotocol; import org.pouyadr.Pouya.Helper.ThemeChanger; import org.pouyadr.Pouya.Setting.Setting; import org.pouyadr.finalsoft.FontActivity; import org.pouyadr.finalsoft.Fonts; import org.pouyadr.messenger.AndroidUtilities; import org.pouyadr.messenger.AnimationCompat.AnimatorListenerAdapterProxy; import org.pouyadr.messenger.AnimationCompat.AnimatorSetProxy; import org.pouyadr.messenger.AnimationCompat.ObjectAnimatorProxy; import org.pouyadr.messenger.AnimationCompat.ViewProxy; import org.pouyadr.messenger.ApplicationLoader; import org.pouyadr.messenger.BuildVars; import org.pouyadr.messenger.FileLoader; import org.pouyadr.messenger.FileLog; import org.pouyadr.messenger.LocaleController; import org.pouyadr.messenger.MediaController; import org.pouyadr.messenger.MessageObject; import org.pouyadr.messenger.MessagesController; import org.pouyadr.messenger.MessagesStorage; import org.pouyadr.messenger.NotificationCenter; import org.pouyadr.messenger.R; import org.pouyadr.messenger.UserConfig; import org.pouyadr.messenger.UserObject; import org.pouyadr.messenger.browser.Browser; import org.pouyadr.tgnet.ConnectionsManager; import org.pouyadr.tgnet.RequestDelegate; import org.pouyadr.tgnet.SerializedData; import org.pouyadr.tgnet.TLObject; import org.pouyadr.tgnet.TLRPC; import org.pouyadr.ui.ActionBar.ActionBar; import org.pouyadr.ui.ActionBar.ActionBarMenu; import org.pouyadr.ui.ActionBar.ActionBarMenuItem; import org.pouyadr.ui.ActionBar.BaseFragment; import org.pouyadr.ui.ActionBar.BottomSheet; import org.pouyadr.ui.ActionBar.Theme; import org.pouyadr.ui.Adapters.BaseFragmentAdapter; import org.pouyadr.ui.Cells.CheckBoxCell; import org.pouyadr.ui.Cells.EmptyCell; import org.pouyadr.ui.Cells.HeaderCell; import org.pouyadr.ui.Cells.ShadowSectionCell; import org.pouyadr.ui.Cells.TextCheckCell; import org.pouyadr.ui.Cells.TextDetailSettingsCell; import org.pouyadr.ui.Cells.TextInfoCell; import org.pouyadr.ui.Cells.TextSettingsCell; import org.pouyadr.ui.Components.AvatarDrawable; import org.pouyadr.ui.Components.AvatarUpdater; import org.pouyadr.ui.Components.BackupImageView; import org.pouyadr.ui.Components.LayoutHelper; import org.pouyadr.ui.Components.NumberPicker; import java.io.File; import java.util.ArrayList; import java.util.Locale; public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider { private ListView listView; private ListAdapter listAdapter; private BackupImageView avatarImage; private TextView nameTextView; private TextView onlineTextView; private ImageView writeButton; private AnimatorSetProxy writeButtonAnimation; private AvatarUpdater avatarUpdater = new AvatarUpdater(); private View extraHeightView; private View shadowView; private int extraHeight; private int overscrollRow; private int emptyRow; private int numberSectionRow; private int newgeramsectionrow; private int newgeramsectionrow2; private int ghostactivate; private int showdateshamsi; private int sendtyping; private int showtimeago; private int numberRow; private int usernameRow; private int settingsSectionRow; private int settingsSectionRow2; private int enableAnimationsRow; private int notificationRow; private int backgroundRow; private int languageRow; private int privacyRow; private int mediaDownloadSection; private int mediaDownloadSection2; private int mobileDownloadRow; private int wifiDownloadRow; private int roamingDownloadRow; private int saveToGalleryRow; private int messagesSectionRow; private int messagesSectionRow2; private int customTabsRow; private int directShareRow; private int textSizeRow; private int fontType; private int stickersRow; private int cacheRow; private int raiseToSpeakRow; private int sendByEnterRow; private int supportSectionRow; private int supportSectionRow2; private int askQuestionRow; private int telegramFaqRow; private int privacyPolicyRow; private int sendLogsRow; private int clearLogsRow; private int switchBackendButtonRow; private int versionRow; private int contactsSectionRow; private int contactsReimportRow; private int contactsSortRow; private int autoplayGifsRow; private int rowCount; private final static int edit_name = 1; private final static int logout = 2; private int answeringmachinerow2; private int answeringmachinerow; private int tabletforceoverride; private int anweringmachinactive; private int answermachinetext; private static class LinkMovementMethodMy extends LinkMovementMethod { @Override public boolean onTouchEvent(@NonNull TextView widget, @NonNull Spannable buffer, @NonNull MotionEvent event) { try { return super.onTouchEvent(widget, buffer, event); } catch (Exception e) { FileLog.e("tmessages", e); } return false; } } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); avatarUpdater.parentFragment = this; avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() { @Override public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) { TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto(); req.caption = ""; req.crop = new TLRPC.TL_inputPhotoCropAuto(); req.file = file; req.geo_point = new TLRPC.TL_inputGeoPointEmpty(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); if (user == null) { return; } MessagesController.getInstance().putUser(user, false); } else { UserConfig.setCurrentUser(user); } TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response; ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes; TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100); TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000); user.photo = new TLRPC.TL_userProfilePhoto(); user.photo.photo_id = photo.photo.id; if (smallSize != null) { user.photo.photo_small = smallSize.location; } if (bigSize != null) { user.photo.photo_big = bigSize.location; } else if (smallSize != null) { user.photo.photo_small = smallSize.location; } MessagesStorage.getInstance().clearUserPhotos(user.id); ArrayList<TLRPC.User> users = new ArrayList<>(); users.add(user); MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL); NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); UserConfig.saveConfig(true); } }); } } }); } }; NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); rowCount = 0; overscrollRow = rowCount++; emptyRow = rowCount++; numberSectionRow = rowCount++; numberRow = rowCount++; usernameRow = rowCount++; newgeramsectionrow = rowCount++; newgeramsectionrow2 = rowCount++; ghostactivate = rowCount++; sendtyping = rowCount++; showtimeago = rowCount++; showdateshamsi = rowCount++; tabletforceoverride = rowCount++; answeringmachinerow = rowCount++; answeringmachinerow2 = rowCount++; anweringmachinactive = rowCount++; answermachinetext = rowCount++; settingsSectionRow = rowCount++; settingsSectionRow2 = rowCount++; notificationRow = rowCount++; privacyRow = rowCount++; backgroundRow = rowCount++; languageRow = rowCount++; enableAnimationsRow = rowCount++; mediaDownloadSection = rowCount++; mediaDownloadSection2 = rowCount++; mobileDownloadRow = rowCount++; wifiDownloadRow = rowCount++; roamingDownloadRow = rowCount++; if (Build.VERSION.SDK_INT >= 11) { autoplayGifsRow = rowCount++; } saveToGalleryRow = rowCount++; messagesSectionRow = rowCount++; messagesSectionRow2 = rowCount++; customTabsRow = rowCount++; if (Build.VERSION.SDK_INT >= 23) { directShareRow = rowCount++; } textSizeRow = rowCount++; fontType = rowCount++; stickersRow = rowCount++; cacheRow = rowCount++; raiseToSpeakRow = rowCount++; sendByEnterRow = rowCount++; supportSectionRow = rowCount++; supportSectionRow2 = rowCount++; askQuestionRow = rowCount++; telegramFaqRow = rowCount++; privacyPolicyRow = rowCount++; if (BuildVars.DEBUG_VERSION) { sendLogsRow = rowCount++; clearLogsRow = rowCount++; switchBackendButtonRow = rowCount++; } versionRow = rowCount++; //contactsSectionRow = rowCount++; //contactsReimportRow = rowCount++; //contactsSortRow = rowCount++; MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true); return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); if (avatarImage != null) { avatarImage.setImageDrawable(null); } MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId()); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); avatarUpdater.clear(); } @Override public View createView(final Context context) { actionBar.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); actionBar.setItemsBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAddToContainer(false); extraHeight = 88; if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == edit_name) { presentFragment(new ChangeNameActivity()); } else if (id == logout) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().performLogout(true); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } } }); ActionBarMenu menu = actionBar.createMenu(); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0); item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0); listAdapter = new ListAdapter(context); fragmentView = new FrameLayout(context) { @Override protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) { if (child == listView) { boolean result = super.drawChild(canvas, child, drawingTime); if (parentLayout != null) { int actionBarHeight = 0; int childCount = getChildCount(); for (int a = 0; a < childCount; a++) { View view = getChildAt(a); if (view == child) { continue; } if (view instanceof ActionBar && view.getVisibility() == VISIBLE) { if (((ActionBar) view).getCastShadows()) { actionBarHeight = view.getMeasuredHeight(); } break; } } parentLayout.drawHeaderShadow(canvas, actionBarHeight); } return result; } else { return super.drawChild(canvas, child, drawingTime); } } }; FrameLayout frameLayout = (FrameLayout) fragmentView; listView = new ListView(context); listView.setDivider(null); listView.setDividerHeight(0); listView.setVerticalScrollBarEnabled(false); AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { if (i == textSizeRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize)); final NumberPicker numberPicker = new NumberPicker(getParentActivity()); numberPicker.setMinValue(12); numberPicker.setMaxValue(30); numberPicker.setValue(MessagesController.getInstance().fontSize); builder.setView(numberPicker); builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("fons_size", numberPicker.getValue()); MessagesController.getInstance().fontSize = numberPicker.getValue(); editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); showDialog(builder.create()); } else if (i == fontType) { // Toast.makeText(context, "ssssssssssss", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, FontActivity.class); context.startActivity(intent); } else if (i == enableAnimationsRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); boolean animations = preferences.getBoolean("view_animations", true); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("view_animations", !animations); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!animations); } } else if (i == notificationRow) { presentFragment(new NotificationsSettingsActivity()); } else if (i == answermachinetext) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext)); final EditText input = new EditText(context); input.setText(Setting.getAnsweringmachineText()); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Setting.setAnsweringmachineText(input.getText().toString()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } else if (i == backgroundRow) { presentFragment(new WallpapersActivity()); } else if (i == askQuestionRow) { if (getParentActivity() == null) { return; } final TextView message = new TextView(getParentActivity()); message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo))); message.setTextSize(18); message.setLinkTextColor(Theme.MSG_LINK_TEXT_COLOR); // message.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont())); message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6)); message.setMovementMethod(new LinkMovementMethodMy()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setView(message); builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { performAskAQuestion(); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == sendLogsRow) { sendLogs(); } else if (i == clearLogsRow) { FileLog.cleanupLogs(); } else if (i == sendByEnterRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); boolean send = preferences.getBoolean("send_by_enter", false); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("send_by_enter", !send); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == ghostactivate) { boolean send = Setting.getGhostMode(); GhostPorotocol.toggleGhostPortocol(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == sendtyping) { boolean send = Setting.getSendTyping(); Setting.setSendTyping(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == anweringmachinactive) { boolean send = Setting.getAnsweringMachine(); Setting.setAnsweringMachine(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == showtimeago) { boolean send = Setting.getShowTimeAgo(); Setting.setShowTimeAgo(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == showdateshamsi) { boolean send = Setting.getDatePersian(); Setting.setDatePersian(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == tabletforceoverride) { boolean send = Setting.getTabletMode(); Setting.setTabletMode(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == raiseToSpeakRow) { MediaController.getInstance().toogleRaiseToSpeak(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canRaiseToSpeak()); } } else if (i == autoplayGifsRow) { MediaController.getInstance().toggleAutoplayGifs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canAutoplayGifs()); } } else if (i == saveToGalleryRow) { MediaController.getInstance().toggleSaveToGallery(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery()); } } else if (i == customTabsRow) { MediaController.getInstance().toggleCustomTabs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canCustomTabs()); } } else if (i == directShareRow) { MediaController.getInstance().toggleDirectShare(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canDirectShare()); } } else if (i == privacyRow) { presentFragment(new PrivacySettingsActivity()); } else if (i == languageRow) { presentFragment(new LanguageSelectActivity()); } else if (i == switchBackendButtonRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ConnectionsManager.getInstance().switchBackend(); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == telegramFaqRow) { Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl)); } else if (i == privacyPolicyRow) { Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl)); } else if (i == contactsReimportRow) { //not implemented } else if (i == contactsSortRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); builder.setItems(new CharSequence[]{ LocaleController.getString("Default", R.string.Default), LocaleController.getString("SortFirstName", R.string.SortFirstName), LocaleController.getString("SortLastName", R.string.SortLastName) }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("sortContactsBy", which); editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { if (getParentActivity() == null) { return; } final boolean maskValues[] = new boolean[6]; BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); int mask = 0; if (i == mobileDownloadRow) { mask = MediaController.getInstance().mobileDataDownloadMask; } else if (i == wifiDownloadRow) { mask = MediaController.getInstance().wifiDownloadMask; } else if (i == roamingDownloadRow) { mask = MediaController.getInstance().roamingDownloadMask; } builder.setApplyTopPadding(false); builder.setApplyBottomPadding(false); LinearLayout linearLayout = new LinearLayout(getParentActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); for (int a = 0; a < 6; a++) { String name = null; if (a == 0) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0; name = LocaleController.getString("AttachPhoto", R.string.AttachPhoto); } else if (a == 1) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0; name = LocaleController.getString("AttachAudio", R.string.AttachAudio); } else if (a == 2) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0; name = LocaleController.getString("AttachVideo", R.string.AttachVideo); } else if (a == 3) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0; name = LocaleController.getString("AttachDocument", R.string.AttachDocument); } else if (a == 4) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0; name = LocaleController.getString("AttachMusic", R.string.AttachMusic); } else if (a == 5) { if (Build.VERSION.SDK_INT >= 11) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0; name = LocaleController.getString("AttachGif", R.string.AttachGif); } else { continue; } } CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity()); checkBoxCell.setTag(a); checkBoxCell.setBackgroundResource(R.drawable.list_selector); linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); checkBoxCell.setText(name, "", maskValues[a], true); checkBoxCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBoxCell cell = (CheckBoxCell) v; int num = (Integer) cell.getTag(); maskValues[num] = !maskValues[num]; cell.setChecked(maskValues[num], true); } }); } BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1); cell.setBackgroundResource(R.drawable.list_selector); cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0); cell.setTextColor(Theme.AUTODOWNLOAD_SHEET_SAVE_TEXT_COLOR); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if (visibleDialog != null) { visibleDialog.dismiss(); } } catch (Exception e) { FileLog.e("tmessages", e); } int newMask = 0; for (int a = 0; a < 6; a++) { if (maskValues[a]) { if (a == 0) { newMask |= MediaController.AUTODOWNLOAD_MASK_PHOTO; } else if (a == 1) { newMask |= MediaController.AUTODOWNLOAD_MASK_AUDIO; } else if (a == 2) { newMask |= MediaController.AUTODOWNLOAD_MASK_VIDEO; } else if (a == 3) { newMask |= MediaController.AUTODOWNLOAD_MASK_DOCUMENT; } else if (a == 4) { newMask |= MediaController.AUTODOWNLOAD_MASK_MUSIC; } else if (a == 5) { newMask |= MediaController.AUTODOWNLOAD_MASK_GIF; } } } SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit(); if (i == mobileDownloadRow) { editor.putInt("mobileDataDownloadMask", newMask); MediaController.getInstance().mobileDataDownloadMask = newMask; } else if (i == wifiDownloadRow) { editor.putInt("wifiDownloadMask", newMask); MediaController.getInstance().wifiDownloadMask = newMask; } else if (i == roamingDownloadRow) { editor.putInt("roamingDownloadMask", newMask); MediaController.getInstance().roamingDownloadMask = newMask; } editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); builder.setCustomView(linearLayout); showDialog(builder.create()); } else if (i == usernameRow) { presentFragment(new ChangeUsernameActivity()); } else if (i == numberRow) { presentFragment(new ChangePhoneHelpActivity()); } else if (i == stickersRow) { presentFragment(new StickersActivity()); } else if (i == cacheRow) { presentFragment(new CacheControlActivity()); } } }); frameLayout.addView(actionBar); extraHeightView = new View(context); ViewProxy.setPivotY(extraHeightView, 0); extraHeightView.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88)); shadowView = new View(context); shadowView.setBackgroundResource(R.drawable.header_shadow); frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3)); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(21)); ViewProxy.setPivotX(avatarImage, 0); ViewProxy.setPivotY(avatarImage, 0); frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0)); avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); } } }); nameTextView = new TextView(context); nameTextView.setTextColor(0xffffffff); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); nameTextView.setLines(1); nameTextView.setMaxLines(1); nameTextView.setSingleLine(true); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setGravity(Gravity.LEFT); nameTextView.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont())); ViewProxy.setPivotX(nameTextView, 0); ViewProxy.setPivotY(nameTextView, 0); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0)); onlineTextView = new TextView(context); onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5)); onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); onlineTextView.setLines(1); onlineTextView.setMaxLines(1); onlineTextView.setSingleLine(true); onlineTextView.setEllipsize(TextUtils.TruncateAt.END); onlineTextView.setGravity(Gravity.LEFT); frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0)); writeButton = new ImageView(context); writeButton.setBackgroundResource(R.drawable.floating_user_states); writeButton.setImageResource(R.drawable.floating_camera); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); writeButton.setStateListAnimator(animator); writeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); } }); } frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0)); writeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); } if (user == null) { return; } boolean fullMenu = false; if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; fullMenu = true; } else { items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; } final boolean full = fullMenu; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { avatarUpdater.openCamera(); } else if (i == 1) { avatarUpdater.openGallery(); } else if (i == 2) { MessagesController.getInstance().deleteUserPhoto(null); } } }); showDialog(builder.create()); } }); needLayout(); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount == 0) { return; } int height = 0; View child = view.getChildAt(0); if (child != null) { if (firstVisibleItem == 0) { height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0); } if (extraHeight != height) { extraHeight = height; needLayout(); } } } }); return fragmentView; } @Override protected void onDialogDismiss(Dialog dialog) { MediaController.getInstance().checkAutodownloadSettings(); } @Override public void updatePhotoAtIndex(int index) { } @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { if (fileLocation == null) { return null; } TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { TLRPC.FileLocation photoBig = user.photo.photo_big; if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { int coords[] = new int[2]; avatarImage.getLocationInWindow(coords); PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = avatarImage; object.imageReceiver = avatarImage.getImageReceiver(); object.user_id = UserConfig.getClientUserId(); object.thumb = object.imageReceiver.getBitmap(); object.size = -1; object.radius = avatarImage.getImageReceiver().getRoundRadius(); object.scale = ViewProxy.getScaleX(avatarImage); return object; } } return null; } @Override public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { return null; } @Override public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { } @Override public void willHidePhotoViewer() { avatarImage.getImageReceiver().setVisible(true, true); } @Override public boolean isPhotoChecked(int index) { return false; } @Override public void setPhotoChecked(int index) { } @Override public boolean cancelButtonPressed() { return true; } @Override public void sendButtonPressed(int index) { } @Override public int getSelectedCount() { return 0; } public void performAskAQuestion() { final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int uid = preferences.getInt("support_id", 0); TLRPC.User supportUser = null; if (uid != 0) { supportUser = MessagesController.getInstance().getUser(uid); if (supportUser == null) { String userString = preferences.getString("support_user", null); if (userString != null) { try { byte[] datacentersBytes = Base64.decode(userString, Base64.DEFAULT); if (datacentersBytes != null) { SerializedData data = new SerializedData(datacentersBytes); supportUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false); if (supportUser != null && supportUser.id == 333000) { supportUser = null; } data.cleanup(); } } catch (Exception e) { FileLog.e("tmessages", e); supportUser = null; } } } } if (supportUser == null) { final ProgressDialog progressDialog = new ProgressDialog(getParentActivity()); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.show(); TLRPC.TL_help_getSupport req = new TLRPC.TL_help_getSupport(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { SharedPreferences.Editor editor = preferences.edit(); editor.putInt("support_id", res.user.id); SerializedData data = new SerializedData(); res.user.serializeToStream(data); editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)); editor.commit(); data.cleanup(); try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } ArrayList<TLRPC.User> users = new ArrayList<>(); users.add(res.user); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); MessagesController.getInstance().putUser(res.user, false); Bundle args = new Bundle(); args.putInt("user_id", res.user.id); presentFragment(new ChatActivity(args)); } }); } else { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } } }); } else { MessagesController.getInstance().putUser(supportUser, true); Bundle args = new Bundle(); args.putInt("user_id", supportUser.id); presentFragment(new ChatActivity(args)); } } @Override public void onActivityResultFragment(int requestCode, int resultCode, Intent data) { avatarUpdater.onActivityResult(requestCode, resultCode, data); } @Override public void saveSelfArgs(Bundle args) { if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) { args.putString("path", avatarUpdater.currentPicturePath); } } @Override public void restoreSelfArgs(Bundle args) { if (avatarUpdater != null) { avatarUpdater.currentPicturePath = args.getString("path"); } } @Override public void didReceivedNotification(int id, Object... args) { if (id == NotificationCenter.updateInterfaces) { int mask = (Integer) args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { updateUserData(); } } } @Override public void onResume() { super.onResume(); if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } updateUserData(); fixLayout(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); fixLayout(); } private void needLayout() { FrameLayout.LayoutParams layoutParams; int newTop = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight(); if (listView != null) { layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); if (layoutParams.topMargin != newTop) { layoutParams.topMargin = newTop; listView.setLayoutParams(layoutParams); ViewProxy.setTranslationY(extraHeightView, newTop); } } if (avatarImage != null) { float diff = extraHeight / (float) AndroidUtilities.dp(88); ViewProxy.setScaleY(extraHeightView, diff); ViewProxy.setTranslationY(shadowView, newTop + extraHeight); if (Build.VERSION.SDK_INT < 11) { layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); layoutParams.topMargin = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f); writeButton.setLayoutParams(layoutParams); } else { ViewProxy.setTranslationY(writeButton, (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f)); } final boolean setVisible = diff > 0.2f; boolean currentVisible = writeButton.getTag() == null; if (setVisible != currentVisible) { if (setVisible) { writeButton.setTag(null); writeButton.setVisibility(View.VISIBLE); } else { writeButton.setTag(0); } if (writeButtonAnimation != null) { AnimatorSetProxy old = writeButtonAnimation; writeButtonAnimation = null; old.cancel(); } writeButtonAnimation = new AnimatorSetProxy(); if (setVisible) { writeButtonAnimation.setInterpolator(new DecelerateInterpolator()); writeButtonAnimation.playTogether( ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 1.0f), ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 1.0f), ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 1.0f) ); } else { writeButtonAnimation.setInterpolator(new AccelerateInterpolator()); writeButtonAnimation.playTogether( ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 0.2f), ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 0.2f), ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 0.0f) ); } writeButtonAnimation.setDuration(150); writeButtonAnimation.addListener(new AnimatorListenerAdapterProxy() { @Override public void onAnimationEnd(Object animation) { if (writeButtonAnimation != null && writeButtonAnimation.equals(animation)) { writeButton.clearAnimation(); writeButton.setVisibility(setVisible ? View.VISIBLE : View.GONE); writeButtonAnimation = null; } } }); writeButtonAnimation.start(); } ViewProxy.setScaleX(avatarImage, (42 + 18 * diff) / 42.0f); ViewProxy.setScaleY(avatarImage, (42 + 18 * diff) / 42.0f); float avatarY = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() / 2.0f * (1.0f + diff) - 21 * AndroidUtilities.density + 27 * AndroidUtilities.density * diff; ViewProxy.setTranslationX(avatarImage, -AndroidUtilities.dp(47) * diff); ViewProxy.setTranslationY(avatarImage, (float) Math.ceil(avatarY)); ViewProxy.setTranslationX(nameTextView, -21 * AndroidUtilities.density * diff); ViewProxy.setTranslationY(nameTextView, (float) Math.floor(avatarY) - (float) Math.ceil(AndroidUtilities.density) + (float) Math.floor(7 * AndroidUtilities.density * diff)); ViewProxy.setTranslationX(onlineTextView, -21 * AndroidUtilities.density * diff); ViewProxy.setTranslationY(onlineTextView, (float) Math.floor(avatarY) + AndroidUtilities.dp(22) + (float) Math.floor(11 * AndroidUtilities.density) * diff); ViewProxy.setScaleX(nameTextView, 1.0f + 0.12f * diff); ViewProxy.setScaleY(nameTextView, 1.0f + 0.12f * diff); } } private void fixLayout() { if (fragmentView == null) { return; } fragmentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (fragmentView != null) { needLayout(); fragmentView.getViewTreeObserver().removeOnPreDrawListener(this); } return true; } }); } private void updateUserData() { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); TLRPC.FileLocation photo = null; TLRPC.FileLocation photoBig = null; if (user.photo != null) { photo = user.photo.photo_small; photoBig = user.photo.photo_big; } AvatarDrawable avatarDrawable = new AvatarDrawable(user, true); avatarDrawable.setColor(Theme.ACTION_BAR_MAIN_AVATAR_COLOR); if (avatarImage != null) { avatarImage.setImage(photo, "50_50", avatarDrawable); avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); nameTextView.setText(UserObject.getUserName(user)); onlineTextView.setText(LocaleController.getString("Online", R.string.Online)); avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } } private void sendLogs() { try { ArrayList<Uri> uris = new ArrayList<>(); File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null); File dir = new File(sdCard.getAbsolutePath() + "/logs"); File[] files = dir.listFiles(); for (File file : files) { uris.add(Uri.fromFile(file)); } if (uris.isEmpty()) { return; } Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{BuildVars.SEND_LOGS_EMAIL}); i.putExtra(Intent.EXTRA_SUBJECT, "last logs"); i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); getParentActivity().startActivityForResult(Intent.createChooser(i, "Select email application."), 500); } catch (Exception e) { e.printStackTrace(); } } private class ListAdapter extends BaseFragmentAdapter { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int i) { return i == textSizeRow || i == fontType || i == tabletforceoverride || i == anweringmachinactive || i == answermachinetext || i == sendtyping || i == showdateshamsi || i == showtimeago || i == ghostactivate || i == enableAnimationsRow || i == notificationRow || i == backgroundRow || i == numberRow || i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == autoplayGifsRow || i == privacyRow || i == wifiDownloadRow || i == mobileDownloadRow || i == clearLogsRow || i == roamingDownloadRow || i == languageRow || i == usernameRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsSortRow || i == contactsReimportRow || i == saveToGalleryRow || i == stickersRow || i == cacheRow || i == raiseToSpeakRow || i == privacyPolicyRow || i == customTabsRow || i == directShareRow; } @Override public int getCount() { return rowCount; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int type = getItemViewType(i); if (type == 0) { if (view == null) { view = new EmptyCell(mContext); } if (i == overscrollRow) { ((EmptyCell) view).setHeight(AndroidUtilities.dp(88)); } else { ((EmptyCell) view).setHeight(AndroidUtilities.dp(16)); } } else if (type == 1) { if (view == null) { view = new ShadowSectionCell(mContext); } } else if (type == 2) { if (view == null) { view = new TextSettingsCell(mContext); } TextSettingsCell textCell = (TextSettingsCell) view; if (i == textSizeRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int size = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16); textCell.setTextAndValue(LocaleController.getString("TextSize", R.string.TextSize), String.format("%d", size), true); } else if (i == fontType) { textCell.setTextAndValue( "نوع خط نوشتاری", Fonts.CurrentFont().replace("fonts/","").replace(".ttf",""), true); } else if (i == languageRow) { textCell.setTextAndValue(LocaleController.getString("Language", R.string.Language), LocaleController.getCurrentLanguageName(), true); } else if (i == contactsSortRow) { String value; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int sort = preferences.getInt("sortContactsBy", 0); if (sort == 0) { value = LocaleController.getString("Default", R.string.Default); } else if (sort == 1) { value = LocaleController.getString("FirstName", R.string.SortFirstName); } else { value = LocaleController.getString("LastName", R.string.SortLastName); } textCell.setTextAndValue(LocaleController.getString("SortBy", R.string.SortBy), value, true); } else if (i == notificationRow) { textCell.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds), true); } else if (i == backgroundRow) { textCell.setText(LocaleController.getString("ChatBackground", R.string.ChatBackground), true); } else if (i == answermachinetext) { textCell.setTextAndValue(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext), Setting.getAnsweringmachineText(), true); } else if (i == sendLogsRow) { textCell.setText("Send Logs", true); } else if (i == clearLogsRow) { textCell.setText("Clear Logs", true); } else if (i == askQuestionRow) { textCell.setText(LocaleController.getString("AskAQuestion", R.string.AskAQuestion), true); } else if (i == privacyRow) { textCell.setText(LocaleController.getString("PrivacySettings", R.string.PrivacySettings), true); } else if (i == switchBackendButtonRow) { textCell.setText("Switch Backend", true); } else if (i == telegramFaqRow) { textCell.setText(LocaleController.getString("TelegramFAQ", R.string.TelegramFaq), true); } else if (i == contactsReimportRow) { textCell.setText(LocaleController.getString("ImportContacts", R.string.ImportContacts), true); } else if (i == stickersRow) { textCell.setText(LocaleController.getString("Stickers", R.string.Stickers), true); } else if (i == cacheRow) { textCell.setText(LocaleController.getString("CacheSettings", R.string.CacheSettings), true); } else if (i == privacyPolicyRow) { textCell.setText(LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy), true); } } else if (type == 3) { if (view == null) { view = new TextCheckCell(mContext); } TextCheckCell textCell = (TextCheckCell) view; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); if (i == enableAnimationsRow) { textCell.setTextAndCheck(LocaleController.getString("EnableAnimations", R.string.EnableAnimations), preferences.getBoolean("view_animations", true), false); } else if (i == sendByEnterRow) { textCell.setTextAndCheck(LocaleController.getString("SendByEnter", R.string.SendByEnter), preferences.getBoolean("send_by_enter", false), false); } else if (i == ghostactivate) { textCell.setTextAndValueAndCheck(LocaleController.getString("GhostMode", R.string.GhostMode), LocaleController.getString("GhostModeInfo", R.string.GhostModeInfo), Setting.getGhostMode(), true, true); } else if (i == sendtyping) { textCell.setTextAndValueAndCheck(LocaleController.getString("HideTypingState", R.string.HideTypingState), LocaleController.getString("HideTypingStateinfo", R.string.HideTypingStateinfo), Setting.getSendTyping(), true, true); } else if (i == anweringmachinactive) { textCell.setTextAndValueAndCheck(LocaleController.getString("Answeringmachineenable", R.string.Answeringmachineenable), LocaleController.getString("Answeringmachineenableinfo", R.string.Answeringmachineenableinfo), Setting.getAnsweringMachine(), true, true); } else if (i == showtimeago) { textCell.setTextAndValueAndCheck(LocaleController.getString("showtimeago", R.string.showtimeago), LocaleController.getString("showtimeagoinfo", R.string.showtimeagoinfo), Setting.getShowTimeAgo(), true, true); } else if (i == showdateshamsi) { textCell.setTextAndValueAndCheck(LocaleController.getString("showshamsidate", R.string.Showshamsidate), LocaleController.getString("showshamsidateinfo", R.string.showshamsidateinfo), Setting.getDatePersian(), true, true); } else if (i == tabletforceoverride) { textCell.setTextAndValueAndCheck(LocaleController.getString("TabletMode", R.string.TabletMode), LocaleController.getString("tabletmodeinfo", R.string.tabletmodeinfo), Setting.getTabletMode(), true, true); } else if (i == saveToGalleryRow) { textCell.setTextAndCheck(LocaleController.getString("SaveToGallerySettings", R.string.SaveToGallerySettings), MediaController.getInstance().canSaveToGallery(), false); } else if (i == autoplayGifsRow) { textCell.setTextAndCheck(LocaleController.getString("AutoplayGifs", R.string.AutoplayGifs), MediaController.getInstance().canAutoplayGifs(), true); } else if (i == raiseToSpeakRow) { textCell.setTextAndCheck(LocaleController.getString("RaiseToSpeak", R.string.RaiseToSpeak), MediaController.getInstance().canRaiseToSpeak(), true); } else if (i == customTabsRow) { textCell.setTextAndValueAndCheck(LocaleController.getString("ChromeCustomTabs", R.string.ChromeCustomTabs), LocaleController.getString("ChromeCustomTabsInfo", R.string.ChromeCustomTabsInfo), MediaController.getInstance().canCustomTabs(), false, true); } else if (i == directShareRow) { textCell.setTextAndValueAndCheck(LocaleController.getString("DirectShare", R.string.DirectShare), LocaleController.getString("DirectShareInfo", R.string.DirectShareInfo), MediaController.getInstance().canDirectShare(), false, true); } } else if (type == 4) { if (view == null) { view = new HeaderCell(mContext); } if (i == answeringmachinerow2) { ((HeaderCell) view).setText(LocaleController.getString("AnsweringMachin", R.string.answeringmachine)); } else if (i == settingsSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("SETTINGS", R.string.SETTINGS)); } else if (i == supportSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("Support", R.string.Support)); } else if (i == messagesSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("MessagesSettings", R.string.MessagesSettings)); } else if (i == mediaDownloadSection2) { ((HeaderCell) view).setText(LocaleController.getString("AutomaticMediaDownload", R.string.AutomaticMediaDownload)); } else if (i == numberSectionRow) { ((HeaderCell) view).setText(LocaleController.getString("Info", R.string.Info)); } else if (i == newgeramsectionrow2) { ((HeaderCell) view).setText(LocaleController.getString("NewGramSettings", R.string.newgeramsettings)); } } else if (type == 5) { if (view == null) { view = new TextInfoCell(mContext); try { PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); int code = pInfo.versionCode / 10; String abi = ""; switch (pInfo.versionCode % 10) { case 0: abi = "arm"; break; case 1: abi = "arm-v7a"; break; case 2: abi = "x86"; break; case 3: abi = "universal"; break; } ((TextInfoCell) view).setText(String.format(Locale.US, "AriaGram for Android v%s (%d) %s", pInfo.versionName, code, abi)); } catch (Exception e) { FileLog.e("tmessages", e); } } } else if (type == 6) { if (view == null) { view = new TextDetailSettingsCell(mContext); } TextDetailSettingsCell textCell = (TextDetailSettingsCell) view; if (i == mobileDownloadRow || i == wifiDownloadRow || i == roamingDownloadRow) { int mask; String value; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); if (i == mobileDownloadRow) { value = LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData); mask = MediaController.getInstance().mobileDataDownloadMask; } else if (i == wifiDownloadRow) { value = LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi); mask = MediaController.getInstance().wifiDownloadMask; } else { value = LocaleController.getString("WhenRoaming", R.string.WhenRoaming); mask = MediaController.getInstance().roamingDownloadMask; } String text = ""; if ((mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) { text += LocaleController.getString("AttachPhoto", R.string.AttachPhoto); } if ((mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachAudio", R.string.AttachAudio); } if ((mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachVideo", R.string.AttachVideo); } if ((mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachDocument", R.string.AttachDocument); } if ((mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachMusic", R.string.AttachMusic); } if (Build.VERSION.SDK_INT >= 11) { if ((mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachGif", R.string.AttachGif); } } if (text.length() == 0) { text = LocaleController.getString("NoMediaAutoDownload", R.string.NoMediaAutoDownload); } textCell.setTextAndValue(value, text, true); } else if (i == numberRow) { TLRPC.User user = UserConfig.getCurrentUser(); String value; if (user != null && user.phone != null && user.phone.length() != 0) { value = PhoneFormat.getInstance().format("+" + user.phone); } else { value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown); } textCell.setTextAndValue(value, LocaleController.getString("Phone", R.string.Phone), true); } else if (i == usernameRow) { TLRPC.User user = UserConfig.getCurrentUser(); String value; if (user != null && user.username != null && user.username.length() != 0) { value = "@" + user.username; } else { value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty); } // Log.i("username",""+ user.username); textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), false); } } return view; } @Override public int getItemViewType(int i) { if (i == emptyRow || i == overscrollRow) { return 0; } if (i == answeringmachinerow || i == settingsSectionRow || i == newgeramsectionrow || i == supportSectionRow || i == messagesSectionRow || i == mediaDownloadSection || i == contactsSectionRow) { return 1; } else if (i == enableAnimationsRow || i == tabletforceoverride || i == showdateshamsi || i == showtimeago || i == anweringmachinactive || i == sendtyping || i == ghostactivate || i == sendByEnterRow || i == saveToGalleryRow || i == autoplayGifsRow || i == raiseToSpeakRow || i == customTabsRow || i == directShareRow) { return 3; } else if (i == notificationRow || i == answermachinetext || i == backgroundRow || i == askQuestionRow || i == sendLogsRow || i == privacyRow || i == clearLogsRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsReimportRow || i == textSizeRow || i == fontType || i == languageRow || i == contactsSortRow || i == stickersRow || i == cacheRow || i == privacyPolicyRow) { return 2; } else if (i == versionRow) { return 5; } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow || i == numberRow || i == usernameRow) { return 6; } else if (i == settingsSectionRow2 || i == answeringmachinerow2 || i == newgeramsectionrow2 || i == messagesSectionRow2 || i == supportSectionRow2 || i == numberSectionRow || i == mediaDownloadSection2) { return 4; } else { return 2; } } @Override public int getViewTypeCount() { return 7; } @Override public boolean isEmpty() { return false; } } }
Fakkar/TeligramFars
TMessagesProj/src/main/java/com/teligramfars/ui/SettingsActivity.java
Java
gpl-2.0
80,162
/*************************************************************************** Copyright (C) 2014-2015 by Nick Thijssen <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. ***************************************************************************/ using test.Controls; namespace test { partial class TestTransform { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.bottomPanel = new System.Windows.Forms.FlowLayoutPanel(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.xNumeric = new System.Windows.Forms.NumericUpDown(); this.yNumeric = new System.Windows.Forms.NumericUpDown(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.wNumeric = new System.Windows.Forms.NumericUpDown(); this.hNumeric = new System.Windows.Forms.NumericUpDown(); this.positionLabel = new System.Windows.Forms.Label(); this.sizeLabel = new System.Windows.Forms.Label(); this.rotationLabel = new System.Windows.Forms.Label(); this.positionalalignmentLabel = new System.Windows.Forms.Label(); this.Alignment = new test.Controls.AlignmentBox(); this.Rotation = new test.Controls.RotationBox(); this.bottomPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.xNumeric)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.yNumeric)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.wNumeric)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.hNumeric)).BeginInit(); this.SuspendLayout(); // // bottomPanel // this.bottomPanel.AutoSize = true; this.bottomPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.bottomPanel.Controls.Add(this.cancelButton); this.bottomPanel.Controls.Add(this.okButton); this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.bottomPanel.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; this.bottomPanel.Location = new System.Drawing.Point(0, 230); this.bottomPanel.Name = "bottomPanel"; this.bottomPanel.Size = new System.Drawing.Size(364, 29); this.bottomPanel.TabIndex = 0; // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(286, 3); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 1; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // okButton // this.okButton.Location = new System.Drawing.Point(205, 3); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 0; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel2, 1, 0); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 1, 1); this.tableLayoutPanel1.Controls.Add(this.positionLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.sizeLabel, 0, 1); this.tableLayoutPanel1.Controls.Add(this.rotationLabel, 0, 2); this.tableLayoutPanel1.Controls.Add(this.positionalalignmentLabel, 0, 3); this.tableLayoutPanel1.Controls.Add(this.Alignment, 1, 3); this.tableLayoutPanel1.Controls.Add(this.Rotation, 1, 2); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 5; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(364, 230); this.tableLayoutPanel1.TabIndex = 0; // // flowLayoutPanel2 // this.flowLayoutPanel2.AutoSize = true; this.flowLayoutPanel2.Controls.Add(this.xNumeric); this.flowLayoutPanel2.Controls.Add(this.yNumeric); this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel2.Location = new System.Drawing.Point(107, 0); this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(257, 26); this.flowLayoutPanel2.TabIndex = 7; // // xNumeric // this.xNumeric.DecimalPlaces = 3; this.xNumeric.Location = new System.Drawing.Point(3, 3); this.xNumeric.Name = "xNumeric"; this.xNumeric.Size = new System.Drawing.Size(120, 20); this.xNumeric.TabIndex = 0; // // yNumeric // this.yNumeric.DecimalPlaces = 3; this.yNumeric.Location = new System.Drawing.Point(129, 3); this.yNumeric.Name = "yNumeric"; this.yNumeric.Size = new System.Drawing.Size(120, 20); this.yNumeric.TabIndex = 1; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.Controls.Add(this.wNumeric); this.flowLayoutPanel1.Controls.Add(this.hNumeric); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(107, 26); this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(257, 26); this.flowLayoutPanel1.TabIndex = 1; // // wNumeric // this.wNumeric.DecimalPlaces = 3; this.wNumeric.Location = new System.Drawing.Point(3, 3); this.wNumeric.Name = "wNumeric"; this.wNumeric.Size = new System.Drawing.Size(120, 20); this.wNumeric.TabIndex = 1; // // hNumeric // this.hNumeric.DecimalPlaces = 3; this.hNumeric.Location = new System.Drawing.Point(129, 3); this.hNumeric.Name = "hNumeric"; this.hNumeric.Size = new System.Drawing.Size(120, 20); this.hNumeric.TabIndex = 0; // // positionLabel // this.positionLabel.AutoSize = true; this.positionLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.positionLabel.Location = new System.Drawing.Point(3, 0); this.positionLabel.Name = "positionLabel"; this.positionLabel.Size = new System.Drawing.Size(101, 26); this.positionLabel.TabIndex = 0; this.positionLabel.Text = "Position"; this.positionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // sizeLabel // this.sizeLabel.AutoSize = true; this.sizeLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.sizeLabel.Location = new System.Drawing.Point(3, 26); this.sizeLabel.Name = "sizeLabel"; this.sizeLabel.Size = new System.Drawing.Size(101, 26); this.sizeLabel.TabIndex = 6; this.sizeLabel.Text = "Size"; this.sizeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // rotationLabel // this.rotationLabel.AutoSize = true; this.rotationLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.rotationLabel.Location = new System.Drawing.Point(3, 52); this.rotationLabel.Name = "rotationLabel"; this.rotationLabel.Size = new System.Drawing.Size(101, 78); this.rotationLabel.TabIndex = 5; this.rotationLabel.Text = "Rotation"; this.rotationLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // positionalalignmentLabel // this.positionalalignmentLabel.AutoSize = true; this.positionalalignmentLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.positionalalignmentLabel.Location = new System.Drawing.Point(3, 130); this.positionalalignmentLabel.Name = "positionalalignmentLabel"; this.positionalalignmentLabel.Size = new System.Drawing.Size(101, 78); this.positionalalignmentLabel.TabIndex = 4; this.positionalalignmentLabel.Text = "Positional Alignment"; this.positionalalignmentLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // Alignment // this.Alignment.Alignment = OBS.ObsAlignment.Center; this.Alignment.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.Alignment.AutoSize = true; this.Alignment.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Alignment.Location = new System.Drawing.Point(110, 133); this.Alignment.Name = "Alignment"; this.Alignment.Size = new System.Drawing.Size(72, 72); this.Alignment.TabIndex = 2; // // Rotation // this.Rotation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.Rotation.Debug = false; this.Rotation.Location = new System.Drawing.Point(110, 55); this.Rotation.MaximumSize = new System.Drawing.Size(400, 400); this.Rotation.MinimumSize = new System.Drawing.Size(50, 50); this.Rotation.Name = "Rotation"; this.Rotation.Rotation = 0; this.Rotation.Size = new System.Drawing.Size(72, 72); this.Rotation.SnapAngle = 45; this.Rotation.SnapToAngle = true; this.Rotation.SnapTolerance = 10; this.Rotation.TabIndex = 3; // // TestTransform // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(364, 259); this.ControlBox = false; this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.bottomPanel); this.Name = "TestTransform"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Edit Transform"; this.bottomPanel.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.flowLayoutPanel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.xNumeric)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.yNumeric)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.wNumeric)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.hNumeric)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.FlowLayoutPanel bottomPanel; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.NumericUpDown wNumeric; private System.Windows.Forms.NumericUpDown hNumeric; private System.Windows.Forms.Label positionLabel; private System.Windows.Forms.Label sizeLabel; private System.Windows.Forms.Label rotationLabel; private System.Windows.Forms.Label positionalalignmentLabel; private AlignmentBox Alignment; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.NumericUpDown xNumeric; private System.Windows.Forms.NumericUpDown yNumeric; private RotationBox Rotation; } }
GoaLitiuM/libobs-sharp
test/TestTransform.Designer.cs
C#
gpl-2.0
13,346
/* * Copyright (C) 2005-2013 Junjiro R. Okajima * * This program, aufs is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * all header files */ #ifndef __AUFS_H__ #define __AUFS_H__ #ifdef __KERNEL__ #define AuStub(type, name, body, ...) \ static inline type name(__VA_ARGS__) { body; } #define AuStubVoid(name, ...) \ AuStub(void, name, , __VA_ARGS__) #define AuStubInt0(name, ...) \ AuStub(int, name, return 0, __VA_ARGS__) #include "debug.h" #include "branch.h" #include "cpup.h" #include "dcsub.h" #include "dbgaufs.h" #include "dentry.h" #include "dir.h" #include "dynop.h" #include "file.h" #include "fstype.h" #include "inode.h" #include "loop.h" #include "module.h" #include "opts.h" #include "rwsem.h" #include "spl.h" #include "super.h" #include "sysaufs.h" #include "vfsub.h" #include "whout.h" #include "wkq.h" #endif /* __KERNEL__ */ #endif /* __AUFS_H__ */
gamvrosi/duet
linux-3.13.6+duet/ubuntu/aufs/aufs.h
C
gpl-2.0
1,473
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.similarity; import java.util.Iterator; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.SimpleAttributes; import com.rapidminer.example.set.AbstractExampleReader; import com.rapidminer.example.set.AbstractExampleSet; import com.rapidminer.example.set.MappedExampleSet; import com.rapidminer.example.table.AttributeFactory; import com.rapidminer.example.table.DoubleArrayDataRow; import com.rapidminer.example.table.ExampleTable; import com.rapidminer.example.table.NominalMapping; import com.rapidminer.tools.Ontology; import com.rapidminer.tools.math.similarity.DistanceMeasure; /** * This similarity based example set is used for the operator * {@link ExampleSet2SimilarityExampleSet}. * * @author Ingo Mierswa * @version $Id: SimilarityExampleSet.java,v 1.1 2008/09/08 18:53:49 ingomierswa Exp $ */ public class SimilarityExampleSet extends AbstractExampleSet { private static final long serialVersionUID = 4757975818441794105L; private static class IndexExampleReader extends AbstractExampleReader { private int index = 0; private ExampleSet exampleSet; public IndexExampleReader(ExampleSet exampleSet) { this.exampleSet = exampleSet; } public boolean hasNext() { return index < exampleSet.size() - 1; } public Example next() { Example example = exampleSet.getExample(index); index++; return example; } } private ExampleSet parent; private Attribute parentIdAttribute; private Attributes attributes; private DistanceMeasure measure; public SimilarityExampleSet(ExampleSet parent, DistanceMeasure measure) { this.parent = parent; this.parentIdAttribute = parent.getAttributes().getId(); this.attributes = new SimpleAttributes(); Attribute firstIdAttribute = null; Attribute secondIdAttribute = null; if (parentIdAttribute.isNominal()) { firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NOMINAL); secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NOMINAL); } else { firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NUMERICAL); secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NUMERICAL); } this.attributes.addRegular(firstIdAttribute); this.attributes.addRegular(secondIdAttribute); firstIdAttribute.setTableIndex(0); secondIdAttribute.setTableIndex(1); // copying mapping of original id attribute if (parentIdAttribute.isNominal()) { NominalMapping mapping = parentIdAttribute.getMapping(); firstIdAttribute.setMapping(mapping); secondIdAttribute.setMapping(mapping); } String name = "SIMILARITY"; if (measure.isDistance()) { name = "DISTANCE"; } Attribute similarityAttribute = AttributeFactory.createAttribute(name, Ontology.REAL); this.attributes.addRegular(similarityAttribute); similarityAttribute.setTableIndex(2); this.measure = measure; } public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof MappedExampleSet)) return false; SimilarityExampleSet other = (SimilarityExampleSet)o; if (!this.measure.getClass().equals(other.measure.getClass())) return false; return true; } public int hashCode() { return super.hashCode() ^ this.measure.getClass().hashCode(); } public Attributes getAttributes() { return this.attributes; } public Example getExample(int index) { int firstIndex = index / this.parent.size(); int secondIndex = index % this.parent.size(); Example firstExample = this.parent.getExample(firstIndex); Example secondExample = this.parent.getExample(secondIndex); double[] data = new double[3]; data[0] = firstExample.getValue(parentIdAttribute); data[1] = secondExample.getValue(parentIdAttribute); if (measure.isDistance()) data[2] = measure.calculateDistance(firstExample, secondExample); else data[2] = measure.calculateSimilarity(firstExample, secondExample); return new Example(new DoubleArrayDataRow(data), this); } public Iterator<Example> iterator() { return new IndexExampleReader(this); } public ExampleTable getExampleTable() { return null;//this.parent.getExampleTable(); } public int size() { return this.parent.size() * this.parent.size(); } }
ntj/ComplexRapidMiner
src/com/rapidminer/operator/similarity/SimilarityExampleSet.java
Java
gpl-2.0
5,564
<?php // // ZoneMinder web action file // Copyright (C) 2019 ZoneMinder LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // Event scope actions, view permissions only required if ( !canView('Events') ) { ZM\Warning('You do not have permission to view Events.'); return; } if ( isset($_REQUEST['object']) and ( $_REQUEST['object'] == 'filter' ) ) { if ( $action == 'addterm' ) { $_REQUEST['filter'] = addFilterTerm($_REQUEST['filter'], $_REQUEST['line']); } elseif ( $action == 'delterm' ) { $_REQUEST['filter'] = delFilterTerm($_REQUEST['filter'], $_REQUEST['line']); } else if ( canEdit('Events') ) { require_once('includes/Filter.php'); $filter = new ZM\Filter($_REQUEST['Id']); if ( $action == 'delete' ) { if ( !empty($_REQUEST['Id']) ) { if ( $filter->Background() ) { $filter->control('stop'); } $filter->delete(); } else { ZM\Error('No filter id passed when deleting'); } } else if ( ( $action == 'Save' ) or ( $action == 'SaveAs' ) or ( $action == 'execute' ) ) { $sql = ''; $_REQUEST['filter']['Query']['sort_field'] = validStr($_REQUEST['filter']['Query']['sort_field']); $_REQUEST['filter']['Query']['sort_asc'] = validStr($_REQUEST['filter']['Query']['sort_asc']); $_REQUEST['filter']['Query']['limit'] = validInt($_REQUEST['filter']['Query']['limit']); $_REQUEST['filter']['AutoCopy'] = empty($_REQUEST['filter']['AutoCopy']) ? 0 : 1; $_REQUEST['filter']['AutoMove'] = empty($_REQUEST['filter']['AutoMove']) ? 0 : 1; $_REQUEST['filter']['AutoArchive'] = empty($_REQUEST['filter']['AutoArchive']) ? 0 : 1; $_REQUEST['filter']['AutoVideo'] = empty($_REQUEST['filter']['AutoVideo']) ? 0 : 1; $_REQUEST['filter']['AutoUpload'] = empty($_REQUEST['filter']['AutoUpload']) ? 0 : 1; $_REQUEST['filter']['AutoEmail'] = empty($_REQUEST['filter']['AutoEmail']) ? 0 : 1; $_REQUEST['filter']['AutoMessage'] = empty($_REQUEST['filter']['AutoMessage']) ? 0 : 1; $_REQUEST['filter']['AutoExecute'] = empty($_REQUEST['filter']['AutoExecute']) ? 0 : 1; $_REQUEST['filter']['AutoDelete'] = empty($_REQUEST['filter']['AutoDelete']) ? 0 : 1; $_REQUEST['filter']['UpdateDiskSpace'] = empty($_REQUEST['filter']['UpdateDiskSpace']) ? 0 : 1; $_REQUEST['filter']['Background'] = empty($_REQUEST['filter']['Background']) ? 0 : 1; $_REQUEST['filter']['Concurrent'] = empty($_REQUEST['filter']['Concurrent']) ? 0 : 1; $changes = $filter->changes($_REQUEST['filter']); ZM\Logger::Debug('Changes: ' . print_r($changes,true)); if ( $_REQUEST['Id'] and ( $action == 'Save' ) ) { if ( $filter->Background() ) $filter->control('stop'); $filter->save($changes); } else { if ( $action == 'execute' ) { if ( count($changes) ) { $filter->Name('_TempFilter'.time()); $filter->Id(null); } } else if ( $action == 'SaveAs' ) { $filter->Id(null); } $filter->save($changes); // We update the request id so that the newly saved filter is auto-selected $_REQUEST['Id'] = $filter->Id(); } if ( $action == 'execute' ) { $filter->execute(); if ( count($changes) ) $filter->delete(); $view = 'events'; } else if ( $filter->Background() ) { $filter->control('start'); } $redirect = '?view=filter&Id='.$filter->Id(); } else if ( $action == 'control' ) { if ( $_REQUEST['command'] == 'start' or $_REQUEST['command'] == 'stop' or $_REQUEST['command'] == 'restart' ) { $filter->control($_REQUEST['command'], $_REQUEST['ServerId']); } else { ZM\Error('Invalid command for filter ('.$_REQUEST['command'].')'); } } // end if save or execute } // end if canEdit(Events) } // end if object == filter ?>
ZoneMinder/ZoneMinder
web/includes/actions/filter.php
PHP
gpl-2.0
4,624
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* NetworkManager system settings service * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Copyright (C) 2007 - 2011 Red Hat, Inc. * Copyright (C) 2008 Novell, Inc. */ #ifndef NM_SYSTEM_CONFIG_INTERFACE_H #define NM_SYSTEM_CONFIG_INTERFACE_H #include <glib.h> #include <glib-object.h> #include <nm-connection.h> #include <nm-settings-connection.h> G_BEGIN_DECLS #define PLUGIN_PRINT(pname, fmt, args...) \ { g_message (" " pname ": " fmt, ##args); } #define PLUGIN_WARN(pname, fmt, args...) \ { g_warning (" " pname ": " fmt, ##args); } /* Plugin's factory function that returns a GObject that implements * NMSystemConfigInterface. */ GObject * nm_system_config_factory (void); #define NM_TYPE_SYSTEM_CONFIG_INTERFACE (nm_system_config_interface_get_type ()) #define NM_SYSTEM_CONFIG_INTERFACE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NM_TYPE_SYSTEM_CONFIG_INTERFACE, NMSystemConfigInterface)) #define NM_IS_SYSTEM_CONFIG_INTERFACE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NM_TYPE_SYSTEM_CONFIG_INTERFACE)) #define NM_SYSTEM_CONFIG_INTERFACE_GET_INTERFACE(obj) (G_TYPE_INSTANCE_GET_INTERFACE ((obj), NM_TYPE_SYSTEM_CONFIG_INTERFACE, NMSystemConfigInterface)) #define NM_SYSTEM_CONFIG_INTERFACE_NAME "name" #define NM_SYSTEM_CONFIG_INTERFACE_INFO "info" #define NM_SYSTEM_CONFIG_INTERFACE_CAPABILITIES "capabilities" #define NM_SYSTEM_CONFIG_INTERFACE_HOSTNAME "hostname" #define NM_SYSTEM_CONFIG_INTERFACE_UNMANAGED_SPECS_CHANGED "unmanaged-specs-changed" #define NM_SYSTEM_CONFIG_INTERFACE_UNRECOGNIZED_SPECS_CHANGED "unrecognized-specs-changed" #define NM_SYSTEM_CONFIG_INTERFACE_CONNECTION_ADDED "connection-added" typedef enum { NM_SYSTEM_CONFIG_INTERFACE_CAP_NONE = 0x00000000, NM_SYSTEM_CONFIG_INTERFACE_CAP_MODIFY_CONNECTIONS = 0x00000001, NM_SYSTEM_CONFIG_INTERFACE_CAP_MODIFY_HOSTNAME = 0x00000002 /* When adding more capabilities, be sure to update the "Capabilities" * property max value in nm-system-config-interface.c. */ } NMSystemConfigInterfaceCapabilities; typedef enum { NM_SYSTEM_CONFIG_INTERFACE_PROP_FIRST = 0x1000, NM_SYSTEM_CONFIG_INTERFACE_PROP_NAME = NM_SYSTEM_CONFIG_INTERFACE_PROP_FIRST, NM_SYSTEM_CONFIG_INTERFACE_PROP_INFO, NM_SYSTEM_CONFIG_INTERFACE_PROP_CAPABILITIES, NM_SYSTEM_CONFIG_INTERFACE_PROP_HOSTNAME, } NMSystemConfigInterfaceProp; typedef struct _NMSystemConfigInterface NMSystemConfigInterface; struct _NMSystemConfigInterface { GTypeInterface g_iface; /* Called when the plugin is loaded to initialize it */ void (*init) (NMSystemConfigInterface *config); /* Returns a GSList of NMSettingsConnection objects that represent * connections the plugin knows about. The returned list is freed by the * system settings service. */ GSList * (*get_connections) (NMSystemConfigInterface *config); /* Requests that the plugin load/reload a single connection, if it * recognizes the filename. Returns success or failure. */ gboolean (*load_connection) (NMSystemConfigInterface *config, const char *filename); /* Requests that the plugin reload all connection files from disk, * and emit signals reflecting new, changed, and removed connections. */ void (*reload_connections) (NMSystemConfigInterface *config); /* * Return a string list of specifications of devices which NetworkManager * should not manage. Returned list will be freed by the system settings * service, and each element must be allocated using g_malloc() or its * variants (g_strdup, g_strdup_printf, etc). * * Each string in the list must be in one of the formats recognized by * nm_device_spec_match_list(). */ GSList * (*get_unmanaged_specs) (NMSystemConfigInterface *config); /* * Return a string list of specifications of devices for which at least * one non-NetworkManager-based configuration is defined. Returned list * will be freed by the system settings service, and each element must be * allocated using g_malloc() or its variants (g_strdup, g_strdup_printf, * etc). * * Each string in the list must be in one of the formats recognized by * nm_device_spec_match_list(). */ GSList * (*get_unrecognized_specs) (NMSystemConfigInterface *config); /* * Initialize the plugin-specific connection and return a new * NMSettingsConnection subclass that contains the same settings as the * original connection. The connection should only be saved to backing * storage if @save_to_disk is TRUE. The returned object is owned by the * plugin and must be referenced by the owner if necessary. */ NMSettingsConnection * (*add_connection) (NMSystemConfigInterface *config, NMConnection *connection, gboolean save_to_disk, GError **error); /* Signals */ /* Emitted when a new connection has been found by the plugin */ void (*connection_added) (NMSystemConfigInterface *config, NMSettingsConnection *connection); /* Emitted when the list of unmanaged device specifications changes */ void (*unmanaged_specs_changed) (NMSystemConfigInterface *config); /* Emitted when the list of devices with unrecognized connections changes */ void (*unrecognized_specs_changed) (NMSystemConfigInterface *config); }; GType nm_system_config_interface_get_type (void); void nm_system_config_interface_init (NMSystemConfigInterface *config, gpointer unused); GSList *nm_system_config_interface_get_connections (NMSystemConfigInterface *config); gboolean nm_system_config_interface_load_connection (NMSystemConfigInterface *config, const char *filename); void nm_system_config_interface_reload_connections (NMSystemConfigInterface *config); GSList *nm_system_config_interface_get_unmanaged_specs (NMSystemConfigInterface *config); GSList *nm_system_config_interface_get_unrecognized_specs (NMSystemConfigInterface *config); NMSettingsConnection *nm_system_config_interface_add_connection (NMSystemConfigInterface *config, NMConnection *connection, gboolean save_to_disk, GError **error); G_END_DECLS #endif /* NM_SYSTEM_CONFIG_INTERFACE_H */
heftig/NetworkManager
src/settings/nm-system-config-interface.h
C
gpl-2.0
7,206
/* * 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. */ #ifndef __STACKMAP6_H__ #define __STACKMAP6_H__ #include <stdlib.h> #include <string.h> #include <assert.h> #include "../base/stackmap_x.h" //Constant for parsing StackMapTable attribute enum StackMapTableItems { ITEM_TOP = 0, ITEM_INTEGER = 1, ITEM_FLOAT = 2, ITEM_DOUBLE = 3, ITEM_LONG = 4, ITEM_NULL = 5, ITEM_UNINITIALIZEDTHIS = 6, ITEM_OBJECT = 7, ITEM_UNINITIALIZED = 8 }; //StackMapElement structure represens recorded verification types //it's read from class file StackMapTable attribute struct StackmapElement_6 { //list of IncomingType constraint _SmConstant const_val; }; //WorkMapElement structure represent an element of the workmap vector -- vector of the derived types //in Java6 verification type might be constant (or known) only struct WorkmapElement_6 { //the value _SmConstant const_val; //either a constant (known-type) //// Java5 anachonisms //// void setJsrModified() {}; int isJsrModified() { return 1;}; SmConstant getAnyPossibleValue() { return const_val; } SmConstant getConst() { return const_val; } }; //WorkmapElement type with some constructors struct _WorkmapElement_6 : WorkmapElement_6 { _WorkmapElement_6(WorkmapElement_6 other) { const_val = other.const_val; } _WorkmapElement_6(SmConstant c) { const_val = c; } }; //Store stackmap data for the given instruction // the list is used to organize storing Props as a HashTable struct PropsHead_6 : public PropsHeadBase { typedef MapHead<StackmapElement_6> StackmapHead; //possible properties StackmapHead stackmap; //get stackmap stored here StackmapHead *getStackmap() { return &stackmap; } }; #endif
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/vm/vmcore/src/verifier-3363/java6/stackmap_6.h
C
gpl-2.0
2,640
/* * Copyright (C) 2011-2012 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "CoreAudioDevice.h" #include "CoreAudioAEHAL.h" #include "CoreAudioChannelLayout.h" #include "CoreAudioHardware.h" #include "utils/log.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CCoreAudioDevice ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CCoreAudioDevice::CCoreAudioDevice() : m_Started (false ), m_pSource (NULL ), m_DeviceId (0 ), m_MixerRestore (-1 ), m_IoProc (NULL ), m_ObjectListenerProc (NULL ), m_SampleRateRestore (0.0f ), m_HogPid (-1 ), m_frameSize (0 ), m_OutputBufferIndex (0 ), m_BufferSizeRestore (0 ) { } CCoreAudioDevice::CCoreAudioDevice(AudioDeviceID deviceId) : m_Started (false ), m_pSource (NULL ), m_DeviceId (deviceId ), m_MixerRestore (-1 ), m_IoProc (NULL ), m_ObjectListenerProc (NULL ), m_SampleRateRestore (0.0f ), m_HogPid (-1 ), m_frameSize (0 ), m_OutputBufferIndex (0 ), m_BufferSizeRestore (0 ) { } CCoreAudioDevice::~CCoreAudioDevice() { Close(); } bool CCoreAudioDevice::Open(AudioDeviceID deviceId) { m_DeviceId = deviceId; m_BufferSizeRestore = GetBufferSize(); return true; } void CCoreAudioDevice::Close() { if (!m_DeviceId) return; // Stop the device if it was started Stop(); // Unregister the IOProc if we have one if (m_IoProc) SetInputSource(NULL, 0, 0); SetHogStatus(false); CCoreAudioHardware::SetAutoHogMode(false); if (m_MixerRestore > -1) // We changed the mixer status SetMixingSupport((m_MixerRestore ? true : false)); m_MixerRestore = -1; if (m_SampleRateRestore != 0.0f) SetNominalSampleRate(m_SampleRateRestore); if (m_BufferSizeRestore && m_BufferSizeRestore != GetBufferSize()) { SetBufferSize(m_BufferSizeRestore); m_BufferSizeRestore = 0; } m_IoProc = NULL; m_pSource = NULL; m_DeviceId = 0; m_ObjectListenerProc = NULL; } void CCoreAudioDevice::Start() { if (!m_DeviceId || m_Started) return; OSStatus ret = AudioDeviceStart(m_DeviceId, m_IoProc); if (ret) CLog::Log(LOGERROR, "CCoreAudioDevice::Start: " "Unable to start device. Error = %s", GetError(ret).c_str()); else m_Started = true; } void CCoreAudioDevice::Stop() { if (!m_DeviceId || !m_Started) return; OSStatus ret = AudioDeviceStop(m_DeviceId, m_IoProc); if (ret) CLog::Log(LOGERROR, "CCoreAudioDevice::Stop: " "Unable to stop device. Error = %s", GetError(ret).c_str()); m_Started = false; } void CCoreAudioDevice::RemoveObjectListenerProc(AudioObjectPropertyListenerProc callback, void* pClientData) { if (!m_DeviceId) return; AudioObjectPropertyAddress audioProperty; audioProperty.mSelector = kAudioObjectPropertySelectorWildcard; audioProperty.mScope = kAudioObjectPropertyScopeWildcard; audioProperty.mElement = kAudioObjectPropertyElementWildcard; OSStatus ret = AudioObjectRemovePropertyListener(m_DeviceId, &audioProperty, callback, pClientData); if (ret) { CLog::Log(LOGERROR, "CCoreAudioDevice::RemoveObjectListenerProc: " "Unable to set ObjectListener callback. Error = %s", GetError(ret).c_str()); } m_ObjectListenerProc = NULL; } bool CCoreAudioDevice::SetObjectListenerProc(AudioObjectPropertyListenerProc callback, void* pClientData) { // Allow only one ObjectListener at a time if (!m_DeviceId || m_ObjectListenerProc) return false; AudioObjectPropertyAddress audioProperty; audioProperty.mSelector = kAudioObjectPropertySelectorWildcard; audioProperty.mScope = kAudioObjectPropertyScopeWildcard; audioProperty.mElement = kAudioObjectPropertyElementWildcard; OSStatus ret = AudioObjectAddPropertyListener(m_DeviceId, &audioProperty, callback, pClientData); if (ret) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetObjectListenerProc: " "Unable to remove ObjectListener callback. Error = %s", GetError(ret).c_str()); return false; } m_ObjectListenerProc = callback; return true; } bool CCoreAudioDevice::SetInputSource(ICoreAudioSource* pSource, unsigned int frameSize, unsigned int outputBufferIndex) { m_pSource = pSource; m_frameSize = frameSize; m_OutputBufferIndex = outputBufferIndex; if (pSource) return AddIOProc(); else return RemoveIOProc(); } bool CCoreAudioDevice::AddIOProc() { // Allow only one IOProc at a time if (!m_DeviceId || m_IoProc) return false; OSStatus ret = AudioDeviceCreateIOProcID(m_DeviceId, DirectRenderCallback, this, &m_IoProc); if (ret) { CLog::Log(LOGERROR, "CCoreAudioDevice::AddIOProc: " "Unable to add IOProc. Error = %s", GetError(ret).c_str()); m_IoProc = NULL; return false; } Start(); return true; } bool CCoreAudioDevice::RemoveIOProc() { if (!m_DeviceId || !m_IoProc) return false; Stop(); OSStatus ret = AudioDeviceDestroyIOProcID(m_DeviceId, m_IoProc); if (ret) CLog::Log(LOGERROR, "CCoreAudioDevice::RemoveIOProc: " "Unable to remove IOProc. Error = %s", GetError(ret).c_str()); m_IoProc = NULL; // Clear the reference no matter what m_pSource = NULL; Sleep(100); return true; } std::string CCoreAudioDevice::GetName() { if (!m_DeviceId) return NULL; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyDeviceName; UInt32 propertySize; OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize); if (ret != noErr) return NULL; std::string name = ""; char *buff = new char[propertySize + 1]; buff[propertySize] = 0x00; ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, buff); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::GetName: " "Unable to get device name - id: 0x%04x. Error = %s", (uint)m_DeviceId, GetError(ret).c_str()); } else { name = buff; } delete buff; return name; } UInt32 CCoreAudioDevice::GetTotalOutputChannels() { UInt32 channels = 0; if (!m_DeviceId) return channels; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyStreamConfiguration; UInt32 size = 0; OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &size); if (ret != noErr) return channels; AudioBufferList* pList = (AudioBufferList*)malloc(size); ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, pList); if (ret == noErr) { for(UInt32 buffer = 0; buffer < pList->mNumberBuffers; ++buffer) channels += pList->mBuffers[buffer].mNumberChannels; } else { CLog::Log(LOGERROR, "CCoreAudioDevice::GetTotalOutputChannels: " "Unable to get total device output channels - id: 0x%04x. Error = %s", (uint)m_DeviceId, GetError(ret).c_str()); } free(pList); return channels; } bool CCoreAudioDevice::GetStreams(AudioStreamIdList* pList) { if (!pList || !m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyStreams; UInt32 propertySize = 0; OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize); if (ret != noErr) return false; UInt32 streamCount = propertySize / sizeof(AudioStreamID); AudioStreamID* pStreamList = new AudioStreamID[streamCount]; ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pStreamList); if (ret == noErr) { for (UInt32 stream = 0; stream < streamCount; stream++) pList->push_back(pStreamList[stream]); } delete[] pStreamList; return ret == noErr; } bool CCoreAudioDevice::IsRunning() { AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyDeviceIsRunning; UInt32 isRunning = 0; UInt32 propertySize = sizeof(isRunning); OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &isRunning); if (ret != noErr) return false; return isRunning != 0; } bool CCoreAudioDevice::SetHogStatus(bool hog) { // According to Jeff Moore (Core Audio, Apple), Setting kAudioDevicePropertyHogMode // is a toggle and the only way to tell if you do get hog mode is to compare // the returned pid against getpid, if the match, you have hog mode, if not you don't. if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyHogMode; if (hog) { // Not already set if (m_HogPid == -1) { OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(m_HogPid), &m_HogPid); // even if setting hogmode was successfull our PID might not get written // into m_HogPid (so it stays -1). Readback hogstatus for judging if we // had success on getting hog status m_HogPid = GetHogStatus(); if (ret || m_HogPid != getpid()) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetHogStatus: " "Unable to set 'hog' status. Error = %s", GetError(ret).c_str()); return false; } } } else { // Currently Set if (m_HogPid > -1) { pid_t hogPid = -1; OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(hogPid), &hogPid); if (ret || hogPid == getpid()) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetHogStatus: " "Unable to release 'hog' status. Error = %s", GetError(ret).c_str()); return false; } // Reset internal state m_HogPid = hogPid; } } return true; } pid_t CCoreAudioDevice::GetHogStatus() { if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyHogMode; pid_t hogPid = -1; UInt32 size = sizeof(hogPid); AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, &hogPid); return hogPid; } bool CCoreAudioDevice::SetMixingSupport(UInt32 mix) { if (!m_DeviceId) return false; if (!GetMixingSupport()) return false; int restore = -1; if (m_MixerRestore == -1) { // This is our first change to this setting. Store the original setting for restore restore = (GetMixingSupport() ? 1 : 0); } AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertySupportsMixing; UInt32 mixEnable = mix ? 1 : 0; OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(mixEnable), &mixEnable); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetMixingSupport: " "Unable to set MixingSupport to %s. Error = %s", mix ? "'On'" : "'Off'", GetError(ret).c_str()); return false; } if (m_MixerRestore == -1) m_MixerRestore = restore; return true; } bool CCoreAudioDevice::GetMixingSupport() { if (!m_DeviceId) return false; UInt32 size; UInt32 mix = 0; Boolean writable = false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertySupportsMixing; if( AudioObjectHasProperty( m_DeviceId, &propertyAddress ) ) { OSStatus ret = AudioObjectIsPropertySettable(m_DeviceId, &propertyAddress, &writable); if (ret) { CLog::Log(LOGERROR, "CCoreAudioDevice::SupportsMixing: " "Unable to get propertyinfo mixing support. Error = %s", GetError(ret).c_str()); writable = false; } if (writable) { size = sizeof(mix); ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &size, &mix); if (ret != noErr) mix = 0; } } CLog::Log(LOGERROR, "CCoreAudioDevice::SupportsMixing: " "Device mixing support : %s.", mix ? "'Yes'" : "'No'"); return (mix > 0); } bool CCoreAudioDevice::SetCurrentVolume(Float32 vol) { if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kHALOutputParam_Volume; OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(Float32), &vol); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetCurrentVolume: " "Unable to set AudioUnit volume. Error = %s", GetError(ret).c_str()); return false; } return true; } bool CCoreAudioDevice::GetPreferredChannelLayout(CCoreAudioChannelLayout& layout) { if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout; UInt32 propertySize = 0; OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize); if (ret) return false; void* pBuf = malloc(propertySize); ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pBuf); if (ret != noErr) CLog::Log(LOGERROR, "CCoreAudioDevice::GetPreferredChannelLayout: " "Unable to retrieve preferred channel layout. Error = %s", GetError(ret).c_str()); else { // Copy the result into the caller's instance layout.CopyLayout(*((AudioChannelLayout*)pBuf)); } free(pBuf); return (ret == noErr); } bool CCoreAudioDevice::GetDataSources(CoreAudioDataSourceList* pList) { if (!pList || !m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyDataSources; UInt32 propertySize = 0; OSStatus ret = AudioObjectGetPropertyDataSize(m_DeviceId, &propertyAddress, 0, NULL, &propertySize); if (ret != noErr) return false; UInt32 sources = propertySize / sizeof(UInt32); UInt32* pSources = new UInt32[sources]; ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, pSources); if (ret == noErr) { for (UInt32 i = 0; i < sources; i++) pList->push_back(pSources[i]); } delete[] pSources; return (!ret); } Float64 CCoreAudioDevice::GetNominalSampleRate() { if (!m_DeviceId) return 0.0f; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate; Float64 sampleRate = 0.0f; UInt32 propertySize = sizeof(Float64); OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &sampleRate); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::GetNominalSampleRate: " "Unable to retrieve current device sample rate. Error = %s", GetError(ret).c_str()); return 0.0f; } return sampleRate; } bool CCoreAudioDevice::SetNominalSampleRate(Float64 sampleRate) { if (!m_DeviceId || sampleRate == 0.0f) return false; Float64 currentRate = GetNominalSampleRate(); if (currentRate == sampleRate) return true; //No need to change AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate; OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, sizeof(Float64), &sampleRate); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetNominalSampleRate: " "Unable to set current device sample rate to %0.0f. Error = %s", (float)sampleRate, GetError(ret).c_str()); return false; } if (m_SampleRateRestore == 0.0f) m_SampleRateRestore = currentRate; return true; } UInt32 CCoreAudioDevice::GetNumLatencyFrames() { UInt32 num_latency_frames = 0; if (!m_DeviceId) return 0; // number of frames of latency in the AudioDevice AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyLatency; UInt32 i_param = 0; UInt32 i_param_size = sizeof(uint32_t); OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param); if (ret == noErr) num_latency_frames += i_param; // number of frames in the IO buffers propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param); if (ret == noErr) num_latency_frames += i_param; // number for frames in ahead the current hardware position that is safe to do IO propertyAddress.mSelector = kAudioDevicePropertySafetyOffset; ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &i_param_size, &i_param); if (ret == noErr) num_latency_frames += i_param; return (num_latency_frames); } UInt32 CCoreAudioDevice::GetBufferSize() { if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; UInt32 size = 0; UInt32 propertySize = sizeof(size); OSStatus ret = AudioObjectGetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, &propertySize, &size); if (ret != noErr) CLog::Log(LOGERROR, "CCoreAudioDevice::GetBufferSize: " "Unable to retrieve buffer size. Error = %s", GetError(ret).c_str()); return size; } bool CCoreAudioDevice::SetBufferSize(UInt32 size) { if (!m_DeviceId) return false; AudioObjectPropertyAddress propertyAddress; propertyAddress.mScope = kAudioDevicePropertyScopeOutput; propertyAddress.mElement = 0; propertyAddress.mSelector = kAudioDevicePropertyBufferFrameSize; UInt32 propertySize = sizeof(size); OSStatus ret = AudioObjectSetPropertyData(m_DeviceId, &propertyAddress, 0, NULL, propertySize, &size); if (ret != noErr) { CLog::Log(LOGERROR, "CCoreAudioDevice::SetBufferSize: " "Unable to set buffer size. Error = %s", GetError(ret).c_str()); } if (GetBufferSize() != size) CLog::Log(LOGERROR, "CCoreAudioDevice::SetBufferSize: Buffer size change not applied."); return (ret == noErr); } OSStatus CCoreAudioDevice::DirectRenderCallback(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { OSStatus ret = noErr; CCoreAudioDevice *audioDevice = (CCoreAudioDevice*)inClientData; if (audioDevice->m_pSource && audioDevice->m_frameSize) { UInt32 frames = outOutputData->mBuffers[audioDevice->m_OutputBufferIndex].mDataByteSize / audioDevice->m_frameSize; ret = audioDevice->m_pSource->Render(NULL, inInputTime, 0, frames, outOutputData); } else { outOutputData->mBuffers[audioDevice->m_OutputBufferIndex].mDataByteSize = 0; } return ret; }
mekinik232/ambipi
xbmc/cores/AudioEngine/Engines/CoreAudio/CoreAudioDevice.cpp
C++
gpl-2.0
21,096
<?php /** * Write users to file * @param string $filename * @param array $array_data * @return null */ // function insert($user,$config) function readUser($id, $config) { switch ($config['adapter']) { case 'txt': include_once('file/users.php'); $user=readUserFromFile($id, $config); return $users; break; case 'mysql': include_once('mysql/users.php'); $users = select($id,$config); return $users; break; case 'googledocs': include_once('googledocs/users.php'); $users = selectAll($config); return $users; break; } } function update($user, $id, $config) { switch ($config['adapter']) { case 'txt': include_once('file/users.php'); updateUserTofile($id, $user, $user['filename'], $config); return; break; case 'mysql': include_once('mysql/users.php'); $users = updateUser($id, $user, $config); return $users; break; case 'googledocs': include_once('googledocs/users.php'); $users = selectAll($config); return $users; break; } } // function select($id, $config) function readUsers($config) { switch ($config['adapter']) { case 'txt': include_once('file/users.php'); $users=readUsersFromFile($config); return $users; break; case 'mysql': include_once('mysql/users.php'); $users = selectAll($config); return $users; break; case 'googledocs': include_once('googledocs/users.php'); $users = selectAll($config); return $users; break; } } // function delete($id, $config)
zerophp/zgz2013octM
proyecto7/model/users/usersModel.php
PHP
gpl-2.0
1,523
ace_comment { color: #a86; } ace_keyword { line-height: 1em; font-weight: bold; color: blue; } ace_string { color: #a22; } ace_builtin { line-height: 1em; font-weight: bold; color: #077; } ace_special { line-height: 1em; font-weight: bold; color: #0aa; } ace_variable { color: black; } ace_number, ace_atom { color: #3a3; } ace_meta { color: #555; } ace_link { color: #3a3; } ace_activeline-background { background: #e8f2ff; } ace_matchingbracket { outline:1px solid grey; color:black !important; }
Seagat2011/JINSIL-JINT-BLACK-SPADE-
build 1/editor/theme/neat.css
CSS
gpl-2.0
500
/** * yamsLog is a program for real time multi sensor logging and * supervision * Copyright (C) 2014 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import Database.Messages.ProjectMetaData; import Database.Sensors.Sensor; import Errors.BackendError; import FrontendConnection.Backend; import FrontendConnection.Listeners.ProjectCreationStatusListener; import protobuf.Protocol; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created with IntelliJ IDEA. * User: Aitesh * Date: 2014-04-10 * Time: 09:34 * To change this template use File | Settings | File Templates. */ public class NewDebugger implements ProjectCreationStatusListener { private boolean projectListChanged; public NewDebugger(){ try{ Backend.createInstance(null); //args[0],Integer.parseInt(args[1]), Backend.getInstance().addProjectCreationStatusListener(this); Backend.getInstance().connectToServer("130.236.63.46",2001); } catch (BackendError b){ b.printStackTrace(); } projectListChanged = false; } private synchronized boolean readWriteBoolean(Boolean b){ if(b!=null) projectListChanged=b; return projectListChanged; } public void runPlayback() { try{ Thread.sleep(1000); //Backend.getInstance().sendSettingsRequestMessageALlSensors(0); readWriteBoolean(false); Random r = new Random(); String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"}; String project = "projectName" +r.nextInt()%10000; String playbackProject = "realCollection"; Thread.sleep(1000); System.out.println("Setting active project to : " + playbackProject); Backend.getInstance().setActiveProject(playbackProject); ProjectMetaData d = new ProjectMetaData(); d.setTest_leader("ffu"); d.setDate(1l); List<String> s = new ArrayList<String>(); s.add("memer1"); d.setMember_names(s); d.setTags(s); d.setDescription("desc"); List l = d.getMember_names(); l.add(r.nextInt()+". name"); d.setMember_names(l); Backend.getInstance().sendProjectMetaData(d); System.out.println("starting data collection"); Thread.sleep(100); String experimentName = "smallrun"; //Backend.getInstance().setActiveProject(playbackProject); // projektnamn: Thread.sleep(3000); // Backend.getInstance().getSensorConfigurationForPlayback().getSensorId(); List<Protocol.SensorConfiguration> playbackConfig; playbackConfig = Backend.getInstance().getSensorConfigurationForPlayback(); List<Integer> listOfIds = new ArrayList<Integer>(); /* for (Protocol.SensorConfiguration aPlaybackConfig : playbackConfig) { listOfIds.add(aPlaybackConfig.getSensorId()); }*/ System.out.println("LIST OF IDS SENT TO SERVER-------------------------------------------"); System.out.println(listOfIds); System.out.println("LIST OF IDS END -----------------------------------------------------"); System.out.println("LIST OF IDS CURRENTLY IN DATABASE -----------------------------------"); System.out.println(Backend.getInstance().getSensors()); System.out.println("LIST IN DATABASE END ------------------------------------------------"); Backend.getInstance().sendExperimentPlaybackRequest(experimentName, listOfIds); //Thread.sleep(3000); //Backend.getInstance().stopConnection(); } catch (BackendError b){ b.printStackTrace(); } catch (InterruptedException ignore){ } } public void run(){ try{ Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0); readWriteBoolean(false); Random r = new Random(); String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"}; String project = "projectName" +r.nextInt()%10000; String playbackProject = "realCollection"; for(int i = 0; i < 1000; i++){ // project+=strings[r.nextInt(strings.length)]; } //System.out.println(project); //if(r.nextInt()>0) return; Thread.sleep(1000); Backend.getInstance().createNewProjectRequest(project);//"projectName"+ System.currentTimeMillis()); if(!readWriteBoolean(null)){ System.out.println("Waiting on projectListAgain"); while (!readWriteBoolean(null)); System.out.println("finished waiting"); } // = Backend.getInstance().getProjectFilesFromServer().get()); System.out.println("Setting active project to : " + project); Backend.getInstance().setActiveProject(project); ProjectMetaData d = new ProjectMetaData(); //d.setEmail("[email protected]"); d.setTest_leader("ffu"); d.setDate(1l); List<String> s = new ArrayList<String>(); s.add("memer1"); d.setMember_names(s); d.setTags(s); d.setDescription("desc"); List l = d.getMember_names(); l.add(r.nextInt() + ". name"); d.setMember_names(l); Backend.getInstance().sendProjectMetaData(d); /* while(!readWriteBoolean(null) && readWriteBoolean(null)){ Backend.getInstance().sendProjectMetaData(d); List<String> f =d.getTags(); f.add(String.valueOf(System.currentTimeMillis())); d.setTags(f); } **/ System.out.println("starting data collection"); Thread.sleep(100); String experimentName = "experimentNam5"+System.currentTimeMillis(); //String experimentName = "smallrun"; // projektnamn: Backend.getInstance().startDataCollection(experimentName); Thread.sleep(3000); Backend.getInstance().stopDataCollection(); Thread.sleep(1); } catch (BackendError b){ b.printStackTrace(); } catch (InterruptedException ignore){ } System.out.println("Exiting"); } public void runTest(){ // try{ // Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0); // Thread.sleep(1000); Backend.getInstance().createNewProjectRequest("projectName"+ System.currentTimeMillis()); // // //Backend.getInstance().startDataCollection("test1234"); // // //Thread.sleep(5000); Backend.getInstance().stopDataCollection(); // Backend localInstance = Backend.getInstance(); // // Sensor sensor = localInstance.getSensors().get(0); // for(int i = 0; i<sensor.getAttributeList(0).size();i++){ // System.out.print(String.format("%f", sensor.getAttributeList(0).get(i).floatValue()).replace(',', '.') + ","); // // System.out.print(sensor.getId() + ","); // for (int j = 1; j < sensor.getAttributesName().length;j++){ // // System.out.print(sensor.getAttributeList(j).get(i).floatValue() + " ,"); // } // System.out.println(); // } // // } catch (BackendError b){ // b.printStackTrace(); // } catch (InterruptedException ignore){} } @Override public void projectCreationStatusChanged(Protocol.CreateNewProjectResponseMsg.ResponseType responseType) { readWriteBoolean(true); } }
droberg/yamsLog
client-backend/src/NewDebugger.java
Java
gpl-2.0
8,996
using System; using Microsoft.VisualStudio.TestTools.UITesting.WpfControls; namespace CaptainPav.Testing.UI.CodedUI.PageModeling.Wpf { /// <summary> /// Default implementation of a Wpf page model /// </summary> public abstract class WpfPageModelBase<T> : PageModelBase<T> where T : WpfControl { protected readonly WpfWindow parent; protected WpfPageModelBase(WpfWindow bw) { if (null == bw) { throw new ArgumentNullException(nameof(bw)); } this.parent = bw; } protected WpfWindow DocumentWindow => this.parent; } }
lazyRiffs/CodedUIFluentExtensions
CodedUIExtensions/CaptainPav.Testing.UI.CodedUI.PageModeling/Wpf/WpfBaseModels.cs
C#
gpl-2.0
624
/**************************************************************************** * * ViSP, open source Visual Servoing Platform software. * Copyright (C) 2005 - 2019 by Inria. All rights reserved. * * This software is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact Inria about acquiring a ViSP Professional * Edition License. * * See http://visp.inria.fr for more information. * * This software was developed at: * Inria Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * * If you have questions regarding the use of this file, please contact * Inria at [email protected] * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Description: * Test for Afma 6 dof robot. * * Authors: * Fabien Spindler * *****************************************************************************/ /*! \example testRobotAfma6.cpp Example of a real robot control, the Afma6 robot (cartesian robot, with 6 degrees of freedom). */ #include <visp3/core/vpCameraParameters.h> #include <visp3/core/vpDebug.h> #include <visp3/robot/vpRobotAfma6.h> #include <iostream> #ifdef VISP_HAVE_AFMA6 int main() { try { std::cout << "a test for vpRobotAfma6 class..." << std::endl; vpRobotAfma6 afma6; vpCameraParameters cam; std::cout << "-- Default settings for Afma6 ---" << std::endl; std::cout << afma6 << std::endl; afma6.getCameraParameters(cam, 640, 480); std::cout << cam << std::endl; std::cout << "-- Settings associated to the CCMOP tool without distortion ---" << std::endl; afma6.init(vpAfma6::TOOL_CCMOP); std::cout << afma6 << std::endl; afma6.getCameraParameters(cam, 640, 480); std::cout << cam << std::endl; std::cout << "-- Settings associated to CCMOP tool with distortion ------" << std::endl; afma6.init(vpAfma6::TOOL_CCMOP, vpCameraParameters::perspectiveProjWithDistortion); std::cout << afma6 << std::endl; afma6.getCameraParameters(cam, 640, 480); std::cout << cam << std::endl; std::cout << "-- Settings associated to the gripper tool without distortion ---" << std::endl; afma6.init(vpAfma6::TOOL_GRIPPER); std::cout << afma6 << std::endl; afma6.getCameraParameters(cam, 640, 480); std::cout << cam << std::endl; std::cout << "-- Settings associated to gripper tool with distortion ------" << std::endl; afma6.init(vpAfma6::TOOL_GRIPPER, vpCameraParameters::perspectiveProjWithDistortion); std::cout << afma6 << std::endl; afma6.getCameraParameters(cam, 640, 480); std::cout << cam << std::endl; } catch (const vpException &e) { std::cout << "Catch an exception: " << e << std::endl; } return 0; } #else int main() { std::cout << "The real Afma6 robot controller is not available." << std::endl; return 0; } #endif
lagadic/visp
modules/robot/test/servo-afma6/testRobotAfma6.cpp
C++
gpl-2.0
3,333
{% extends 'application_portal/base.html' %} {% block title %}Contact Form{% endblock %} {% block content %} <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <div class="well sidebar-nav"> <li class="nav-header">Important links</li> <ul class="nav nav-list"> <li><a href="/ladm/search/">View Parcel map</a> </li> <li><a href="/ladm/apply/">Submit applications</a> </li> </ul> </div> </div> <div class="span9"> <h2>Contact Form</h2> <p>To send us a message fill out the below form.</p> {% if errors %} <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} <form action="/ladm/contact/" method="post"> {% csrf_token %} <div class="fieldWrapper"> <label>Subject:</label> <input type="text" name="subject"> </div> <br> <div class="fieldWrapper"> <label>Your e-mail (optional):</label> <input type="text" name="email"> </div> <br> <div class="fieldWrapper"> <label>Message: </label> <textarea name="message" class="input-block-level" rows="10" cols="100"></textarea> </div> <br> <input type="submit" name="submit" class="btn btn-primary" value="Submit"> </form> </div> </div> </div> {% endblock %}
wanjohikibui/LIMS
templates/application_portal/contact.html
HTML
gpl-2.0
1,992
/* $Id: capi.c,v 1.1.1.1 2007-05-25 06:50:09 bruce Exp $ * * ISDN lowlevel-module for the IBM ISDN-S0 Active 2000. * CAPI encoder/decoder * * Author Fritz Elfert * Copyright by Fritz Elfert <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Thanks to Friedemann Baitinger and IBM Germany * */ #include "act2000.h" #include "capi.h" static actcapi_msgdsc valid_msg[] = { {{ 0x86, 0x02}, "DATA_B3_IND"}, /* DATA_B3_IND/CONF must be first because of speed!!! */ {{ 0x86, 0x01}, "DATA_B3_CONF"}, {{ 0x02, 0x01}, "CONNECT_CONF"}, {{ 0x02, 0x02}, "CONNECT_IND"}, {{ 0x09, 0x01}, "CONNECT_INFO_CONF"}, {{ 0x03, 0x02}, "CONNECT_ACTIVE_IND"}, {{ 0x04, 0x01}, "DISCONNECT_CONF"}, {{ 0x04, 0x02}, "DISCONNECT_IND"}, {{ 0x05, 0x01}, "LISTEN_CONF"}, {{ 0x06, 0x01}, "GET_PARAMS_CONF"}, {{ 0x07, 0x01}, "INFO_CONF"}, {{ 0x07, 0x02}, "INFO_IND"}, {{ 0x08, 0x01}, "DATA_CONF"}, {{ 0x08, 0x02}, "DATA_IND"}, {{ 0x40, 0x01}, "SELECT_B2_PROTOCOL_CONF"}, {{ 0x80, 0x01}, "SELECT_B3_PROTOCOL_CONF"}, {{ 0x81, 0x01}, "LISTEN_B3_CONF"}, {{ 0x82, 0x01}, "CONNECT_B3_CONF"}, {{ 0x82, 0x02}, "CONNECT_B3_IND"}, {{ 0x83, 0x02}, "CONNECT_B3_ACTIVE_IND"}, {{ 0x84, 0x01}, "DISCONNECT_B3_CONF"}, {{ 0x84, 0x02}, "DISCONNECT_B3_IND"}, {{ 0x85, 0x01}, "GET_B3_PARAMS_CONF"}, {{ 0x01, 0x01}, "RESET_B3_CONF"}, {{ 0x01, 0x02}, "RESET_B3_IND"}, /* {{ 0x87, 0x02, "HANDSET_IND"}, not implemented */ {{ 0xff, 0x01}, "MANUFACTURER_CONF"}, {{ 0xff, 0x02}, "MANUFACTURER_IND"}, #ifdef DEBUG_MSG /* Requests */ {{ 0x01, 0x00}, "RESET_B3_REQ"}, {{ 0x02, 0x00}, "CONNECT_REQ"}, {{ 0x04, 0x00}, "DISCONNECT_REQ"}, {{ 0x05, 0x00}, "LISTEN_REQ"}, {{ 0x06, 0x00}, "GET_PARAMS_REQ"}, {{ 0x07, 0x00}, "INFO_REQ"}, {{ 0x08, 0x00}, "DATA_REQ"}, {{ 0x09, 0x00}, "CONNECT_INFO_REQ"}, {{ 0x40, 0x00}, "SELECT_B2_PROTOCOL_REQ"}, {{ 0x80, 0x00}, "SELECT_B3_PROTOCOL_REQ"}, {{ 0x81, 0x00}, "LISTEN_B3_REQ"}, {{ 0x82, 0x00}, "CONNECT_B3_REQ"}, {{ 0x84, 0x00}, "DISCONNECT_B3_REQ"}, {{ 0x85, 0x00}, "GET_B3_PARAMS_REQ"}, {{ 0x86, 0x00}, "DATA_B3_REQ"}, {{ 0xff, 0x00}, "MANUFACTURER_REQ"}, /* Responses */ {{ 0x01, 0x03}, "RESET_B3_RESP"}, {{ 0x02, 0x03}, "CONNECT_RESP"}, {{ 0x03, 0x03}, "CONNECT_ACTIVE_RESP"}, {{ 0x04, 0x03}, "DISCONNECT_RESP"}, {{ 0x07, 0x03}, "INFO_RESP"}, {{ 0x08, 0x03}, "DATA_RESP"}, {{ 0x82, 0x03}, "CONNECT_B3_RESP"}, {{ 0x83, 0x03}, "CONNECT_B3_ACTIVE_RESP"}, {{ 0x84, 0x03}, "DISCONNECT_B3_RESP"}, {{ 0x86, 0x03}, "DATA_B3_RESP"}, {{ 0xff, 0x03}, "MANUFACTURER_RESP"}, #endif {{ 0x00, 0x00}, NULL}, }; #define num_valid_msg (sizeof(valid_msg)/sizeof(actcapi_msgdsc)) #define num_valid_imsg 27 /* MANUFACTURER_IND */ /* * Check for a valid incoming CAPI message. * Return: * 0 = Invalid message * 1 = Valid message, no B-Channel-data * 2 = Valid message, B-Channel-data */ int actcapi_chkhdr(act2000_card * card, actcapi_msghdr *hdr) { int i; if (hdr->applicationID != 1) return 0; if (hdr->len < 9) return 0; for (i = 0; i < num_valid_imsg; i++) if ((hdr->cmd.cmd == valid_msg[i].cmd.cmd) && (hdr->cmd.subcmd == valid_msg[i].cmd.subcmd)) { return (i?1:2); } return 0; } #define ACTCAPI_MKHDR(l, c, s) { \ skb = alloc_skb(l + 8, GFP_ATOMIC); \ if (skb) { \ m = (actcapi_msg *)skb_put(skb, l + 8); \ m->hdr.len = l + 8; \ m->hdr.applicationID = 1; \ m->hdr.cmd.cmd = c; \ m->hdr.cmd.subcmd = s; \ m->hdr.msgnum = actcapi_nextsmsg(card); \ } else m = NULL;\ } #define ACTCAPI_CHKSKB if (!skb) { \ printk(KERN_WARNING "actcapi: alloc_skb failed\n"); \ return; \ } #define ACTCAPI_QUEUE_TX { \ actcapi_debug_msg(skb, 1); \ skb_queue_tail(&card->sndq, skb); \ act2000_schedule_tx(card); \ } int actcapi_listen_req(act2000_card *card) { __u16 eazmask = 0; int i; actcapi_msg *m; struct sk_buff *skb; for (i = 0; i < ACT2000_BCH; i++) eazmask |= card->bch[i].eazmask; ACTCAPI_MKHDR(9, 0x05, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return -ENOMEM; } m->msg.listen_req.controller = 0; m->msg.listen_req.infomask = 0x3f; /* All information */ m->msg.listen_req.eazmask = eazmask; m->msg.listen_req.simask = (eazmask)?0x86:0; /* All SI's */ ACTCAPI_QUEUE_TX; return 0; } int actcapi_connect_req(act2000_card *card, act2000_chan *chan, char *phone, char eaz, int si1, int si2) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR((11 + strlen(phone)), 0x02, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); chan->fsm_state = ACT2000_STATE_NULL; return -ENOMEM; } m->msg.connect_req.controller = 0; m->msg.connect_req.bchan = 0x83; m->msg.connect_req.infomask = 0x3f; m->msg.connect_req.si1 = si1; m->msg.connect_req.si2 = si2; m->msg.connect_req.eaz = eaz?eaz:'0'; m->msg.connect_req.addr.len = strlen(phone) + 1; m->msg.connect_req.addr.tnp = 0x81; memcpy(m->msg.connect_req.addr.num, phone, strlen(phone)); chan->callref = m->hdr.msgnum; ACTCAPI_QUEUE_TX; return 0; } static void actcapi_connect_b3_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(17, 0x82, 0x00); ACTCAPI_CHKSKB; m->msg.connect_b3_req.plci = chan->plci; memset(&m->msg.connect_b3_req.ncpi, 0, sizeof(m->msg.connect_b3_req.ncpi)); m->msg.connect_b3_req.ncpi.len = 13; m->msg.connect_b3_req.ncpi.modulo = 8; ACTCAPI_QUEUE_TX; } /* * Set net type (1TR6) or (EDSS1) */ int actcapi_manufacturer_req_net(act2000_card *card) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(5, 0xff, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return -ENOMEM; } m->msg.manufacturer_req_net.manuf_msg = 0x11; m->msg.manufacturer_req_net.controller = 1; m->msg.manufacturer_req_net.nettype = (card->ptype == ISDN_PTYPE_EURO)?1:0; ACTCAPI_QUEUE_TX; printk(KERN_INFO "act2000 %s: D-channel protocol now %s\n", card->interface.id, (card->ptype == ISDN_PTYPE_EURO)?"euro":"1tr6"); card->interface.features &= ~(ISDN_FEATURE_P_UNKNOWN | ISDN_FEATURE_P_EURO | ISDN_FEATURE_P_1TR6); card->interface.features |= ((card->ptype == ISDN_PTYPE_EURO)?ISDN_FEATURE_P_EURO:ISDN_FEATURE_P_1TR6); return 0; } /* * Switch V.42 on or off */ #if 0 int actcapi_manufacturer_req_v42(act2000_card *card, ulong arg) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(8, 0xff, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return -ENOMEM; } m->msg.manufacturer_req_v42.manuf_msg = 0x10; m->msg.manufacturer_req_v42.controller = 0; m->msg.manufacturer_req_v42.v42control = (arg?1:0); ACTCAPI_QUEUE_TX; return 0; } #endif /* 0 */ /* * Set error-handler */ int actcapi_manufacturer_req_errh(act2000_card *card) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(4, 0xff, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return -ENOMEM; } m->msg.manufacturer_req_err.manuf_msg = 0x03; m->msg.manufacturer_req_err.controller = 0; ACTCAPI_QUEUE_TX; return 0; } /* * Set MSN-Mapping. */ int actcapi_manufacturer_req_msn(act2000_card *card) { msn_entry *p = card->msn_list; actcapi_msg *m; struct sk_buff *skb; int len; while (p) { int i; len = strlen(p->msn); for (i = 0; i < 2; i++) { ACTCAPI_MKHDR(6 + len, 0xff, 0x00); if (!skb) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return -ENOMEM; } m->msg.manufacturer_req_msn.manuf_msg = 0x13 + i; m->msg.manufacturer_req_msn.controller = 0; m->msg.manufacturer_req_msn.msnmap.eaz = p->eaz; m->msg.manufacturer_req_msn.msnmap.len = len; memcpy(m->msg.manufacturer_req_msn.msnmap.msn, p->msn, len); ACTCAPI_QUEUE_TX; } p = p->next; } return 0; } void actcapi_select_b2_protocol_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(10, 0x40, 0x00); ACTCAPI_CHKSKB; m->msg.select_b2_protocol_req.plci = chan->plci; memset(&m->msg.select_b2_protocol_req.dlpd, 0, sizeof(m->msg.select_b2_protocol_req.dlpd)); m->msg.select_b2_protocol_req.dlpd.len = 6; switch (chan->l2prot) { case ISDN_PROTO_L2_TRANS: m->msg.select_b2_protocol_req.protocol = 0x03; m->msg.select_b2_protocol_req.dlpd.dlen = 4000; break; case ISDN_PROTO_L2_HDLC: m->msg.select_b2_protocol_req.protocol = 0x02; m->msg.select_b2_protocol_req.dlpd.dlen = 4000; break; case ISDN_PROTO_L2_X75I: case ISDN_PROTO_L2_X75UI: case ISDN_PROTO_L2_X75BUI: m->msg.select_b2_protocol_req.protocol = 0x01; m->msg.select_b2_protocol_req.dlpd.dlen = 4000; m->msg.select_b2_protocol_req.dlpd.laa = 3; m->msg.select_b2_protocol_req.dlpd.lab = 1; m->msg.select_b2_protocol_req.dlpd.win = 7; m->msg.select_b2_protocol_req.dlpd.modulo = 8; break; } ACTCAPI_QUEUE_TX; } static void actcapi_select_b3_protocol_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(17, 0x80, 0x00); ACTCAPI_CHKSKB; m->msg.select_b3_protocol_req.plci = chan->plci; memset(&m->msg.select_b3_protocol_req.ncpd, 0, sizeof(m->msg.select_b3_protocol_req.ncpd)); switch (chan->l3prot) { case ISDN_PROTO_L3_TRANS: m->msg.select_b3_protocol_req.protocol = 0x04; m->msg.select_b3_protocol_req.ncpd.len = 13; m->msg.select_b3_protocol_req.ncpd.modulo = 8; break; } ACTCAPI_QUEUE_TX; } static void actcapi_listen_b3_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x81, 0x00); ACTCAPI_CHKSKB; m->msg.listen_b3_req.plci = chan->plci; ACTCAPI_QUEUE_TX; } static void actcapi_disconnect_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(3, 0x04, 0x00); ACTCAPI_CHKSKB; m->msg.disconnect_req.plci = chan->plci; m->msg.disconnect_req.cause = 0; ACTCAPI_QUEUE_TX; } void actcapi_disconnect_b3_req(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(17, 0x84, 0x00); ACTCAPI_CHKSKB; m->msg.disconnect_b3_req.ncci = chan->ncci; memset(&m->msg.disconnect_b3_req.ncpi, 0, sizeof(m->msg.disconnect_b3_req.ncpi)); m->msg.disconnect_b3_req.ncpi.len = 13; m->msg.disconnect_b3_req.ncpi.modulo = 8; chan->fsm_state = ACT2000_STATE_BHWAIT; ACTCAPI_QUEUE_TX; } void actcapi_connect_resp(act2000_card *card, act2000_chan *chan, __u8 cause) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(3, 0x02, 0x03); ACTCAPI_CHKSKB; m->msg.connect_resp.plci = chan->plci; m->msg.connect_resp.rejectcause = cause; if (cause) { chan->fsm_state = ACT2000_STATE_NULL; chan->plci = 0x8000; } else chan->fsm_state = ACT2000_STATE_IWAIT; ACTCAPI_QUEUE_TX; } static void actcapi_connect_active_resp(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x03, 0x03); ACTCAPI_CHKSKB; m->msg.connect_resp.plci = chan->plci; if (chan->fsm_state == ACT2000_STATE_IWAIT) chan->fsm_state = ACT2000_STATE_IBWAIT; ACTCAPI_QUEUE_TX; } static void actcapi_connect_b3_resp(act2000_card *card, act2000_chan *chan, __u8 rejectcause) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR((rejectcause?3:17), 0x82, 0x03); ACTCAPI_CHKSKB; m->msg.connect_b3_resp.ncci = chan->ncci; m->msg.connect_b3_resp.rejectcause = rejectcause; if (!rejectcause) { memset(&m->msg.connect_b3_resp.ncpi, 0, sizeof(m->msg.connect_b3_resp.ncpi)); m->msg.connect_b3_resp.ncpi.len = 13; m->msg.connect_b3_resp.ncpi.modulo = 8; chan->fsm_state = ACT2000_STATE_BWAIT; } ACTCAPI_QUEUE_TX; } static void actcapi_connect_b3_active_resp(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x83, 0x03); ACTCAPI_CHKSKB; m->msg.connect_b3_active_resp.ncci = chan->ncci; chan->fsm_state = ACT2000_STATE_ACTIVE; ACTCAPI_QUEUE_TX; } static void actcapi_info_resp(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x07, 0x03); ACTCAPI_CHKSKB; m->msg.info_resp.plci = chan->plci; ACTCAPI_QUEUE_TX; } static void actcapi_disconnect_b3_resp(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x84, 0x03); ACTCAPI_CHKSKB; m->msg.disconnect_b3_resp.ncci = chan->ncci; chan->ncci = 0x8000; chan->queued = 0; ACTCAPI_QUEUE_TX; } static void actcapi_disconnect_resp(act2000_card *card, act2000_chan *chan) { actcapi_msg *m; struct sk_buff *skb; ACTCAPI_MKHDR(2, 0x04, 0x03); ACTCAPI_CHKSKB; m->msg.disconnect_resp.plci = chan->plci; chan->plci = 0x8000; ACTCAPI_QUEUE_TX; } static int new_plci(act2000_card *card, __u16 plci) { int i; for (i = 0; i < ACT2000_BCH; i++) if (card->bch[i].plci == 0x8000) { card->bch[i].plci = plci; return i; } return -1; } static int find_plci(act2000_card *card, __u16 plci) { int i; for (i = 0; i < ACT2000_BCH; i++) if (card->bch[i].plci == plci) return i; return -1; } static int find_ncci(act2000_card *card, __u16 ncci) { int i; for (i = 0; i < ACT2000_BCH; i++) if (card->bch[i].ncci == ncci) return i; return -1; } static int find_dialing(act2000_card *card, __u16 callref) { int i; for (i = 0; i < ACT2000_BCH; i++) if ((card->bch[i].callref == callref) && (card->bch[i].fsm_state == ACT2000_STATE_OCALL)) return i; return -1; } static int actcapi_data_b3_ind(act2000_card *card, struct sk_buff *skb) { __u16 plci; __u16 ncci; __u16 controller; __u8 blocknr; int chan; actcapi_msg *msg = (actcapi_msg *)skb->data; EVAL_NCCI(msg->msg.data_b3_ind.fakencci, plci, controller, ncci); chan = find_ncci(card, ncci); if (chan < 0) return 0; if (card->bch[chan].fsm_state != ACT2000_STATE_ACTIVE) return 0; if (card->bch[chan].plci != plci) return 0; blocknr = msg->msg.data_b3_ind.blocknr; skb_pull(skb, 19); card->interface.rcvcallb_skb(card->myid, chan, skb); if (!(skb = alloc_skb(11, GFP_ATOMIC))) { printk(KERN_WARNING "actcapi: alloc_skb failed\n"); return 1; } msg = (actcapi_msg *)skb_put(skb, 11); msg->hdr.len = 11; msg->hdr.applicationID = 1; msg->hdr.cmd.cmd = 0x86; msg->hdr.cmd.subcmd = 0x03; msg->hdr.msgnum = actcapi_nextsmsg(card); msg->msg.data_b3_resp.ncci = ncci; msg->msg.data_b3_resp.blocknr = blocknr; ACTCAPI_QUEUE_TX; return 1; } /* * Walk over ackq, unlink DATA_B3_REQ from it, if * ncci and blocknr are matching. * Decrement queued-bytes counter. */ static int handle_ack(act2000_card *card, act2000_chan *chan, __u8 blocknr) { unsigned long flags; struct sk_buff *skb; struct sk_buff *tmp; struct actcapi_msg *m; int ret = 0; spin_lock_irqsave(&card->lock, flags); skb = skb_peek(&card->ackq); spin_unlock_irqrestore(&card->lock, flags); if (!skb) { printk(KERN_WARNING "act2000: handle_ack nothing found!\n"); return 0; } tmp = skb; while (1) { m = (actcapi_msg *)tmp->data; if ((((m->msg.data_b3_req.fakencci >> 8) & 0xff) == chan->ncci) && (m->msg.data_b3_req.blocknr == blocknr)) { /* found corresponding DATA_B3_REQ */ skb_unlink(tmp, &card->ackq); chan->queued -= m->msg.data_b3_req.datalen; if (m->msg.data_b3_req.flags) ret = m->msg.data_b3_req.datalen; dev_kfree_skb(tmp); if (chan->queued < 0) chan->queued = 0; return ret; } spin_lock_irqsave(&card->lock, flags); tmp = skb_peek((struct sk_buff_head *)tmp); spin_unlock_irqrestore(&card->lock, flags); if ((tmp == skb) || (tmp == NULL)) { /* reached end of queue */ printk(KERN_WARNING "act2000: handle_ack nothing found!\n"); return 0; } } } void actcapi_dispatch(struct work_struct *work) { struct act2000_card *card = container_of(work, struct act2000_card, rcv_tq); struct sk_buff *skb; actcapi_msg *msg; __u16 ccmd; int chan; int len; act2000_chan *ctmp; isdn_ctrl cmd; char tmp[170]; while ((skb = skb_dequeue(&card->rcvq))) { actcapi_debug_msg(skb, 0); msg = (actcapi_msg *)skb->data; ccmd = ((msg->hdr.cmd.cmd << 8) | msg->hdr.cmd.subcmd); switch (ccmd) { case 0x8602: /* DATA_B3_IND */ if (actcapi_data_b3_ind(card, skb)) return; break; case 0x8601: /* DATA_B3_CONF */ chan = find_ncci(card, msg->msg.data_b3_conf.ncci); if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_ACTIVE)) { if (msg->msg.data_b3_conf.info != 0) printk(KERN_WARNING "act2000: DATA_B3_CONF: %04x\n", msg->msg.data_b3_conf.info); len = handle_ack(card, &card->bch[chan], msg->msg.data_b3_conf.blocknr); if (len) { cmd.driver = card->myid; cmd.command = ISDN_STAT_BSENT; cmd.arg = chan; cmd.parm.length = len; card->interface.statcallb(&cmd); } } break; case 0x0201: /* CONNECT_CONF */ chan = find_dialing(card, msg->hdr.msgnum); if (chan >= 0) { if (msg->msg.connect_conf.info) { card->bch[chan].fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } else { card->bch[chan].fsm_state = ACT2000_STATE_OWAIT; card->bch[chan].plci = msg->msg.connect_conf.plci; } } break; case 0x0202: /* CONNECT_IND */ chan = new_plci(card, msg->msg.connect_ind.plci); if (chan < 0) { ctmp = (act2000_chan *)tmp; ctmp->plci = msg->msg.connect_ind.plci; actcapi_connect_resp(card, ctmp, 0x11); /* All Card-Cannels busy */ } else { card->bch[chan].fsm_state = ACT2000_STATE_ICALL; cmd.driver = card->myid; cmd.command = ISDN_STAT_ICALL; cmd.arg = chan; cmd.parm.setup.si1 = msg->msg.connect_ind.si1; cmd.parm.setup.si2 = msg->msg.connect_ind.si2; if (card->ptype == ISDN_PTYPE_EURO) strcpy(cmd.parm.setup.eazmsn, act2000_find_eaz(card, msg->msg.connect_ind.eaz)); else { cmd.parm.setup.eazmsn[0] = msg->msg.connect_ind.eaz; cmd.parm.setup.eazmsn[1] = 0; } memset(cmd.parm.setup.phone, 0, sizeof(cmd.parm.setup.phone)); memcpy(cmd.parm.setup.phone, msg->msg.connect_ind.addr.num, msg->msg.connect_ind.addr.len - 1); cmd.parm.setup.plan = msg->msg.connect_ind.addr.tnp; cmd.parm.setup.screen = 0; if (card->interface.statcallb(&cmd) == 2) actcapi_connect_resp(card, &card->bch[chan], 0x15); /* Reject Call */ } break; case 0x0302: /* CONNECT_ACTIVE_IND */ chan = find_plci(card, msg->msg.connect_active_ind.plci); if (chan >= 0) switch (card->bch[chan].fsm_state) { case ACT2000_STATE_IWAIT: actcapi_connect_active_resp(card, &card->bch[chan]); break; case ACT2000_STATE_OWAIT: actcapi_connect_active_resp(card, &card->bch[chan]); actcapi_select_b2_protocol_req(card, &card->bch[chan]); break; } break; case 0x8202: /* CONNECT_B3_IND */ chan = find_plci(card, msg->msg.connect_b3_ind.plci); if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_IBWAIT)) { card->bch[chan].ncci = msg->msg.connect_b3_ind.ncci; actcapi_connect_b3_resp(card, &card->bch[chan], 0); } else { ctmp = (act2000_chan *)tmp; ctmp->ncci = msg->msg.connect_b3_ind.ncci; actcapi_connect_b3_resp(card, ctmp, 0x11); /* All Card-Cannels busy */ } break; case 0x8302: /* CONNECT_B3_ACTIVE_IND */ chan = find_ncci(card, msg->msg.connect_b3_active_ind.ncci); if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_BWAIT)) { actcapi_connect_b3_active_resp(card, &card->bch[chan]); cmd.driver = card->myid; cmd.command = ISDN_STAT_BCONN; cmd.arg = chan; card->interface.statcallb(&cmd); } break; case 0x8402: /* DISCONNECT_B3_IND */ chan = find_ncci(card, msg->msg.disconnect_b3_ind.ncci); if (chan >= 0) { ctmp = &card->bch[chan]; actcapi_disconnect_b3_resp(card, ctmp); switch (ctmp->fsm_state) { case ACT2000_STATE_ACTIVE: ctmp->fsm_state = ACT2000_STATE_DHWAIT2; cmd.driver = card->myid; cmd.command = ISDN_STAT_BHUP; cmd.arg = chan; card->interface.statcallb(&cmd); break; case ACT2000_STATE_BHWAIT2: actcapi_disconnect_req(card, ctmp); ctmp->fsm_state = ACT2000_STATE_DHWAIT; cmd.driver = card->myid; cmd.command = ISDN_STAT_BHUP; cmd.arg = chan; card->interface.statcallb(&cmd); break; } } break; case 0x0402: /* DISCONNECT_IND */ chan = find_plci(card, msg->msg.disconnect_ind.plci); if (chan >= 0) { ctmp = &card->bch[chan]; actcapi_disconnect_resp(card, ctmp); ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } else { ctmp = (act2000_chan *)tmp; ctmp->plci = msg->msg.disconnect_ind.plci; actcapi_disconnect_resp(card, ctmp); } break; case 0x4001: /* SELECT_B2_PROTOCOL_CONF */ chan = find_plci(card, msg->msg.select_b2_protocol_conf.plci); if (chan >= 0) switch (card->bch[chan].fsm_state) { case ACT2000_STATE_ICALL: case ACT2000_STATE_OWAIT: ctmp = &card->bch[chan]; if (msg->msg.select_b2_protocol_conf.info == 0) actcapi_select_b3_protocol_req(card, ctmp); else { ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } break; } break; case 0x8001: /* SELECT_B3_PROTOCOL_CONF */ chan = find_plci(card, msg->msg.select_b3_protocol_conf.plci); if (chan >= 0) switch (card->bch[chan].fsm_state) { case ACT2000_STATE_ICALL: case ACT2000_STATE_OWAIT: ctmp = &card->bch[chan]; if (msg->msg.select_b3_protocol_conf.info == 0) actcapi_listen_b3_req(card, ctmp); else { ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } } break; case 0x8101: /* LISTEN_B3_CONF */ chan = find_plci(card, msg->msg.listen_b3_conf.plci); if (chan >= 0) switch (card->bch[chan].fsm_state) { case ACT2000_STATE_ICALL: ctmp = &card->bch[chan]; if (msg->msg.listen_b3_conf.info == 0) actcapi_connect_resp(card, ctmp, 0); else { ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } break; case ACT2000_STATE_OWAIT: ctmp = &card->bch[chan]; if (msg->msg.listen_b3_conf.info == 0) { actcapi_connect_b3_req(card, ctmp); ctmp->fsm_state = ACT2000_STATE_OBWAIT; cmd.driver = card->myid; cmd.command = ISDN_STAT_DCONN; cmd.arg = chan; card->interface.statcallb(&cmd); } else { ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } break; } break; case 0x8201: /* CONNECT_B3_CONF */ chan = find_plci(card, msg->msg.connect_b3_conf.plci); if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_OBWAIT)) { ctmp = &card->bch[chan]; if (msg->msg.connect_b3_conf.info) { ctmp->fsm_state = ACT2000_STATE_NULL; cmd.driver = card->myid; cmd.command = ISDN_STAT_DHUP; cmd.arg = chan; card->interface.statcallb(&cmd); } else { ctmp->ncci = msg->msg.connect_b3_conf.ncci; ctmp->fsm_state = ACT2000_STATE_BWAIT; } } break; case 0x8401: /* DISCONNECT_B3_CONF */ chan = find_ncci(card, msg->msg.disconnect_b3_conf.ncci); if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_BHWAIT)) card->bch[chan].fsm_state = ACT2000_STATE_BHWAIT2; break; case 0x0702: /* INFO_IND */ chan = find_plci(card, msg->msg.info_ind.plci); if (chan >= 0) /* TODO: Eval Charging info / cause */ actcapi_info_resp(card, &card->bch[chan]); break; case 0x0401: /* LISTEN_CONF */ case 0x0501: /* LISTEN_CONF */ case 0xff01: /* MANUFACTURER_CONF */ break; case 0xff02: /* MANUFACTURER_IND */ if (msg->msg.manuf_msg == 3) { memset(tmp, 0, sizeof(tmp)); strncpy(tmp, &msg->msg.manufacturer_ind_err.errstring, msg->hdr.len - 16); if (msg->msg.manufacturer_ind_err.errcode) printk(KERN_WARNING "act2000: %s\n", tmp); else { printk(KERN_DEBUG "act2000: %s\n", tmp); if ((!strncmp(tmp, "INFO: Trace buffer con", 22)) || (!strncmp(tmp, "INFO: Compile Date/Tim", 22))) { card->flags |= ACT2000_FLAGS_RUNNING; cmd.command = ISDN_STAT_RUN; cmd.driver = card->myid; cmd.arg = 0; actcapi_manufacturer_req_net(card); actcapi_manufacturer_req_msn(card); actcapi_listen_req(card); card->interface.statcallb(&cmd); } } } break; default: printk(KERN_WARNING "act2000: UNHANDLED Message %04x\n", ccmd); break; } dev_kfree_skb(skb); } } #ifdef DEBUG_MSG static void actcapi_debug_caddr(actcapi_addr *addr) { char tmp[30]; printk(KERN_DEBUG " Alen = %d\n", addr->len); if (addr->len > 0) printk(KERN_DEBUG " Atnp = 0x%02x\n", addr->tnp); if (addr->len > 1) { memset(tmp, 0, 30); memcpy(tmp, addr->num, addr->len - 1); printk(KERN_DEBUG " Anum = '%s'\n", tmp); } } static void actcapi_debug_ncpi(actcapi_ncpi *ncpi) { printk(KERN_DEBUG " ncpi.len = %d\n", ncpi->len); if (ncpi->len >= 2) printk(KERN_DEBUG " ncpi.lic = 0x%04x\n", ncpi->lic); if (ncpi->len >= 4) printk(KERN_DEBUG " ncpi.hic = 0x%04x\n", ncpi->hic); if (ncpi->len >= 6) printk(KERN_DEBUG " ncpi.ltc = 0x%04x\n", ncpi->ltc); if (ncpi->len >= 8) printk(KERN_DEBUG " ncpi.htc = 0x%04x\n", ncpi->htc); if (ncpi->len >= 10) printk(KERN_DEBUG " ncpi.loc = 0x%04x\n", ncpi->loc); if (ncpi->len >= 12) printk(KERN_DEBUG " ncpi.hoc = 0x%04x\n", ncpi->hoc); if (ncpi->len >= 13) printk(KERN_DEBUG " ncpi.mod = %d\n", ncpi->modulo); } static void actcapi_debug_dlpd(actcapi_dlpd *dlpd) { printk(KERN_DEBUG " dlpd.len = %d\n", dlpd->len); if (dlpd->len >= 2) printk(KERN_DEBUG " dlpd.dlen = 0x%04x\n", dlpd->dlen); if (dlpd->len >= 3) printk(KERN_DEBUG " dlpd.laa = 0x%02x\n", dlpd->laa); if (dlpd->len >= 4) printk(KERN_DEBUG " dlpd.lab = 0x%02x\n", dlpd->lab); if (dlpd->len >= 5) printk(KERN_DEBUG " dlpd.modulo = %d\n", dlpd->modulo); if (dlpd->len >= 6) printk(KERN_DEBUG " dlpd.win = %d\n", dlpd->win); } #ifdef DEBUG_DUMP_SKB static void dump_skb(struct sk_buff *skb) { char tmp[80]; char *p = skb->data; char *t = tmp; int i; for (i = 0; i < skb->len; i++) { t += sprintf(t, "%02x ", *p++ & 0xff); if ((i & 0x0f) == 8) { printk(KERN_DEBUG "dump: %s\n", tmp); t = tmp; } } if (i & 0x07) printk(KERN_DEBUG "dump: %s\n", tmp); } #endif void actcapi_debug_msg(struct sk_buff *skb, int direction) { actcapi_msg *msg = (actcapi_msg *)skb->data; char *descr; int i; char tmp[170]; #ifndef DEBUG_DATA_MSG if (msg->hdr.cmd.cmd == 0x86) return; #endif descr = "INVALID"; #ifdef DEBUG_DUMP_SKB dump_skb(skb); #endif for (i = 0; i < num_valid_msg; i++) if ((msg->hdr.cmd.cmd == valid_msg[i].cmd.cmd) && (msg->hdr.cmd.subcmd == valid_msg[i].cmd.subcmd)) { descr = valid_msg[i].description; break; } printk(KERN_DEBUG "%s %s msg\n", direction?"Outgoing":"Incoming", descr); printk(KERN_DEBUG " ApplID = %d\n", msg->hdr.applicationID); printk(KERN_DEBUG " Len = %d\n", msg->hdr.len); printk(KERN_DEBUG " MsgNum = 0x%04x\n", msg->hdr.msgnum); printk(KERN_DEBUG " Cmd = 0x%02x\n", msg->hdr.cmd.cmd); printk(KERN_DEBUG " SubCmd = 0x%02x\n", msg->hdr.cmd.subcmd); switch (i) { case 0: /* DATA B3 IND */ printk(KERN_DEBUG " BLOCK = 0x%02x\n", msg->msg.data_b3_ind.blocknr); break; case 2: /* CONNECT CONF */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_conf.plci); printk(KERN_DEBUG " Info = 0x%04x\n", msg->msg.connect_conf.info); break; case 3: /* CONNECT IND */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_ind.plci); printk(KERN_DEBUG " Contr = %d\n", msg->msg.connect_ind.controller); printk(KERN_DEBUG " SI1 = %d\n", msg->msg.connect_ind.si1); printk(KERN_DEBUG " SI2 = %d\n", msg->msg.connect_ind.si2); printk(KERN_DEBUG " EAZ = '%c'\n", msg->msg.connect_ind.eaz); actcapi_debug_caddr(&msg->msg.connect_ind.addr); break; case 5: /* CONNECT ACTIVE IND */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_active_ind.plci); actcapi_debug_caddr(&msg->msg.connect_active_ind.addr); break; case 8: /* LISTEN CONF */ printk(KERN_DEBUG " Contr = %d\n", msg->msg.listen_conf.controller); printk(KERN_DEBUG " Info = 0x%04x\n", msg->msg.listen_conf.info); break; case 11: /* INFO IND */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.info_ind.plci); printk(KERN_DEBUG " Imsk = 0x%04x\n", msg->msg.info_ind.nr.mask); if (msg->hdr.len > 12) { int l = msg->hdr.len - 12; int j; char *p = tmp; for (j = 0; j < l ; j++) p += sprintf(p, "%02x ", msg->msg.info_ind.el.display[j]); printk(KERN_DEBUG " D = '%s'\n", tmp); } break; case 14: /* SELECT B2 PROTOCOL CONF */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.select_b2_protocol_conf.plci); printk(KERN_DEBUG " Info = 0x%04x\n", msg->msg.select_b2_protocol_conf.info); break; case 15: /* SELECT B3 PROTOCOL CONF */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.select_b3_protocol_conf.plci); printk(KERN_DEBUG " Info = 0x%04x\n", msg->msg.select_b3_protocol_conf.info); break; case 16: /* LISTEN B3 CONF */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.listen_b3_conf.plci); printk(KERN_DEBUG " Info = 0x%04x\n", msg->msg.listen_b3_conf.info); break; case 18: /* CONNECT B3 IND */ printk(KERN_DEBUG " NCCI = 0x%04x\n", msg->msg.connect_b3_ind.ncci); printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_b3_ind.plci); actcapi_debug_ncpi(&msg->msg.connect_b3_ind.ncpi); break; case 19: /* CONNECT B3 ACTIVE IND */ printk(KERN_DEBUG " NCCI = 0x%04x\n", msg->msg.connect_b3_active_ind.ncci); actcapi_debug_ncpi(&msg->msg.connect_b3_active_ind.ncpi); break; case 26: /* MANUFACTURER IND */ printk(KERN_DEBUG " Mmsg = 0x%02x\n", msg->msg.manufacturer_ind_err.manuf_msg); switch (msg->msg.manufacturer_ind_err.manuf_msg) { case 3: printk(KERN_DEBUG " Contr = %d\n", msg->msg.manufacturer_ind_err.controller); printk(KERN_DEBUG " Code = 0x%08x\n", msg->msg.manufacturer_ind_err.errcode); memset(tmp, 0, sizeof(tmp)); strncpy(tmp, &msg->msg.manufacturer_ind_err.errstring, msg->hdr.len - 16); printk(KERN_DEBUG " Emsg = '%s'\n", tmp); break; } break; case 30: /* LISTEN REQ */ printk(KERN_DEBUG " Imsk = 0x%08x\n", msg->msg.listen_req.infomask); printk(KERN_DEBUG " Emsk = 0x%04x\n", msg->msg.listen_req.eazmask); printk(KERN_DEBUG " Smsk = 0x%04x\n", msg->msg.listen_req.simask); break; case 35: /* SELECT_B2_PROTOCOL_REQ */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.select_b2_protocol_req.plci); printk(KERN_DEBUG " prot = 0x%02x\n", msg->msg.select_b2_protocol_req.protocol); if (msg->hdr.len >= 11) printk(KERN_DEBUG "No dlpd\n"); else actcapi_debug_dlpd(&msg->msg.select_b2_protocol_req.dlpd); break; case 44: /* CONNECT RESP */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_resp.plci); printk(KERN_DEBUG " CAUSE = 0x%02x\n", msg->msg.connect_resp.rejectcause); break; case 45: /* CONNECT ACTIVE RESP */ printk(KERN_DEBUG " PLCI = 0x%04x\n", msg->msg.connect_active_resp.plci); break; } } #endif
shaowei-wang/520board-v1-linux-2.6.21.x
drivers/isdn/act2000/capi.c
C
gpl-2.0
33,040
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Object struct Object_t; // System.Runtime.Remoting.Messaging.Header[] struct HeaderU5BU5D_t1378; // System.IAsyncResult struct IAsyncResult_t47; // System.AsyncCallback struct AsyncCallback_t48; #include "mscorlib_System_MulticastDelegate.h" // System.Runtime.Remoting.Messaging.HeaderHandler struct HeaderHandler_t1377 : public MulticastDelegate_t46 { };
Soufien/unityIntoIOSSample
SampleProject/il2cpp_output/mscorlib_System_Runtime_Remoting_Messaging_HeaderHandler.h
C
gpl-2.0
509
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants from numpy import array class is_near_arterial(Variable): """Boolean indicating if this gridcell is near an arterial, as specified by the arterial threshold (a constant). Distance is assumed to be measured from the "border" of the gridcell.""" distance_to_arterial = "distance_to_arterial" def dependencies(self): return [my_attribute_label(self.distance_to_arterial)] def compute(self, dataset_pool): return get_is_near_arterial(self.get_dataset().get_attribute(self.distance_to_arterial), dataset_pool.get_dataset('urbansim_constant')) def post_check(self, values, dataset_pool): self.do_check("x == False or x == True", values) def get_is_near_arterial(distance, urbansim_constant): length = UrbanSimLength(distance, urbansim_constant["gridcell_width"].units) return length.less_than(urbansim_constant["near_arterial_threshold_unit"]) from opus_core.tests import opus_unittest from opus_core.tests.utils.variable_tester import VariableTester from numpy import array class Tests(opus_unittest.OpusTestCase): def test_my_inputs( self ): # Assumes distance is measured from the gridcell border to the arterial. tester = VariableTester( __file__, package_order=['urbansim'], test_data={ 'gridcell':{ 'grid_id': array([1,2,3,4,5,6]), 'distance_to_arterial': array([0.0, 50.0, 99.0, 100.0, 101.0, 200.0]), }, 'urbansim_constant':{ 'cell_size': array([150]), 'near_arterial_threshold': array([100]), 'units': array(['meters']), } } ) should_be = array( [True, True, True, False, False, False] ) tester.test_is_equal_for_variable_defined_by_this_module(self, should_be) if __name__=='__main__': opus_unittest.main()
christianurich/VIBe2UrbanSim
3rdparty/opus/src/urbansim/gridcell/is_near_arterial.py
Python
gpl-2.0
2,343
<?php /** * Nooku Framework - http://nooku.org/framework * * @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-framework for the canonical source repository */ /** * Object Mixable Interface * * @author Johan Janssens <https://github.com/johanjanssens> * @package Koowa\Library\Object */ interface KObjectMixable { /** * Mixin an object * * When using mixin(), the calling object inherits the methods of the mixed in objects, in a LIFO order. * * @param mixed $identifier An KObjectIdentifier, identifier string or object implementing KObjectMixinInterface * @param array $config An optional associative array of configuration options * @return KObjectMixinInterface * @throws KObjectExceptionInvalidIdentifier If the identifier is not valid * @throws UnexpectedValueException If the mixin does not implement the KObjectMixinInterface */ public function mixin($identifier, $config = array()); /** * Checks if the object or one of it's mixin's inherits from a class. * * @param string|object $class The class to check * @return bool Returns TRUE if the object inherits from the class */ public function inherits($class); /** * Get a list of all the available methods * * This function returns an array of all the methods, both native and mixed in * * @return array An array */ public function getMethods(); }
kosmosby/medicine-prof
libraries/koowa/libraries/object/mixable.php
PHP
gpl-2.0
1,622
/* arch/arm/mach-msm/cpufreq.c * * MSM architecture cpufreq driver * * Copyright (C) 2007 Google, Inc. * Copyright (c) 2007-2010, Code Aurora Forum. All rights reserved. * Author: Mike A. Chan <[email protected]> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/earlysuspend.h> #include <linux/init.h> #include <linux/cpufreq.h> #include <linux/workqueue.h> #include <linux/completion.h> #include <linux/cpu.h> #include <linux/cpumask.h> #include <linux/sched.h> #include <linux/suspend.h> #include <mach/socinfo.h> #include "acpuclock.h" #ifdef CONFIG_SMP struct cpufreq_work_struct { struct work_struct work; struct cpufreq_policy *policy; struct completion complete; int frequency; int status; }; static DEFINE_PER_CPU(struct cpufreq_work_struct, cpufreq_work); static struct workqueue_struct *msm_cpufreq_wq; #endif struct cpufreq_suspend_t { struct mutex suspend_mutex; int device_suspended; }; static DEFINE_PER_CPU(struct cpufreq_suspend_t, cpufreq_suspend); static int override_cpu; static int set_cpu_freq(struct cpufreq_policy *policy, unsigned int new_freq) { int ret = 0; struct cpufreq_freqs freqs; freqs.old = policy->cur; if (override_cpu) { if (policy->cur == policy->max) return 0; else freqs.new = policy->max; } else freqs.new = new_freq; freqs.cpu = policy->cpu; cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE); ret = acpuclk_set_rate(policy->cpu, new_freq, SETRATE_CPUFREQ); if (!ret) cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE); return ret; } #ifdef CONFIG_SMP static void set_cpu_work(struct work_struct *work) { struct cpufreq_work_struct *cpu_work = container_of(work, struct cpufreq_work_struct, work); cpu_work->status = set_cpu_freq(cpu_work->policy, cpu_work->frequency); complete(&cpu_work->complete); } #endif static int msm_cpufreq_target(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation) { int ret = -EFAULT; int index; struct cpufreq_frequency_table *table; #ifdef CONFIG_SMP struct cpufreq_work_struct *cpu_work = NULL; cpumask_var_t mask; if (!cpu_active(policy->cpu)) { pr_info("cpufreq: cpu %d is not active.\n", policy->cpu); return -ENODEV; } if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; #endif mutex_lock(&per_cpu(cpufreq_suspend, policy->cpu).suspend_mutex); if (per_cpu(cpufreq_suspend, policy->cpu).device_suspended) { pr_debug("cpufreq: cpu%d scheduling frequency change " "in suspend.\n", policy->cpu); ret = -EFAULT; goto done; } table = cpufreq_frequency_get_table(policy->cpu); if (cpufreq_frequency_table_target(policy, table, target_freq, relation, &index)) { pr_err("cpufreq: invalid target_freq: %d\n", target_freq); ret = -EINVAL; goto done; } #ifdef CONFIG_CPU_FREQ_DEBUG pr_debug("CPU[%d] target %d relation %d (%d-%d) selected %d\n", policy->cpu, target_freq, relation, policy->min, policy->max, table[index].frequency); #endif #ifdef CONFIG_SMP cpu_work = &per_cpu(cpufreq_work, policy->cpu); cpu_work->policy = policy; cpu_work->frequency = table[index].frequency; cpu_work->status = -ENODEV; cpumask_clear(mask); cpumask_set_cpu(policy->cpu, mask); if (cpumask_equal(mask, &current->cpus_allowed)) { ret = set_cpu_freq(cpu_work->policy, cpu_work->frequency); goto done; } else { cancel_work_sync(&cpu_work->work); INIT_COMPLETION(cpu_work->complete); queue_work_on(policy->cpu, msm_cpufreq_wq, &cpu_work->work); wait_for_completion(&cpu_work->complete); } ret = cpu_work->status; #else ret = set_cpu_freq(policy, table[index].frequency); #endif done: #ifdef CONFIG_SMP free_cpumask_var(mask); #endif mutex_unlock(&per_cpu(cpufreq_suspend, policy->cpu).suspend_mutex); return ret; } static int msm_cpufreq_verify(struct cpufreq_policy *policy) { cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, policy->cpuinfo.max_freq); return 0; } static int __cpuinit msm_cpufreq_init(struct cpufreq_policy *policy) { int cur_freq; int index; struct cpufreq_frequency_table *table; #ifdef CONFIG_SMP struct cpufreq_work_struct *cpu_work = NULL; #endif if (cpu_is_apq8064()) return -ENODEV; table = cpufreq_frequency_get_table(policy->cpu); if (cpufreq_frequency_table_cpuinfo(policy, table)) { #ifdef CONFIG_MSM_CPU_FREQ_SET_MIN_MAX policy->cpuinfo.min_freq = CONFIG_MSM_CPU_FREQ_MIN; policy->cpuinfo.max_freq = CONFIG_MSM_CPU_FREQ_MAX; #endif } #ifdef CONFIG_MSM_CPU_FREQ_SET_MIN_MAX policy->min = CONFIG_MSM_CPU_FREQ_MIN; policy->max = CONFIG_MSM_CPU_FREQ_MAX; #endif cur_freq = acpuclk_get_rate(policy->cpu); if (cpufreq_frequency_table_target(policy, table, cur_freq, CPUFREQ_RELATION_H, &index) && cpufreq_frequency_table_target(policy, table, cur_freq, CPUFREQ_RELATION_L, &index)) { pr_info("cpufreq: cpu%d at invalid freq: %d\n", policy->cpu, cur_freq); return -EINVAL; } if (cur_freq != table[index].frequency) { int ret = 0; ret = acpuclk_set_rate(policy->cpu, table[index].frequency, SETRATE_CPUFREQ); if (ret) return ret; pr_info("cpufreq: cpu%d init at %d switching to %d\n", policy->cpu, cur_freq, table[index].frequency); cur_freq = table[index].frequency; } policy->cur = cur_freq; policy->cpuinfo.transition_latency = acpuclk_get_switch_time() * NSEC_PER_USEC; #ifdef CONFIG_SMP cpu_work = &per_cpu(cpufreq_work, policy->cpu); INIT_WORK(&cpu_work->work, set_cpu_work); init_completion(&cpu_work->complete); #endif return 0; } static int msm_cpufreq_suspend(struct cpufreq_policy *policy) { int cpu; for_each_possible_cpu(cpu) { per_cpu(cpufreq_suspend, cpu).device_suspended = 1; } return 0; } static int msm_cpufreq_resume(struct cpufreq_policy *policy) { int cpu; for_each_possible_cpu(cpu) { per_cpu(cpufreq_suspend, cpu).device_suspended = 0; } return 0; } static ssize_t store_mfreq(struct sysdev_class *class, struct sysdev_class_attribute *attr, const char *buf, size_t count) { u64 val; if (strict_strtoull(buf, 0, &val) < 0) { pr_err("Invalid parameter to mfreq\n"); return 0; } if (val) override_cpu = 1; else override_cpu = 0; return count; } static SYSDEV_CLASS_ATTR(mfreq, 0200, NULL, store_mfreq); static struct freq_attr *msm_freq_attr[] = { &cpufreq_freq_attr_scaling_available_freqs, NULL, }; static struct cpufreq_driver msm_cpufreq_driver = { /* lps calculations are handled here. */ .flags = CPUFREQ_STICKY | CPUFREQ_CONST_LOOPS, .init = msm_cpufreq_init, .verify = msm_cpufreq_verify, .target = msm_cpufreq_target, .suspend = msm_cpufreq_suspend, .resume = msm_cpufreq_resume, .name = "msm", .attr = msm_freq_attr, }; static int __init msm_cpufreq_register(void) { int cpu; int err = sysfs_create_file(&cpu_sysdev_class.kset.kobj, &attr_mfreq.attr); if (err) pr_err("Failed to create sysfs mfreq\n"); for_each_possible_cpu(cpu) { mutex_init(&(per_cpu(cpufreq_suspend, cpu).suspend_mutex)); per_cpu(cpufreq_suspend, cpu).device_suspended = 0; } #ifdef CONFIG_SMP msm_cpufreq_wq = create_workqueue("msm-cpufreq"); #endif return cpufreq_register_driver(&msm_cpufreq_driver); } late_initcall(msm_cpufreq_register);
BytecodeMe/vanquish
arch/arm/mach-msm/cpufreq.c
C
gpl-2.0
7,616
/** * \file drawMath.c * \brief outputs the math of a model as a dot graph * \author Sarah Keating * * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. */ #include <stdio.h> #include <stdlib.h> #include <sbml/util/util.h> #include <sbml/SBMLTypes.h> #include "FormulaGraphvizFormatter.h" static int noClusters = 0; FILE * fout; /** * @return the given formula AST as a directed graph. The caller * owns the returned string and is responsible for freeing it. */ char * SBML_formulaToDot (const ASTNode_t *tree) { StringBuffer_t *sb = StringBuffer_create(128); char *name; char *s; if (FormulaGraphvizFormatter_isFunction(tree) || ASTNode_isOperator(tree)) { FormulaGraphvizFormatter_visit(NULL, tree, sb); } else { name = FormulaGraphvizFormatter_format(tree); StringBuffer_append(sb, name); } StringBuffer_append(sb, "}\n"); s = StringBuffer_getBuffer(sb); free(sb); return s; } /** * @return true (non-zero) if the given ASTNode is to formatted as a * function. */ int FormulaGraphvizFormatter_isFunction (const ASTNode_t *node) { return ASTNode_isFunction (node) || ASTNode_isLambda (node) || ASTNode_isLogical (node) || ASTNode_isRelational(node); } /** * Formats the given ASTNode as a directed graph token and returns the result as * a string. */ char * FormulaGraphvizFormatter_format (const ASTNode_t *node) { StringBuffer_t *p = StringBuffer_create(128); char *s = NULL; if (ASTNode_isOperator(node)) { s = FormulaGraphvizFormatter_formatOperator(node); } else if (ASTNode_isFunction(node)) { s = FormulaGraphvizFormatter_formatFunction(node); } else if (ASTNode_isInteger(node)) { StringBuffer_appendInt(p, ASTNode_getInteger(node)); s = StringBuffer_toString(p); } else if (ASTNode_isRational(node)) { s = FormulaGraphvizFormatter_formatRational(node); } else if (ASTNode_isReal(node)) { s = FormulaGraphvizFormatter_formatReal(node); } else if ( !ASTNode_isUnknown(node) ) { if (ASTNode_getName(node) == NULL) { StringBuffer_append(p, "unknown"); } else { StringBuffer_append(p, ASTNode_getName(node)); } s = StringBuffer_toString(p); } free(p); return s; } /** * Since graphviz will interpret identical names as referring to * the same node presentation-wise it is better if each function node * has a unique name. * * Returns the name with the name of the first child * prepended * * THIS COULD BE DONE BETTER */ char * FormulaGraphvizFormatter_getUniqueName (const ASTNode_t *node) { StringBuffer_t *p = StringBuffer_create(128); char *s = NULL; if (ASTNode_isOperator(node)) { s = FormulaGraphvizFormatter_OperatorGetUniqueName(node); } else if (ASTNode_isFunction(node)) { s = FormulaGraphvizFormatter_FunctionGetUniqueName(node); } else if (ASTNode_isInteger(node)) { StringBuffer_appendInt(p, ASTNode_getInteger(node)); s = StringBuffer_toString(p); } else if (ASTNode_isRational(node)) { s = FormulaGraphvizFormatter_formatRational(node); } else if (ASTNode_isReal(node)) { s = FormulaGraphvizFormatter_formatReal(node); } else if ( !ASTNode_isUnknown(node) ) { StringBuffer_append(p, ASTNode_getName(node)); s = StringBuffer_toString(p); } free(p); return s; } /** * Formats the given ASTNode as a directed graph function name and returns the * result as a string. */ char * FormulaGraphvizFormatter_formatFunction (const ASTNode_t *node) { char *s; StringBuffer_t *p = StringBuffer_create(128); ASTNodeType_t type = ASTNode_getType(node); switch (type) { case AST_FUNCTION_ARCCOS: s = "acos"; break; case AST_FUNCTION_ARCSIN: s = "asin"; break; case AST_FUNCTION_ARCTAN: s = "atan"; break; case AST_FUNCTION_CEILING: s = "ceil"; break; case AST_FUNCTION_LN: s = "log"; break; case AST_FUNCTION_POWER: s = "pow"; break; default: if (ASTNode_getName(node) == NULL) { StringBuffer_append(p, "unknown"); } else { StringBuffer_append(p, ASTNode_getName(node)); } s = StringBuffer_toString(p); break; } free(p); return s; } /** * Since graphviz will interpret identical names as referring to * the same node presentation-wise it is better if each function node * has a unique name. * * Returns the name of the function with the name of the first child * prepended * * THIS COULD BE DONE BETTER */ char * FormulaGraphvizFormatter_FunctionGetUniqueName (const ASTNode_t *node) { char *s; StringBuffer_t *p = StringBuffer_create(128); ASTNodeType_t type = ASTNode_getType(node); if (ASTNode_getNumChildren(node) != 0) { const char* name = ASTNode_getName(ASTNode_getChild(node,0)); if (name != NULL) StringBuffer_append(p, name); } else { StringBuffer_append(p, "unknown"); } switch (type) { case AST_FUNCTION_ARCCOS: StringBuffer_append(p, "acos"); break; case AST_FUNCTION_ARCSIN: StringBuffer_append(p, "asin"); break; case AST_FUNCTION_ARCTAN: StringBuffer_append(p, "atan"); break; case AST_FUNCTION_CEILING: StringBuffer_append(p, "ceil"); break; case AST_FUNCTION_LN: StringBuffer_append(p, "log"); break; case AST_FUNCTION_POWER: StringBuffer_append(p, "pow"); break; default: if (ASTNode_getName(node) != NULL) { StringBuffer_append(p, ASTNode_getName(node)); } break; } s = StringBuffer_toString(p); free(p); return s; } /** * Formats the given ASTNode as a directed graph operator and returns the result * as a string. */ char * FormulaGraphvizFormatter_formatOperator (const ASTNode_t *node) { char *s; ASTNodeType_t type = ASTNode_getType(node); StringBuffer_t *p = StringBuffer_create(128); switch (type) { case AST_TIMES: s = "times"; break; case AST_DIVIDE: s = "divide"; break; case AST_PLUS: s = "plus"; break; case AST_MINUS: s = "minus"; break; case AST_POWER: s = "power"; break; default: StringBuffer_appendChar(p, ASTNode_getCharacter(node)); s = StringBuffer_toString(p); break; } free(p); return s; } /** * Since graphviz will interpret identical names as referring to * the same node presentation-wise it is better if each function node * has a unique name. * * Returns the name of the operator with the name of the first child * prepended * * THIS COULD BE DONE BETTER */ char * FormulaGraphvizFormatter_OperatorGetUniqueName (const ASTNode_t *node) { char *s; char number[10]; StringBuffer_t *p = StringBuffer_create(128); ASTNodeType_t type = ASTNode_getType(node); if (FormulaGraphvizFormatter_isFunction(ASTNode_getChild(node,0)) || ASTNode_isOperator(ASTNode_getChild(node,0))) { StringBuffer_append(p, "func"); } else { if (ASTNode_isInteger(ASTNode_getChild(node, 0))) { sprintf(number, "%d", (int)ASTNode_getInteger(ASTNode_getChild(node, 0))); StringBuffer_append(p, number); } else if (ASTNode_isReal(ASTNode_getChild(node, 0))) { sprintf(number, "%ld", ASTNode_getNumerator(ASTNode_getChild(node, 0))); StringBuffer_append(p, number); } else { StringBuffer_append(p, ASTNode_getName(ASTNode_getChild(node,0))); } } switch (type) { case AST_TIMES: StringBuffer_append(p, "times"); break; case AST_DIVIDE: StringBuffer_append(p, "divide"); break; case AST_PLUS: StringBuffer_append(p, "plus"); break; case AST_MINUS: StringBuffer_append(p, "minus"); break; case AST_POWER: StringBuffer_append(p, "power"); break; default: StringBuffer_appendChar(p, ASTNode_getCharacter(node)); break; } s = StringBuffer_toString(p); free(p); return s; } /** * Formats the given ASTNode as a rational number and returns the result as * a string. This amounts to: * * "(numerator/denominator)" */ char * FormulaGraphvizFormatter_formatRational (const ASTNode_t *node) { char *s; StringBuffer_t *p = StringBuffer_create(128); StringBuffer_appendChar( p, '('); StringBuffer_appendInt ( p, ASTNode_getNumerator(node) ); StringBuffer_appendChar( p, '/'); StringBuffer_appendInt ( p, ASTNode_getDenominator(node) ); StringBuffer_appendChar( p, ')'); s = StringBuffer_toString(p); free(p); return s; } /** * Formats the given ASTNode as a real number and returns the result as * a string. */ char * FormulaGraphvizFormatter_formatReal (const ASTNode_t *node) { StringBuffer_t *p = StringBuffer_create(128); double value = ASTNode_getReal(node); int sign; char *s; if (util_isNaN(value)) { s = "NaN"; } else if ((sign = util_isInf(value)) != 0) { if (sign == -1) { s = "-INF"; } else { s = "INF"; } } else if (util_isNegZero(value)) { s = "-0"; } else { StringBuffer_appendReal(p, value); s = StringBuffer_toString(p); } free(p); return s; } /** * Visits the given ASTNode node. This function is really just a * dispatcher to either FormulaGraphvizFormatter_visitFunction() or * FormulaGraphvizFormatter_visitOther(). */ void FormulaGraphvizFormatter_visit (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { if (ASTNode_isLog10(node)) { FormulaGraphvizFormatter_visitLog10(parent, node, sb); } else if (ASTNode_isSqrt(node)) { FormulaGraphvizFormatter_visitSqrt(parent, node, sb); } else if (FormulaGraphvizFormatter_isFunction(node)) { FormulaGraphvizFormatter_visitFunction(parent, node, sb); } else if (ASTNode_isUMinus(node)) { FormulaGraphvizFormatter_visitUMinus(parent, node, sb); } else { FormulaGraphvizFormatter_visitOther(parent, node, sb); } } /** * Visits the given ASTNode as a function. For this node only the * traversal is preorder. * Writes the function as a directed graph and appends the result * to the StringBuffer. */ void FormulaGraphvizFormatter_visitFunction (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { unsigned int numChildren = ASTNode_getNumChildren(node); unsigned int n; char *name; char *uniqueName; uniqueName = FormulaGraphvizFormatter_getUniqueName(node); name = FormulaGraphvizFormatter_format(node); StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " [shape=box, label="); StringBuffer_append(sb, name); StringBuffer_append(sb, "];\n"); if (parent != NULL) { name = FormulaGraphvizFormatter_getUniqueName(node); uniqueName = FormulaGraphvizFormatter_getUniqueName(parent); if(strcmp(name, uniqueName)) { StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " -> "); StringBuffer_append(sb, name); StringBuffer_append(sb, ";\n"); } } if (numChildren > 0) { FormulaGraphvizFormatter_visit( node, ASTNode_getChild(node, 0), sb ); } for (n = 1; n < numChildren; n++) { FormulaGraphvizFormatter_visit( node, ASTNode_getChild(node, n), sb ); } } /** * Visits the given ASTNode as the function "log(10, x)" and in doing so, * formats it as "log10(x)" (where x is any subexpression). * Writes the function as a directed graph and appends the result * to the StringBuffer. * * A seperate function may not be strictly speaking necessary for graphs */ void FormulaGraphvizFormatter_visitLog10 (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { char *uniqueName = FormulaGraphvizFormatter_getUniqueName(node); char *name = FormulaGraphvizFormatter_format(node); StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " [shape=box, label="); StringBuffer_append(sb, name); StringBuffer_append(sb, "];\n"); FormulaGraphvizFormatter_visit(node, ASTNode_getChild(node, 1), sb); } /** * Visits the given ASTNode as the function "root(2, x)" and in doing so, * formats it as "sqrt(x)" (where x is any subexpression). * Writes the function as a directed graph and appends the result * to the StringBuffer. * * A seperate function may not be strictly speaking necessary for graphs */ void FormulaGraphvizFormatter_visitSqrt (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { char *uniqueName = FormulaGraphvizFormatter_getUniqueName(node); char *name = FormulaGraphvizFormatter_format(node); StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " [shape=box, label="); StringBuffer_append(sb, name); StringBuffer_append(sb, "];\n"); FormulaGraphvizFormatter_visit(node, ASTNode_getChild(node, 1), sb); } /** * Visits the given ASTNode as a unary minus. For this node only the * traversal is preorder. * Writes the function as a directed graph and appends the result * to the StringBuffer. */ void FormulaGraphvizFormatter_visitUMinus (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { char *uniqueName = FormulaGraphvizFormatter_getUniqueName(node); char *name = FormulaGraphvizFormatter_format(node); StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " [shape=box, label="); StringBuffer_append(sb, name); StringBuffer_append(sb, "];\n"); if (parent != NULL) { uniqueName = FormulaGraphvizFormatter_getUniqueName(parent); name = FormulaGraphvizFormatter_getUniqueName(node); if(strcmp(name, uniqueName)) { StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " -> "); StringBuffer_append(sb, name); StringBuffer_append(sb, ";\n"); } } FormulaGraphvizFormatter_visit ( node, ASTNode_getLeftChild(node), sb ); } /** * Visits the given ASTNode and continues the inorder traversal. * Writes the function as a directed graph and appends the result * to the StringBuffer. */ void FormulaGraphvizFormatter_visitOther (const ASTNode_t *parent, const ASTNode_t *node, StringBuffer_t *sb ) { unsigned int numChildren = ASTNode_getNumChildren(node); char *name; char *uniqueName; if (numChildren > 0) { uniqueName = FormulaGraphvizFormatter_getUniqueName(node); name = FormulaGraphvizFormatter_format(node); StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " [shape=box, label="); StringBuffer_append(sb, name); StringBuffer_append(sb, "];\n"); FormulaGraphvizFormatter_visit( node, ASTNode_getLeftChild(node), sb ); } if (parent != NULL) { name = FormulaGraphvizFormatter_getUniqueName(node); uniqueName = FormulaGraphvizFormatter_getUniqueName(parent); if(strcmp(name, uniqueName)) { StringBuffer_append(sb, uniqueName); StringBuffer_append(sb, " -> "); StringBuffer_append(sb, name); StringBuffer_append(sb, ";\n"); } } if (numChildren > 1) { FormulaGraphvizFormatter_visit( node, ASTNode_getRightChild(node), sb ); } } void printFunctionDefinition (unsigned int n, FunctionDefinition_t *fd) { const ASTNode_t *math; char *formula; if ( FunctionDefinition_isSetMath(fd) ) { math = FunctionDefinition_getMath(fd); /* Print function body. */ if (ASTNode_getNumChildren(math) == 0) { printf("(no body defined)"); } else { math = ASTNode_getChild(math, ASTNode_getNumChildren(math) - 1); formula = SBML_formulaToDot(math); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"FunctionDefinition: %s\";\n%s\n", FunctionDefinition_getId(fd), formula); free(formula); noClusters++; } } } void printRuleMath (unsigned int n, Rule_t *r) { char *formula; if ( Rule_isSetMath(r) ) { formula = SBML_formulaToDot( Rule_getMath(r)); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"Rule: %u\";\n%s\n", n, formula); free(formula); noClusters++; } } void printReactionMath (unsigned int n, Reaction_t *r) { char *formula; KineticLaw_t *kl; if (Reaction_isSetKineticLaw(r)) { kl = Reaction_getKineticLaw(r); if ( KineticLaw_isSetMath(kl) ) { formula = SBML_formulaToDot( KineticLaw_getMath(kl) ); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"Reaction: %s\";\n%s\n", Reaction_getId(r), formula); free(formula); noClusters++; } } } void printEventAssignmentMath (unsigned int n, EventAssignment_t *ea) { const char *variable; char *formula; if ( EventAssignment_isSetMath(ea) ) { variable = EventAssignment_getVariable(ea); formula = SBML_formulaToDot( EventAssignment_getMath(ea) ); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"EventAssignment: %u\";\n", n); fprintf(fout, "%s [shape=box];\n%s -> %s\n", variable, variable, formula); noClusters++; free(formula); } } void printEventMath (unsigned int n, Event_t *e) { char *formula; unsigned int i; if ( Event_isSetDelay(e) ) { formula = SBML_formulaToDot( Delay_getMath(Event_getDelay(e)) ); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"Event %s delay:\";\n%s\n", Event_getId(e), formula); free(formula); noClusters++; } if ( Event_isSetTrigger(e) ) { formula = SBML_formulaToDot( Trigger_getMath(Event_getTrigger(e)) ); fprintf(fout, "subgraph cluster%u {\n", noClusters); fprintf(fout, "label=\"Event %s trigger:\";\n%s\n", Event_getId(e), formula); noClusters++; free(formula); } for (i = 0; i < Event_getNumEventAssignments(e); ++i) { printEventAssignmentMath(i + 1, Event_getEventAssignment(e, i)); } } void printMath (Model_t *m) { unsigned int n; /* a digraph must have a name thus * need to check that Model_getId does not return NULL * and provide a name if it does */ if (Model_getId(m) != NULL) { fprintf(fout, "digraph %s {\n", Model_getId(m)); } else { fprintf(fout, "digraph example {\n"); } fprintf(fout, "compound=true;\n"); for (n = 0; n < Model_getNumFunctionDefinitions(m); ++n) { printFunctionDefinition(n + 1, Model_getFunctionDefinition(m, n)); } for (n = 0; n < Model_getNumRules(m); ++n) { printRuleMath(n + 1, Model_getRule(m, n)); } printf("\n"); for (n = 0; n < Model_getNumReactions(m); ++n) { printReactionMath(n + 1, Model_getReaction(m, n)); } printf("\n"); for (n = 0; n < Model_getNumEvents(m); ++n) { printEventMath(n + 1, Model_getEvent(m, n)); } fprintf(fout, "}\n"); } int main (int argc, char *argv[]) { SBMLDocument_t *d; Model_t *m; if (argc != 3) { printf("\n usage: drawMath <sbml filename> <output dot filename>\n\n"); return 1; } d = readSBML(argv[1]); m = SBMLDocument_getModel(d); SBMLDocument_printErrors(d, stdout); if ((fout = fopen( argv[2], "w" )) == NULL ) { printf( "The output file was not opened\n" ); } else { printMath(m); fclose(fout); } SBMLDocument_free(d); return 0; }
dilawar/moose-full
dependencies/libsbml-5.9.0/examples/c/drawMath.c
C
gpl-2.0
20,197
/* * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved. * Copyright (C) 2009 Jan Michael Alonzo * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "AccessibilityController.h" #if HAVE(ACCESSIBILITY) #include "AccessibilityCallbacks.h" #include "AccessibilityUIElement.h" #include "DumpRenderTree.h" #include <atk/atk.h> bool loggingAccessibilityEvents = false; AccessibilityController::AccessibilityController() : m_globalNotificationHandler(nullptr) { } AccessibilityController::~AccessibilityController() { } AccessibilityUIElement AccessibilityController::elementAtPoint(int x, int y) { // FIXME: implement return nullptr; } void AccessibilityController::platformResetToConsistentState() { } void AccessibilityController::setLogFocusEvents(bool) { } void AccessibilityController::setLogScrollingStartEvents(bool) { } void AccessibilityController::setLogValueChangeEvents(bool) { } void AccessibilityController::setLogAccessibilityEvents(bool logAccessibilityEvents) { if (logAccessibilityEvents == loggingAccessibilityEvents) return; if (!logAccessibilityEvents) { loggingAccessibilityEvents = false; disconnectAccessibilityCallbacks(); return; } connectAccessibilityCallbacks(); loggingAccessibilityEvents = true; } bool AccessibilityController::addNotificationListener(JSObjectRef functionCallback) { if (!functionCallback) return false; // Only one global notification listener. if (m_globalNotificationHandler) return false; m_globalNotificationHandler = AccessibilityNotificationHandler::create(); m_globalNotificationHandler->setNotificationFunctionCallback(functionCallback); return true; } void AccessibilityController::removeNotificationListener() { // Programmers should not be trying to remove a listener that's already removed. ASSERT(m_globalNotificationHandler); m_globalNotificationHandler = nullptr; } JSRetainPtr<JSStringRef> AccessibilityController::platformName() const { JSRetainPtr<JSStringRef> platformName(Adopt, JSStringCreateWithUTF8CString("atk")); return platformName; } AtkObject* AccessibilityController::childElementById(AtkObject* parent, const char* id) { if (!ATK_IS_OBJECT(parent)) return nullptr; bool parentFound = false; AtkAttributeSet* attributeSet(atk_object_get_attributes(parent)); for (AtkAttributeSet* attributes = attributeSet; attributes; attributes = attributes->next) { AtkAttribute* attribute = static_cast<AtkAttribute*>(attributes->data); if (!strcmp(attribute->name, "html-id")) { if (!strcmp(attribute->value, id)) parentFound = true; break; } } atk_attribute_set_free(attributeSet); if (parentFound) return parent; int childCount = atk_object_get_n_accessible_children(parent); for (int i = 0; i < childCount; i++) { AtkObject* result = childElementById(atk_object_ref_accessible_child(parent, i), id); if (ATK_IS_OBJECT(result)) return result; } return nullptr; } #endif
loveyoupeng/rt
modules/web/src/main/native/Tools/DumpRenderTree/atk/AccessibilityControllerAtk.cpp
C++
gpl-2.0
4,399
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/slab.h> #include <linux/kthread.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/uaccess.h> #include <linux/wait.h> #include <linux/mutex.h> #include <linux/msm_audio_ion.h> #include <asm/mach-types.h> #include <mach/qdsp6v2/rtac.h> #include <mach/socinfo.h> #include <mach/qdsp6v2/apr_tal.h> #include "sound/apr_audio-v2.h" #include "sound/q6afe-v2.h" #include "audio_acdb.h" #include "q6voice.h" #define TIMEOUT_MS 500 #define CMD_STATUS_SUCCESS 0 #define CMD_STATUS_FAIL 1 /* CVP CAL Size: 245760 = 240 * 1024 */ #define CVP_CAL_SIZE 245760 /* CVS CAL Size: 49152 = 48 * 1024 */ #define CVS_CAL_SIZE 49152 enum { VOC_TOKEN_NONE, VOIP_MEM_MAP_TOKEN, VOC_CAL_MEM_MAP_TOKEN, }; static struct common_data common; static int voice_send_enable_vocproc_cmd(struct voice_data *v); static int voice_send_netid_timing_cmd(struct voice_data *v); static int voice_send_attach_vocproc_cmd(struct voice_data *v); static int voice_send_set_device_cmd(struct voice_data *v); static int voice_send_disable_vocproc_cmd(struct voice_data *v); static int voice_send_vol_index_cmd(struct voice_data *v); static int voice_send_mvm_unmap_memory_physical_cmd(struct voice_data *v, uint32_t mem_handle); static int voice_send_mvm_cal_network_cmd(struct voice_data *v); static int voice_send_mvm_media_type_cmd(struct voice_data *v); static int voice_send_cvs_data_exchange_mode_cmd(struct voice_data *v); static int voice_send_cvs_packet_exchange_config_cmd(struct voice_data *v); static int voice_set_packet_exchange_mode_and_config(uint32_t session_id, uint32_t mode); static int voice_send_cvs_register_cal_cmd(struct voice_data *v); static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v); static int voice_send_cvp_register_dev_cfg_cmd(struct voice_data *v); static int voice_send_cvp_deregister_dev_cfg_cmd(struct voice_data *v); static int voice_send_cvp_register_cal_cmd(struct voice_data *v); static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v); static int voice_send_cvp_register_vol_cal_cmd(struct voice_data *v); static int voice_send_cvp_deregister_vol_cal_cmd(struct voice_data *v); static int voice_cvs_stop_playback(struct voice_data *v); static int voice_cvs_start_playback(struct voice_data *v); static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode); static int voice_cvs_stop_record(struct voice_data *v); static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv); static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv); static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv); static int voice_send_set_pp_enable_cmd(struct voice_data *v, uint32_t module_id, int enable); static struct voice_data *voice_get_session_by_idx(int idx); static u16 voice_get_mvm_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: mvm_handle %d\n", __func__, v->mvm_handle); return v->mvm_handle; } static void voice_set_mvm_handle(struct voice_data *v, u16 mvm_handle) { pr_debug("%s: mvm_handle %d\n", __func__, mvm_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->mvm_handle = mvm_handle; } static u16 voice_get_cvs_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: cvs_handle %d\n", __func__, v->cvs_handle); return v->cvs_handle; } static void voice_set_cvs_handle(struct voice_data *v, u16 cvs_handle) { pr_debug("%s: cvs_handle %d\n", __func__, cvs_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->cvs_handle = cvs_handle; } static u16 voice_get_cvp_handle(struct voice_data *v) { if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return 0; } pr_debug("%s: cvp_handle %d\n", __func__, v->cvp_handle); return v->cvp_handle; } static void voice_set_cvp_handle(struct voice_data *v, u16 cvp_handle) { pr_debug("%s: cvp_handle %d\n", __func__, cvp_handle); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return; } v->cvp_handle = cvp_handle; } char *voc_get_session_name(u32 session_id) { char *session_name = NULL; if (session_id == common.voice[VOC_PATH_PASSIVE].session_id) { session_name = VOICE_SESSION_NAME; } else if (session_id == common.voice[VOC_PATH_VOLTE_PASSIVE].session_id) { session_name = VOLTE_SESSION_NAME; } else if (session_id == common.voice[VOC_PATH_FULL].session_id) { session_name = VOIP_SESSION_NAME; } return session_name; } uint32_t voc_get_session_id(char *name) { u32 session_id = 0; if (name != NULL) { if (!strncmp(name, "Voice session", 13)) session_id = common.voice[VOC_PATH_PASSIVE].session_id; else if (!strncmp(name, "Voice2 session", 14)) session_id = common.voice[VOC_PATH_VOICE2_PASSIVE].session_id; else if (!strncmp(name, "VoLTE session", 13)) session_id = common.voice[VOC_PATH_VOLTE_PASSIVE].session_id; else session_id = common.voice[VOC_PATH_FULL].session_id; pr_debug("%s: %s has session id 0x%x\n", __func__, name, session_id); } return session_id; } static struct voice_data *voice_get_session(u32 session_id) { struct voice_data *v = NULL; switch (session_id) { case VOICE_SESSION_VSID: v = &common.voice[VOC_PATH_PASSIVE]; break; case VOICE2_SESSION_VSID: v = &common.voice[VOC_PATH_VOICE2_PASSIVE]; break; case VOLTE_SESSION_VSID: v = &common.voice[VOC_PATH_VOLTE_PASSIVE]; break; case VOIP_SESSION_VSID: v = &common.voice[VOC_PATH_FULL]; break; case ALL_SESSION_VSID: break; default: pr_err("%s: Invalid session_id : %x\n", __func__, session_id); break; } pr_debug("%s:session_id 0x%x session handle 0x%x\n", __func__, session_id, (unsigned int)v); return v; } int voice_get_idx_for_session(u32 session_id) { int idx = 0; switch (session_id) { case VOICE_SESSION_VSID: idx = VOC_PATH_PASSIVE; break; case VOICE2_SESSION_VSID: idx = VOC_PATH_VOICE2_PASSIVE; break; case VOLTE_SESSION_VSID: idx = VOC_PATH_VOLTE_PASSIVE; break; case VOIP_SESSION_VSID: idx = VOC_PATH_FULL; break; case ALL_SESSION_VSID: idx = MAX_VOC_SESSIONS - 1; break; default: pr_err("%s: Invalid session_id : %x\n", __func__, session_id); break; } return idx; } static struct voice_data *voice_get_session_by_idx(int idx) { return ((idx < 0 || idx >= MAX_VOC_SESSIONS) ? NULL : &common.voice[idx]); } static bool is_voice_session(u32 session_id) { return (session_id == common.voice[VOC_PATH_PASSIVE].session_id); } static bool is_voip_session(u32 session_id) { return (session_id == common.voice[VOC_PATH_FULL].session_id); } static bool is_volte_session(u32 session_id) { return (session_id == common.voice[VOC_PATH_VOLTE_PASSIVE].session_id); } static bool is_voice2_session(u32 session_id) { return (session_id == common.voice[VOC_PATH_VOICE2_PASSIVE].session_id); } static bool is_voc_state_active(int voc_state) { if ((voc_state == VOC_RUN) || (voc_state == VOC_CHANGE) || (voc_state == VOC_STANDBY)) return true; return false; } static void voc_set_error_state(uint16_t reset_proc) { struct voice_data *v = NULL; int i; for (i = 0; i < MAX_VOC_SESSIONS; i++) { if (reset_proc == APR_DEST_MODEM && i == VOC_PATH_FULL) continue; v = &common.voice[i]; if (v != NULL) v->voc_state = VOC_ERROR; } } static bool is_other_session_active(u32 session_id) { int i; bool ret = false; /* Check if there is other active session except the input one */ for (i = 0; i < MAX_VOC_SESSIONS; i++) { if (common.voice[i].session_id == session_id) continue; if ((common.voice[i].voc_state == VOC_RUN) || (common.voice[i].voc_state == VOC_CHANGE) || (common.voice[i].voc_state == VOC_STANDBY)) { ret = true; break; } } pr_debug("%s: ret %d\n", __func__, ret); return ret; } static void init_session_id(void) { common.voice[VOC_PATH_PASSIVE].session_id = VOICE_SESSION_VSID; common.voice[VOC_PATH_VOLTE_PASSIVE].session_id = VOLTE_SESSION_VSID; common.voice[VOC_PATH_VOICE2_PASSIVE].session_id = VOICE2_SESSION_VSID; common.voice[VOC_PATH_FULL].session_id = VOIP_SESSION_VSID; } static int voice_apr_register(void) { void *modem_mvm, *modem_cvs, *modem_cvp; pr_debug("%s\n", __func__); mutex_lock(&common.common_lock); /* register callback to APR */ if (common.apr_q6_mvm == NULL) { pr_debug("%s: Start to register MVM callback\n", __func__); common.apr_q6_mvm = apr_register("ADSP", "MVM", qdsp_mvm_callback, 0xFFFFFFFF, &common); if (common.apr_q6_mvm == NULL) { pr_err("%s: Unable to register MVM\n", __func__); goto err; } /* * Register with modem for SSR callback. The APR handle * is not stored since it is used only to receive notifications * and not for communication */ modem_mvm = apr_register("MODEM", "MVM", qdsp_mvm_callback, 0xFFFFFFFF, &common); if (modem_mvm == NULL) pr_err("%s: Unable to register MVM for MODEM\n", __func__); } if (common.apr_q6_cvs == NULL) { pr_debug("%s: Start to register CVS callback\n", __func__); common.apr_q6_cvs = apr_register("ADSP", "CVS", qdsp_cvs_callback, 0xFFFFFFFF, &common); if (common.apr_q6_cvs == NULL) { pr_err("%s: Unable to register CVS\n", __func__); goto err; } rtac_set_voice_handle(RTAC_CVS, common.apr_q6_cvs); /* * Register with modem for SSR callback. The APR handle * is not stored since it is used only to receive notifications * and not for communication */ modem_cvs = apr_register("MODEM", "CVS", qdsp_cvs_callback, 0xFFFFFFFF, &common); if (modem_cvs == NULL) pr_err("%s: Unable to register CVS for MODEM\n", __func__); } if (common.apr_q6_cvp == NULL) { pr_debug("%s: Start to register CVP callback\n", __func__); common.apr_q6_cvp = apr_register("ADSP", "CVP", qdsp_cvp_callback, 0xFFFFFFFF, &common); if (common.apr_q6_cvp == NULL) { pr_err("%s: Unable to register CVP\n", __func__); goto err; } rtac_set_voice_handle(RTAC_CVP, common.apr_q6_cvp); /* * Register with modem for SSR callback. The APR handle * is not stored since it is used only to receive notifications * and not for communication */ modem_cvp = apr_register("MODEM", "CVP", qdsp_cvp_callback, 0xFFFFFFFF, &common); if (modem_cvp == NULL) pr_err("%s: Unable to register CVP for MODEM\n", __func__); } mutex_unlock(&common.common_lock); return 0; err: if (common.apr_q6_cvs != NULL) { apr_deregister(common.apr_q6_cvs); common.apr_q6_cvs = NULL; rtac_set_voice_handle(RTAC_CVS, NULL); } if (common.apr_q6_mvm != NULL) { apr_deregister(common.apr_q6_mvm); common.apr_q6_mvm = NULL; } mutex_unlock(&common.common_lock); return -ENODEV; } static int voice_send_dual_control_cmd(struct voice_data *v) { int ret = 0; struct mvm_modem_dual_control_session_cmd mvm_voice_ctl_cmd; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } pr_debug("%s: VoLTE command to MVM\n", __func__); if (is_volte_session(v->session_id) || is_voice_session(v->session_id) || is_voice2_session(v->session_id)) { mvm_handle = voice_get_mvm_handle(v); mvm_voice_ctl_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_voice_ctl_cmd.hdr.pkt_size = APR_PKT_SIZE( APR_HDR_SIZE, sizeof(mvm_voice_ctl_cmd) - APR_HDR_SIZE); pr_debug("%s: send mvm Voice Ctl pkt size = %d\n", __func__, mvm_voice_ctl_cmd.hdr.pkt_size); mvm_voice_ctl_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_voice_ctl_cmd.hdr.dest_port = mvm_handle; mvm_voice_ctl_cmd.hdr.token = 0; mvm_voice_ctl_cmd.hdr.opcode = VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL; mvm_voice_ctl_cmd.voice_ctl.enable_flag = true; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_voice_ctl_cmd); if (ret < 0) { pr_err("%s: Error sending MVM Voice CTL CMD\n", __func__); ret = -EINVAL; goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); ret = -EINVAL; goto fail; } } ret = 0; fail: return ret; } static int voice_create_mvm_cvs_session(struct voice_data *v) { int ret = 0; struct mvm_create_ctl_session_cmd mvm_session_cmd; struct cvs_create_passive_ctl_session_cmd cvs_session_cmd; struct cvs_create_full_ctl_session_cmd cvs_full_ctl_cmd; struct mvm_attach_stream_cmd attach_stream_cmd; void *apr_mvm, *apr_cvs, *apr_cvp; u16 mvm_handle, cvs_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvs = common.apr_q6_cvs; apr_cvp = common.apr_q6_cvp; if (!apr_mvm || !apr_cvs || !apr_cvp) { pr_err("%s: apr_mvm or apr_cvs or apr_cvp is NULL\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvs_handle = voice_get_cvs_handle(v); cvp_handle = voice_get_cvp_handle(v); pr_debug("%s: mvm_hdl=%d, cvs_hdl=%d\n", __func__, mvm_handle, cvs_handle); /* send cmd to create mvm session and wait for response */ if (!mvm_handle) { if (is_voice_session(v->session_id) || is_volte_session(v->session_id) || is_voice2_session(v->session_id)) { mvm_session_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_session_cmd.hdr.pkt_size = APR_PKT_SIZE( APR_HDR_SIZE, sizeof(mvm_session_cmd) - APR_HDR_SIZE); pr_debug("%s: send mvm create session pkt size = %d\n", __func__, mvm_session_cmd.hdr.pkt_size); mvm_session_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_session_cmd.hdr.dest_port = 0; mvm_session_cmd.hdr.token = 0; mvm_session_cmd.hdr.opcode = VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION; if (is_volte_session(v->session_id)) { strlcpy(mvm_session_cmd.mvm_session.name, "default volte voice", sizeof(mvm_session_cmd.mvm_session.name)); } else if (is_voice2_session(v->session_id)) { strlcpy(mvm_session_cmd.mvm_session.name, VOICE2_SESSION_VSID_STR, sizeof(mvm_session_cmd.mvm_session.name)); } else { strlcpy(mvm_session_cmd.mvm_session.name, "default modem voice", sizeof(mvm_session_cmd.mvm_session.name)); } v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_session_cmd); if (ret < 0) { pr_err("%s: Error sending MVM_CONTROL_SESSION\n", __func__); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } else { pr_debug("%s: creating MVM full ctrl\n", __func__); mvm_session_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_session_cmd) - APR_HDR_SIZE); mvm_session_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_session_cmd.hdr.dest_port = 0; mvm_session_cmd.hdr.token = 0; mvm_session_cmd.hdr.opcode = VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION; strlcpy(mvm_session_cmd.mvm_session.name, "default voip", sizeof(mvm_session_cmd.mvm_session.name)); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_session_cmd); if (ret < 0) { pr_err("Fail in sending MVM_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } /* Get the created MVM handle. */ mvm_handle = voice_get_mvm_handle(v); } /* send cmd to create cvs session */ if (!cvs_handle) { if (is_voice_session(v->session_id) || is_volte_session(v->session_id) || is_voice2_session(v->session_id)) { pr_debug("%s: creating CVS passive session\n", __func__); cvs_session_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_session_cmd) - APR_HDR_SIZE); cvs_session_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_session_cmd.hdr.dest_port = 0; cvs_session_cmd.hdr.token = 0; cvs_session_cmd.hdr.opcode = VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION; if (is_volte_session(v->session_id)) { strlcpy(cvs_session_cmd.cvs_session.name, "default volte voice", sizeof(cvs_session_cmd.cvs_session.name)); } else if (is_voice2_session(v->session_id)) { strlcpy(cvs_session_cmd.cvs_session.name, VOICE2_SESSION_VSID_STR, sizeof(cvs_session_cmd.cvs_session.name)); } else { strlcpy(cvs_session_cmd.cvs_session.name, "default modem voice", sizeof(cvs_session_cmd.cvs_session.name)); } v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_session_cmd); if (ret < 0) { pr_err("Fail in sending STREAM_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Get the created CVS handle. */ cvs_handle = voice_get_cvs_handle(v); } else { pr_debug("%s: creating CVS full session\n", __func__); cvs_full_ctl_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_full_ctl_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_full_ctl_cmd) - APR_HDR_SIZE); cvs_full_ctl_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_full_ctl_cmd.hdr.dest_port = 0; cvs_full_ctl_cmd.hdr.token = 0; cvs_full_ctl_cmd.hdr.opcode = VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION; cvs_full_ctl_cmd.cvs_session.direction = 2; cvs_full_ctl_cmd.cvs_session.enc_media_type = common.mvs_info.media_type; cvs_full_ctl_cmd.cvs_session.dec_media_type = common.mvs_info.media_type; cvs_full_ctl_cmd.cvs_session.network_id = common.mvs_info.network_type; strlcpy(cvs_full_ctl_cmd.cvs_session.name, "default q6 voice", sizeof(cvs_full_ctl_cmd.cvs_session.name)); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_full_ctl_cmd); if (ret < 0) { pr_err("%s: Err %d sending CREATE_FULL_CTRL\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Get the created CVS handle. */ cvs_handle = voice_get_cvs_handle(v); /* Attach MVM to CVS. */ pr_debug("%s: Attach MVM to stream\n", __func__); attach_stream_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); attach_stream_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(attach_stream_cmd) - APR_HDR_SIZE); attach_stream_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); attach_stream_cmd.hdr.dest_port = mvm_handle; attach_stream_cmd.hdr.token = 0; attach_stream_cmd.hdr.opcode = VSS_IMVM_CMD_ATTACH_STREAM; attach_stream_cmd.attach_stream.handle = cvs_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &attach_stream_cmd); if (ret < 0) { pr_err("%s: Error %d sending ATTACH_STREAM\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } } return 0; fail: return -EINVAL; } static int voice_destroy_mvm_cvs_session(struct voice_data *v) { int ret = 0; struct mvm_detach_stream_cmd detach_stream; struct apr_hdr mvm_destroy; struct apr_hdr cvs_destroy; void *apr_mvm, *apr_cvs; u16 mvm_handle, cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvs = common.apr_q6_cvs; if (!apr_mvm || !apr_cvs) { pr_err("%s: apr_mvm or apr_cvs is NULL\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvs_handle = voice_get_cvs_handle(v); /* MVM, CVS sessions are destroyed only for Full control sessions. */ if (is_voip_session(v->session_id)) { pr_debug("%s: MVM detach stream, VOC_STATE: %d\n", __func__, v->voc_state); /* Detach voice stream. */ detach_stream.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); detach_stream.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(detach_stream) - APR_HDR_SIZE); detach_stream.hdr.src_port = voice_get_idx_for_session(v->session_id); detach_stream.hdr.dest_port = mvm_handle; detach_stream.hdr.token = 0; detach_stream.hdr.opcode = VSS_IMVM_CMD_DETACH_STREAM; detach_stream.detach_stream.handle = cvs_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &detach_stream); if (ret < 0) { pr_err("%s: Error %d sending DETACH_STREAM\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } /* Unmap memory */ if (v->shmem_info.mem_handle != 0) { ret = voice_send_mvm_unmap_memory_physical_cmd(v, v->shmem_info.mem_handle); if (ret < 0) { pr_err("%s Memory_unmap for voip failed %d\n", __func__, ret); goto fail; } v->shmem_info.mem_handle = 0; } } if (is_voip_session(v->session_id) || v->voc_state == VOC_ERROR) { /* Destroy CVS. */ pr_debug("%s: CVS destroy session\n", __func__); cvs_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_destroy) - APR_HDR_SIZE); cvs_destroy.src_port = voice_get_idx_for_session(v->session_id); cvs_destroy.dest_port = cvs_handle; cvs_destroy.token = 0; cvs_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_destroy); if (ret < 0) { pr_err("%s: Error %d sending CVS DESTROY\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } cvs_handle = 0; voice_set_cvs_handle(v, cvs_handle); /* Unmap physical memory for calibration */ pr_debug("%s: cal_mem_handle %d\n", __func__, common.cal_mem_handle); if (!is_other_session_active(v->session_id) && (common.cal_mem_handle != 0)) { ret = voice_send_mvm_unmap_memory_physical_cmd(v, common.cal_mem_handle); if (ret < 0) { pr_err("%s Fail at cal mem unmap %d\n", __func__, ret); goto fail; } common.cal_mem_handle = 0; } /* Destroy MVM. */ pr_debug("MVM destroy session\n"); mvm_destroy.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_destroy.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_destroy) - APR_HDR_SIZE); mvm_destroy.src_port = voice_get_idx_for_session(v->session_id); mvm_destroy.dest_port = mvm_handle; mvm_destroy.token = 0; mvm_destroy.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_destroy); if (ret < 0) { pr_err("%s: Error %d sending MVM DESTROY\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait event timeout\n", __func__); goto fail; } mvm_handle = 0; voice_set_mvm_handle(v, mvm_handle); } return 0; fail: return -EINVAL; } static int voice_send_tty_mode_cmd(struct voice_data *v) { int ret = 0; struct mvm_set_tty_mode_cmd mvm_tty_mode_cmd; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); if (v->tty_mode) { /* send tty mode cmd to mvm */ mvm_tty_mode_cmd.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_tty_mode_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_tty_mode_cmd) - APR_HDR_SIZE); pr_debug("%s: pkt size = %d\n", __func__, mvm_tty_mode_cmd.hdr.pkt_size); mvm_tty_mode_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_tty_mode_cmd.hdr.dest_port = mvm_handle; mvm_tty_mode_cmd.hdr.token = 0; mvm_tty_mode_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_TTY_MODE; mvm_tty_mode_cmd.tty_mode.mode = v->tty_mode; pr_debug("tty mode =%d\n", mvm_tty_mode_cmd.tty_mode.mode); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_tty_mode_cmd); if (ret < 0) { pr_err("%s: Error %d sending SET_TTY_MODE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } } return 0; fail: return -EINVAL; } static int voice_send_set_pp_enable_cmd(struct voice_data *v, uint32_t module_id, int enable) { struct cvs_set_pp_enable_cmd cvs_set_pp_cmd; int ret = 0; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); cvs_set_pp_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_pp_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_pp_cmd) - APR_HDR_SIZE); cvs_set_pp_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_pp_cmd.hdr.dest_port = cvs_handle; cvs_set_pp_cmd.hdr.token = 0; cvs_set_pp_cmd.hdr.opcode = VSS_ICOMMON_CMD_SET_UI_PROPERTY; cvs_set_pp_cmd.vss_set_pp.module_id = module_id; cvs_set_pp_cmd.vss_set_pp.param_id = VOICE_PARAM_MOD_ENABLE; cvs_set_pp_cmd.vss_set_pp.param_size = MOD_ENABLE_PARAM_LEN; cvs_set_pp_cmd.vss_set_pp.reserved = 0; cvs_set_pp_cmd.vss_set_pp.enable = enable; cvs_set_pp_cmd.vss_set_pp.reserved_field = 0; pr_debug("voice_send_set_pp_enable_cmd, module_id=%d, enable=%d\n", module_id, enable); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_pp_cmd); if (ret < 0) { pr_err("Fail: sending cvs set pp enable,\n"); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_set_dtx(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct cvs_set_enc_dtx_mode_cmd cvs_set_dtx; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* Set DTX */ cvs_set_dtx.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_dtx.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_dtx) - APR_HDR_SIZE); cvs_set_dtx.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_dtx.hdr.dest_port = cvs_handle; cvs_set_dtx.hdr.token = 0; cvs_set_dtx.hdr.opcode = VSS_ISTREAM_CMD_SET_ENC_DTX_MODE; cvs_set_dtx.dtx_mode.enable = common.mvs_info.dtx_mode; pr_debug("%s: Setting DTX %d\n", __func__, common.mvs_info.dtx_mode); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_dtx); if (ret < 0) { pr_err("%s: Error %d sending SET_DTX\n", __func__, ret); return -EINVAL; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return 0; } static int voice_send_mvm_media_type_cmd(struct voice_data *v) { struct vss_imvm_cmd_set_cal_media_type_t mvm_set_cal_media_type; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_set_cal_media_type.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_cal_media_type.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_cal_media_type) - APR_HDR_SIZE); mvm_set_cal_media_type.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_set_cal_media_type.hdr.dest_port = mvm_handle; mvm_set_cal_media_type.hdr.token = 0; mvm_set_cal_media_type.hdr.opcode = VSS_IMVM_CMD_SET_CAL_MEDIA_TYPE; mvm_set_cal_media_type.media_id = common.mvs_info.media_type; pr_debug("%s: setting media_id as %x\n", __func__ , mvm_set_cal_media_type.media_id); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_cal_media_type); if (ret < 0) { pr_err("%s: Error %d sending media type\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout %d\n", __func__, ret); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_dtmf_rx_detection_cmd(struct voice_data *v, uint32_t enable) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct cvs_set_rx_dtmf_detection_cmd cvs_dtmf_rx_detection; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); /* Set SET_DTMF_RX_DETECTION */ cvs_dtmf_rx_detection.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_dtmf_rx_detection.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_dtmf_rx_detection) - APR_HDR_SIZE); cvs_dtmf_rx_detection.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_dtmf_rx_detection.hdr.dest_port = cvs_handle; cvs_dtmf_rx_detection.hdr.token = 0; cvs_dtmf_rx_detection.hdr.opcode = VSS_ISTREAM_CMD_SET_RX_DTMF_DETECTION; cvs_dtmf_rx_detection.cvs_dtmf_det.enable = enable; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_dtmf_rx_detection); if (ret < 0) { pr_err("%s: Error %d sending SET_DTMF_RX_DETECTION\n", __func__, ret); return -EINVAL; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return ret; } void voc_disable_dtmf_det_on_active_sessions(void) { struct voice_data *v = NULL; int i; for (i = 0; i < MAX_VOC_SESSIONS; i++) { v = &common.voice[i]; if ((v->dtmf_rx_detect_en) && ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY))) { pr_debug("disable dtmf det on ses_id=%d\n", v->session_id); voice_send_dtmf_rx_detection_cmd(v, 0); } } } int voc_enable_dtmf_rx_detection(uint32_t session_id, uint32_t enable) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dtmf_rx_detect_en = enable; if ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY)) ret = voice_send_dtmf_rx_detection_cmd(v, v->dtmf_rx_detect_en); mutex_unlock(&v->lock); return ret; } static int voice_config_cvs_vocoder(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; /* Set media type. */ struct cvs_set_media_type_cmd cvs_set_media_cmd; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); cvs_set_media_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_media_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_media_cmd) - APR_HDR_SIZE); cvs_set_media_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_media_cmd.hdr.dest_port = cvs_handle; cvs_set_media_cmd.hdr.token = 0; cvs_set_media_cmd.hdr.opcode = VSS_ISTREAM_CMD_SET_MEDIA_TYPE; cvs_set_media_cmd.media_type.tx_media_id = common.mvs_info.media_type; cvs_set_media_cmd.media_type.rx_media_id = common.mvs_info.media_type; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_media_cmd); if (ret < 0) { pr_err("%s: Error %d sending SET_MEDIA_TYPE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Set encoder properties. */ switch (common.mvs_info.media_type) { case VSS_MEDIA_ID_EVRC_MODEM: case VSS_MEDIA_ID_4GV_NB_MODEM: case VSS_MEDIA_ID_4GV_WB_MODEM: { struct cvs_set_cdma_enc_minmax_rate_cmd cvs_set_cdma_rate; pr_debug("Setting EVRC min-max rate\n"); cvs_set_cdma_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_cdma_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_cdma_rate) - APR_HDR_SIZE); cvs_set_cdma_rate.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_cdma_rate.hdr.dest_port = cvs_handle; cvs_set_cdma_rate.hdr.token = 0; cvs_set_cdma_rate.hdr.opcode = VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE; cvs_set_cdma_rate.cdma_rate.min_rate = common.mvs_info.rate; cvs_set_cdma_rate.cdma_rate.max_rate = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_cdma_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_EVRC_MINMAX_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } break; } case VSS_MEDIA_ID_AMR_NB_MODEM: { struct cvs_set_amr_enc_rate_cmd cvs_set_amr_rate; pr_debug("Setting AMR rate\n"); cvs_set_amr_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_amr_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_amr_rate) - APR_HDR_SIZE); cvs_set_amr_rate.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_amr_rate.hdr.dest_port = cvs_handle; cvs_set_amr_rate.hdr.token = 0; cvs_set_amr_rate.hdr.opcode = VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE; cvs_set_amr_rate.amr_rate.mode = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amr_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_AMR_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } ret = voice_set_dtx(v); if (ret < 0) goto fail; break; } case VSS_MEDIA_ID_AMR_WB_MODEM: { struct cvs_set_amrwb_enc_rate_cmd cvs_set_amrwb_rate; pr_debug("Setting AMR WB rate\n"); cvs_set_amrwb_rate.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_set_amrwb_rate.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_set_amrwb_rate) - APR_HDR_SIZE); cvs_set_amrwb_rate.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_set_amrwb_rate.hdr.dest_port = cvs_handle; cvs_set_amrwb_rate.hdr.token = 0; cvs_set_amrwb_rate.hdr.opcode = VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE; cvs_set_amrwb_rate.amrwb_rate.mode = common.mvs_info.rate; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_set_amrwb_rate); if (ret < 0) { pr_err("%s: Error %d sending SET_AMRWB_RATE\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } ret = voice_set_dtx(v); if (ret < 0) goto fail; break; } case VSS_MEDIA_ID_G729: case VSS_MEDIA_ID_G711_ALAW: case VSS_MEDIA_ID_G711_MULAW: { ret = voice_set_dtx(v); break; } default: /* Do nothing. */ break; } return 0; fail: return -EINVAL; } static int voice_send_start_voice_cmd(struct voice_data *v) { struct apr_hdr mvm_start_voice_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_start_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_start_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_start_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_start_voice_cmd pkt size = %d\n", mvm_start_voice_cmd.pkt_size); mvm_start_voice_cmd.src_port = voice_get_idx_for_session(v->session_id); mvm_start_voice_cmd.dest_port = mvm_handle; mvm_start_voice_cmd.token = 0; mvm_start_voice_cmd.opcode = VSS_IMVM_CMD_START_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_start_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_START_VOICE\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_disable_vocproc_cmd(struct voice_data *v) { struct apr_hdr cvp_disable_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr regist failed\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* disable vocproc and wait for respose */ cvp_disable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_disable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_disable_cmd) - APR_HDR_SIZE); pr_debug("cvp_disable_cmd pkt size = %d, cvp_handle=%d\n", cvp_disable_cmd.pkt_size, cvp_handle); cvp_disable_cmd.src_port = voice_get_idx_for_session(v->session_id); cvp_disable_cmd.dest_port = cvp_handle; cvp_disable_cmd.token = 0; cvp_disable_cmd.opcode = VSS_IVOCPROC_CMD_DISABLE; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_disable_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IVOCPROC_CMD_DISABLE\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static void voc_get_tx_rx_topology(struct voice_data *v, uint32_t *tx_topology_id, uint32_t *rx_topology_id) { uint32_t tx_id = 0; uint32_t rx_id = 0; if (v->lch_mode == VOICE_LCH_START) { pr_debug("%s: Setting TX and RX topology to NONE for LCH\n", __func__); tx_id = VSS_IVOCPROC_TOPOLOGY_ID_NONE; rx_id = VSS_IVOCPROC_TOPOLOGY_ID_NONE; } else { /* Use default topology if invalid value in ACDB */ tx_id = get_voice_tx_topology(); if (tx_id == 0) tx_id = VSS_IVOCPROC_TOPOLOGY_ID_TX_SM_ECNS; rx_id = get_voice_rx_topology(); if (rx_id == 0) rx_id = VSS_IVOCPROC_TOPOLOGY_ID_RX_DEFAULT; } *tx_topology_id = tx_id; *rx_topology_id = rx_id; } static int voice_send_set_device_cmd(struct voice_data *v) { struct cvp_set_device_cmd cvp_setdev_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* set device and wait for response */ cvp_setdev_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_setdev_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_setdev_cmd) - APR_HDR_SIZE); pr_debug(" send create cvp setdev, pkt size = %d\n", cvp_setdev_cmd.hdr.pkt_size); cvp_setdev_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_setdev_cmd.hdr.dest_port = cvp_handle; cvp_setdev_cmd.hdr.token = 0; cvp_setdev_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_DEVICE_V2; voc_get_tx_rx_topology(v, &cvp_setdev_cmd.cvp_set_device_v2.tx_topology_id, &cvp_setdev_cmd.cvp_set_device_v2.rx_topology_id); cvp_setdev_cmd.cvp_set_device_v2.tx_port_id = v->dev_tx.port_id; cvp_setdev_cmd.cvp_set_device_v2.rx_port_id = v->dev_rx.port_id; cvp_setdev_cmd.cvp_set_device_v2.vocproc_mode = VSS_IVOCPROC_VOCPROC_MODE_EC_INT_MIXING; cvp_setdev_cmd.cvp_set_device_v2.ec_ref_port_id = VSS_IVOCPROC_PORT_ID_NONE; pr_debug("topology=%d , tx_port_id=%d, rx_port_id=%d\n", cvp_setdev_cmd.cvp_set_device_v2.tx_topology_id, cvp_setdev_cmd.cvp_set_device_v2.tx_port_id, cvp_setdev_cmd.cvp_set_device_v2.rx_port_id); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_setdev_cmd); if (ret < 0) { pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n"); goto fail; } pr_debug("wait for cvp create session event\n"); ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_stop_voice_cmd(struct voice_data *v) { struct apr_hdr mvm_stop_voice_cmd; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_stop_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_stop_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_stop_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_stop_voice_cmd pkt size = %d\n", mvm_stop_voice_cmd.pkt_size); mvm_stop_voice_cmd.src_port = voice_get_idx_for_session(v->session_id); mvm_stop_voice_cmd.dest_port = mvm_handle; mvm_stop_voice_cmd.token = 0; mvm_stop_voice_cmd.opcode = VSS_IMVM_CMD_STOP_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_stop_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_STOP_VOICE\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_register_cal_cmd(struct voice_data *v) { struct cvs_register_cal_data_cmd cvs_reg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvs_reg_cal_cmd, 0, sizeof(cvs_reg_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvs) { pr_err("%s: apr_cvs is NULL\n", __func__); goto fail; } if (!common.cal_mem_handle) { pr_err("%s: Cal mem handle is NULL\n", __func__); goto fail; } get_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) { pr_err("%s: CVS cal size is 0\n", __func__); goto fail; } cvs_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_reg_cal_cmd) - APR_HDR_SIZE); cvs_reg_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_reg_cal_cmd.hdr.dest_port = voice_get_cvs_handle(v); cvs_reg_cal_cmd.hdr.token = 0; cvs_reg_cal_cmd.hdr.opcode = VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA_V2; cvs_reg_cal_cmd.cvs_cal_data.cal_mem_handle = common.cal_mem_handle; cvs_reg_cal_cmd.cvs_cal_data.cal_mem_address = cal_block.cal_paddr; cvs_reg_cal_cmd.cvs_cal_data.cal_mem_size = cal_block.cal_size; /* Get the column info corresponding to CVS cal from ACDB. */ get_voice_col_data(VOCSTRM_CAL, &cal_block); if (cal_block.cal_size == 0 || cal_block.cal_size > sizeof(cvs_reg_cal_cmd.cvs_cal_data.column_info)) { pr_err("%s: Invalid VOCSTRM_CAL size %d\n", __func__, cal_block.cal_size); goto fail; } memcpy(&cvs_reg_cal_cmd.cvs_cal_data.column_info[0], (void *) cal_block.cal_kvaddr, cal_block.cal_size); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvs, (uint32_t *) &cvs_reg_cal_cmd); if (ret < 0) { pr_err("%s: Error %d registering CVS cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvs_deregister_cal_cmd(struct voice_data *v) { struct cvs_deregister_cal_data_cmd cvs_dereg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvs_dereg_cal_cmd, 0, sizeof(cvs_dereg_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvs) { pr_err("%s: apr_cvs is NULL\n", __func__); goto fail; } get_vocstrm_cal(&cal_block); if (cal_block.cal_size == 0) return 0; cvs_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_dereg_cal_cmd) - APR_HDR_SIZE); cvs_dereg_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_dereg_cal_cmd.hdr.dest_port = voice_get_cvs_handle(v); cvs_dereg_cal_cmd.hdr.token = 0; cvs_dereg_cal_cmd.hdr.opcode = VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvs, (uint32_t *) &cvs_dereg_cal_cmd); if (ret < 0) { pr_err("%s: Error %d de-registering CVS cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_register_dev_cfg_cmd(struct voice_data *v) { struct cvp_register_dev_cfg_cmd cvp_reg_dev_cfg_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_reg_dev_cfg_cmd, 0, sizeof(cvp_reg_dev_cfg_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL\n", __func__); goto fail; } if (!common.cal_mem_handle) { pr_err("%s: Cal mem handle is NULL\n", __func__); goto fail; } get_vocproc_dev_cfg_cal(&cal_block); if (cal_block.cal_size == 0) { pr_err("%s: CVP cal size is 0\n", __func__); goto fail; } cvp_reg_dev_cfg_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_reg_dev_cfg_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_reg_dev_cfg_cmd) - APR_HDR_SIZE); cvp_reg_dev_cfg_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_reg_dev_cfg_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_reg_dev_cfg_cmd.hdr.token = 0; cvp_reg_dev_cfg_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_DEVICE_CONFIG; cvp_reg_dev_cfg_cmd.cvp_dev_cfg_data.mem_handle = common.cal_mem_handle; cvp_reg_dev_cfg_cmd.cvp_dev_cfg_data.mem_address = cal_block.cal_paddr; cvp_reg_dev_cfg_cmd.cvp_dev_cfg_data.mem_size = cal_block.cal_size; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_reg_dev_cfg_cmd); if (ret < 0) { pr_err("%s: Error %d registering CVP dev cfg cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_deregister_dev_cfg_cmd(struct voice_data *v) { struct cvp_deregister_dev_cfg_cmd cvp_dereg_dev_cfg_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_dereg_dev_cfg_cmd, 0, sizeof(cvp_dereg_dev_cfg_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); goto fail; } get_vocproc_dev_cfg_cal(&cal_block); if (cal_block.cal_size == 0) return 0; cvp_dereg_dev_cfg_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_dereg_dev_cfg_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_dereg_dev_cfg_cmd) - APR_HDR_SIZE); cvp_dereg_dev_cfg_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_dereg_dev_cfg_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_dereg_dev_cfg_cmd.hdr.token = 0; cvp_dereg_dev_cfg_cmd.hdr.opcode = VSS_IVOCPROC_CMD_DEREGISTER_DEVICE_CONFIG; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_dereg_dev_cfg_cmd); if (ret < 0) { pr_err("%s: Error %d de-registering CVP dev cfg cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_register_cal_cmd(struct voice_data *v) { struct cvp_register_cal_data_cmd cvp_reg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_reg_cal_cmd, 0, sizeof(cvp_reg_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL\n", __func__); goto fail; } if (!common.cal_mem_handle) { pr_err("%s: Cal mem handle is NULL\n", __func__); goto fail; } get_vocproc_cal(&cal_block); if (cal_block.cal_size == 0) { pr_err("%s: CVP cal size is 0\n", __func__); goto fail; } cvp_reg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_reg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_reg_cal_cmd) - APR_HDR_SIZE); cvp_reg_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_reg_cal_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_reg_cal_cmd.hdr.token = 0; cvp_reg_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA_V2; cvp_reg_cal_cmd.cvp_cal_data.cal_mem_handle = common.cal_mem_handle; cvp_reg_cal_cmd.cvp_cal_data.cal_mem_address = cal_block.cal_paddr; cvp_reg_cal_cmd.cvp_cal_data.cal_mem_size = cal_block.cal_size; /* Get the column info corresponding to CVP cal from ACDB. */ get_voice_col_data(VOCPROC_CAL, &cal_block); if (cal_block.cal_size == 0 || cal_block.cal_size > sizeof(cvp_reg_cal_cmd.cvp_cal_data.column_info)) { pr_err("%s: Invalid VOCPROC_CAL size %d\n", __func__, cal_block.cal_size); goto fail; } memcpy(&cvp_reg_cal_cmd.cvp_cal_data.column_info[0], (void *) cal_block.cal_kvaddr, cal_block.cal_size); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_reg_cal_cmd); if (ret < 0) { pr_err("%s: Error %d registering CVP cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_deregister_cal_cmd(struct voice_data *v) { struct cvp_deregister_cal_data_cmd cvp_dereg_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_dereg_cal_cmd, 0, sizeof(cvp_dereg_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); goto fail; } get_vocproc_cal(&cal_block); if (cal_block.cal_size == 0) return 0; cvp_dereg_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_dereg_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_dereg_cal_cmd) - APR_HDR_SIZE); cvp_dereg_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_dereg_cal_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_dereg_cal_cmd.hdr.token = 0; cvp_dereg_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_dereg_cal_cmd); if (ret < 0) { pr_err("%s: Error %d de-registering CVP cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_register_vol_cal_cmd(struct voice_data *v) { struct cvp_register_vol_cal_data_cmd cvp_reg_vol_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_reg_vol_cal_cmd, 0, sizeof(cvp_reg_vol_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); goto fail; } if (!common.cal_mem_handle) { pr_err("%s: Cal mem handle is NULL\n", __func__); goto fail; } get_vocvol_cal(&cal_block); if (cal_block.cal_size == 0) { pr_err("%s: CVP vol cal size is 0\n", __func__); goto fail; } cvp_reg_vol_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_reg_vol_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_reg_vol_cal_cmd) - APR_HDR_SIZE); cvp_reg_vol_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_reg_vol_cal_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_reg_vol_cal_cmd.hdr.token = 0; cvp_reg_vol_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_REGISTER_VOL_CALIBRATION_DATA; cvp_reg_vol_cal_cmd.cvp_vol_cal_data.cal_mem_handle = common.cal_mem_handle; cvp_reg_vol_cal_cmd.cvp_vol_cal_data.cal_mem_address = cal_block.cal_paddr; cvp_reg_vol_cal_cmd.cvp_vol_cal_data.cal_mem_size = cal_block.cal_size; /* Get the column info corresponding to CVP volume cal from ACDB. */ get_voice_col_data(VOCVOL_CAL, &cal_block); if (cal_block.cal_size == 0 || cal_block.cal_size > sizeof(cvp_reg_vol_cal_cmd.cvp_vol_cal_data.column_info)) { pr_err("%s: Invalid VOCVOL_CAL size %d\n", __func__, cal_block.cal_size); goto fail; } memcpy(&cvp_reg_vol_cal_cmd.cvp_vol_cal_data.column_info[0], (void *) cal_block.cal_kvaddr, cal_block.cal_size); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_reg_vol_cal_cmd); if (ret < 0) { pr_err("%s: Error %d registering CVP vol cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_cvp_deregister_vol_cal_cmd(struct voice_data *v) { struct cvp_deregister_vol_cal_data_cmd cvp_dereg_vol_cal_cmd; struct acdb_cal_block cal_block; int ret = 0; memset(&cvp_dereg_vol_cal_cmd, 0, sizeof(cvp_dereg_vol_cal_cmd)); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL\n", __func__); goto fail; } get_vocvol_cal(&cal_block); if (cal_block.cal_size == 0) return 0; cvp_dereg_vol_cal_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_dereg_vol_cal_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_dereg_vol_cal_cmd) - APR_HDR_SIZE); cvp_dereg_vol_cal_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_dereg_vol_cal_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_dereg_vol_cal_cmd.hdr.token = 0; cvp_dereg_vol_cal_cmd.hdr.opcode = VSS_IVOCPROC_CMD_DEREGISTER_VOL_CALIBRATION_DATA; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_dereg_vol_cal_cmd); if (ret < 0) { pr_err("%s: Error %d de-registering CVP vol cal\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } fail: return ret; } static int voice_map_memory_physical_cmd(struct voice_data *v, struct mem_map_table *table_info, dma_addr_t phys, uint32_t size, uint32_t token) { struct vss_imemory_cmd_map_physical_t mvm_map_phys_cmd; uint32_t *memtable; int ret = 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); goto fail; } if (!table_info->data) { pr_err("%s: memory table is NULL.\n", __func__); goto fail; } memtable = (uint32_t *) table_info->data; /* * Store next table descriptor's address(64 bit) as NULL as there * is only one memory block */ memtable[0] = (uint32_t)NULL; memtable[1] = (uint32_t)NULL; /* Store next table descriptor's size */ memtable[2] = 0; /* Store shared mem add */ memtable[3] = phys; memtable[4] = 0; /* Store shared memory size */ memtable[5] = size; mvm_map_phys_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_map_phys_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_map_phys_cmd) - APR_HDR_SIZE); mvm_map_phys_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_map_phys_cmd.hdr.dest_port = voice_get_mvm_handle(v); mvm_map_phys_cmd.hdr.token = token; mvm_map_phys_cmd.hdr.opcode = VSS_IMEMORY_CMD_MAP_PHYSICAL; mvm_map_phys_cmd.table_descriptor.mem_address = table_info->phys; mvm_map_phys_cmd.table_descriptor.mem_size = sizeof(struct vss_imemory_block_t) + sizeof(struct vss_imemory_table_descriptor_t); mvm_map_phys_cmd.is_cached = true; mvm_map_phys_cmd.cache_line_size = 128; mvm_map_phys_cmd.access_mask = 3; mvm_map_phys_cmd.page_align = 4096; mvm_map_phys_cmd.min_data_width = 8; mvm_map_phys_cmd.max_data_width = 64; pr_debug("%s: next table desc: add: %lld, size: %d\n", __func__, *((uint64_t *) memtable), *(((uint32_t *) memtable) + 2)); pr_debug("%s: phy add of of mem being mapped 0x%x, size: %d\n", __func__, *(((uint32_t *) memtable) + 3), *(((uint32_t *) memtable) + 5)); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_mvm, (uint32_t *) &mvm_map_phys_cmd); if (ret < 0) { pr_err("%s: Error %d sending mvm map phy cmd\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_mem_map_cal_block(struct voice_data *v) { int ret = 0; struct acdb_cal_block cal_block; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (common.cal_mem_handle != 0) { pr_debug("%s: Cal block already mem mapped\n", __func__); return ret; } /* Get the physical address of calibration memory block from ACDB. */ get_voice_cal_allocation(&cal_block); if (!cal_block.cal_paddr) { pr_err("%s: Cal block not allocated\n", __func__); return -EINVAL; } ret = voice_map_memory_physical_cmd(v, &common.cal_mem_map_table, cal_block.cal_paddr, cal_block.cal_size, VOC_CAL_MEM_MAP_TOKEN); return ret; } static int voice_pause_voice_call(struct voice_data *v) { struct apr_hdr mvm_pause_voice_cmd; void *apr_mvm; int ret = 0; pr_debug("%s\n", __func__); if (v == NULL) { pr_err("%s: Voice data is NULL\n", __func__); ret = -EINVAL; goto done; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); ret = -EINVAL; goto done; } mvm_pause_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_pause_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_pause_voice_cmd) - APR_HDR_SIZE); mvm_pause_voice_cmd.src_port = voice_get_idx_for_session(v->session_id); mvm_pause_voice_cmd.dest_port = voice_get_mvm_handle(v); mvm_pause_voice_cmd.token = 0; mvm_pause_voice_cmd.opcode = VSS_IMVM_CMD_PAUSE_VOICE; v->mvm_state = CMD_STATUS_FAIL; pr_debug("%s: send mvm_pause_voice_cmd pkt size = %d\n", __func__, mvm_pause_voice_cmd.pkt_size); ret = apr_send_pkt(apr_mvm, (uint32_t *)&mvm_pause_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_PAUSE_VOICE\n"); ret = -EINVAL; goto done; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); ret = -EINVAL; goto done; } done: return ret; } int voc_unmap_cal_blocks(void) { int result = 0; int result2 = 0; int i; struct voice_data *v = NULL; pr_debug("%s\n", __func__); mutex_lock(&common.common_lock); if (common.cal_mem_handle == 0) goto done; for (i = 0; i < MAX_VOC_SESSIONS; i++) { v = &common.voice[i]; mutex_lock(&v->lock); if (is_voc_state_active(v->voc_state)) { result2 = voice_pause_voice_call(v); if (result2 < 0) { pr_err("%s: voice_pause_voice_call failed for session 0x%x, err %d!\n", __func__, v->session_id, result2); result = result2; } voice_send_cvp_deregister_vol_cal_cmd(v); voice_send_cvp_deregister_cal_cmd(v); voice_send_cvp_deregister_dev_cfg_cmd(v); voice_send_cvs_deregister_cal_cmd(v); result2 = voice_send_start_voice_cmd(v); if (result2) { pr_err("%s: voice_send_start_voice_cmd failed for session 0x%x, err %d!\n", __func__, v->session_id, result2); result = result2; } } if ((common.cal_mem_handle != 0) && (!is_other_session_active(v->session_id))) { result2 = voice_send_mvm_unmap_memory_physical_cmd( v, common.cal_mem_handle); if (result2) { pr_err("%s: voice_send_mvm_unmap_memory_physical_cmd failed for session 0x%x, err %d!\n", __func__, v->session_id, result2); result = result2; } else { common.cal_mem_handle = 0; } } mutex_unlock(&v->lock); } done: mutex_unlock(&common.common_lock); return result; } static int voice_setup_vocproc(struct voice_data *v) { struct cvp_create_full_ctl_session_cmd cvp_session_cmd; int ret = 0; void *apr_cvp; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } /* create cvp session and wait for response */ cvp_session_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_session_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_session_cmd) - APR_HDR_SIZE); pr_debug(" send create cvp session, pkt size = %d\n", cvp_session_cmd.hdr.pkt_size); cvp_session_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_session_cmd.hdr.dest_port = 0; cvp_session_cmd.hdr.token = 0; cvp_session_cmd.hdr.opcode = VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION_V2; voc_get_tx_rx_topology(v, &cvp_session_cmd.cvp_session.tx_topology_id, &cvp_session_cmd.cvp_session.rx_topology_id); cvp_session_cmd.cvp_session.direction = 2; /*tx and rx*/ cvp_session_cmd.cvp_session.tx_port_id = v->dev_tx.port_id; cvp_session_cmd.cvp_session.rx_port_id = v->dev_rx.port_id; cvp_session_cmd.cvp_session.profile_id = VSS_ICOMMON_CAL_NETWORK_ID_NONE; cvp_session_cmd.cvp_session.vocproc_mode = VSS_IVOCPROC_VOCPROC_MODE_EC_INT_MIXING; cvp_session_cmd.cvp_session.ec_ref_port_id = VSS_IVOCPROC_PORT_ID_NONE; pr_debug("tx_topology: %d tx_port_id=%d, rx_port_id=%d, mode: 0x%x\n", cvp_session_cmd.cvp_session.tx_topology_id, cvp_session_cmd.cvp_session.tx_port_id, cvp_session_cmd.cvp_session.rx_port_id, cvp_session_cmd.cvp_session.vocproc_mode); pr_debug("rx_topology: %d, profile_id: 0x%x, pkt_size: %d\n", cvp_session_cmd.cvp_session.rx_topology_id, cvp_session_cmd.cvp_session.profile_id, cvp_session_cmd.hdr.pkt_size); v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_session_cmd); if (ret < 0) { pr_err("Fail in sending VOCPROC_FULL_CONTROL_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } voice_send_cvs_register_cal_cmd(v); voice_send_cvp_register_dev_cfg_cmd(v); voice_send_cvp_register_cal_cmd(v); voice_send_cvp_register_vol_cal_cmd(v); /* enable vocproc */ ret = voice_send_enable_vocproc_cmd(v); if (ret < 0) goto fail; /* attach vocproc */ ret = voice_send_attach_vocproc_cmd(v); if (ret < 0) goto fail; /* send tty mode if tty device is used */ voice_send_tty_mode_cmd(v); if (is_voip_session(v->session_id)) { ret = voice_send_mvm_cal_network_cmd(v); if (ret < 0) pr_err("%s: voice_send_mvm_cal_network_cmd: %d\n", __func__, ret); ret = voice_send_mvm_media_type_cmd(v); if (ret < 0) pr_err("%s: voice_send_mvm_media_type_cmd: %d\n", __func__, ret); voice_send_netid_timing_cmd(v); } /* enable slowtalk if st_enable is set */ if (v->st_enable) voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, v->st_enable); /* Start in-call music delivery if this feature is enabled */ if (v->music_info.play_enable) voice_cvs_start_playback(v); /* Start in-call recording if this feature is enabled */ if (v->rec_info.rec_enable) voice_cvs_start_record(v, v->rec_info.rec_mode); if (v->dtmf_rx_detect_en) voice_send_dtmf_rx_detection_cmd(v, v->dtmf_rx_detect_en); rtac_add_voice(voice_get_cvs_handle(v), voice_get_cvp_handle(v), v->dev_rx.port_id, v->dev_tx.port_id, v->session_id); return 0; fail: return -EINVAL; } static int voice_send_enable_vocproc_cmd(struct voice_data *v) { int ret = 0; struct apr_hdr cvp_enable_cmd; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* enable vocproc and wait for respose */ cvp_enable_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_enable_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_enable_cmd) - APR_HDR_SIZE); pr_debug("cvp_enable_cmd pkt size = %d, cvp_handle=%d\n", cvp_enable_cmd.pkt_size, cvp_handle); cvp_enable_cmd.src_port = voice_get_idx_for_session(v->session_id); cvp_enable_cmd.dest_port = cvp_handle; cvp_enable_cmd.token = 0; cvp_enable_cmd.opcode = VSS_IVOCPROC_CMD_ENABLE; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_enable_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IVOCPROC_CMD_ENABLE\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_mvm_cal_network_cmd(struct voice_data *v) { struct vss_imvm_cmd_set_cal_network_t mvm_set_cal_network; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mvm_set_cal_network.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_cal_network.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_cal_network) - APR_HDR_SIZE); mvm_set_cal_network.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_set_cal_network.hdr.dest_port = mvm_handle; mvm_set_cal_network.hdr.token = 0; mvm_set_cal_network.hdr.opcode = VSS_IMVM_CMD_SET_CAL_NETWORK; mvm_set_cal_network.network_id = VSS_ICOMMON_CAL_NETWORK_ID_NONE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_cal_network); if (ret < 0) { pr_err("%s: Error %d sending SET_NETWORK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout %d\n", __func__, ret); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_netid_timing_cmd(struct voice_data *v) { int ret = 0; void *apr_mvm; u16 mvm_handle; struct mvm_set_network_cmd mvm_set_network; struct mvm_set_voice_timing_cmd mvm_set_voice_timing; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); ret = voice_config_cvs_vocoder(v); if (ret < 0) { pr_err("%s: Error %d configuring CVS voc", __func__, ret); goto fail; } /* Set network ID. */ pr_debug("Setting network ID\n"); mvm_set_network.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_network.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_network) - APR_HDR_SIZE); mvm_set_network.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_set_network.hdr.dest_port = mvm_handle; mvm_set_network.hdr.token = 0; mvm_set_network.hdr.opcode = VSS_ICOMMON_CMD_SET_NETWORK; mvm_set_network.network.network_id = common.mvs_info.network_type; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_network); if (ret < 0) { pr_err("%s: Error %d sending SET_NETWORK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } /* Set voice timing. */ pr_debug("Setting voice timing\n"); mvm_set_voice_timing.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_set_voice_timing.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_set_voice_timing) - APR_HDR_SIZE); mvm_set_voice_timing.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_set_voice_timing.hdr.dest_port = mvm_handle; mvm_set_voice_timing.hdr.token = 0; mvm_set_voice_timing.hdr.opcode = VSS_ICOMMON_CMD_SET_VOICE_TIMING; mvm_set_voice_timing.timing.mode = 0; mvm_set_voice_timing.timing.enc_offset = 8000; mvm_set_voice_timing.timing.dec_req_offset = 3300; mvm_set_voice_timing.timing.dec_offset = 8300; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_set_voice_timing); if (ret < 0) { pr_err("%s: Error %d sending SET_TIMING\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_attach_vocproc_cmd(struct voice_data *v) { int ret = 0; struct mvm_attach_vocproc_cmd mvm_a_vocproc_cmd; void *apr_mvm; u16 mvm_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvp_handle = voice_get_cvp_handle(v); /* attach vocproc and wait for response */ mvm_a_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_a_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_a_vocproc_cmd) - APR_HDR_SIZE); pr_debug("send mvm_a_vocproc_cmd pkt size = %d\n", mvm_a_vocproc_cmd.hdr.pkt_size); mvm_a_vocproc_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_a_vocproc_cmd.hdr.dest_port = mvm_handle; mvm_a_vocproc_cmd.hdr.token = 0; mvm_a_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_ATTACH_VOCPROC; mvm_a_vocproc_cmd.mvm_attach_cvp_handle.handle = cvp_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_a_vocproc_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_ATTACH_VOCPROC\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_destroy_vocproc(struct voice_data *v) { struct mvm_detach_vocproc_cmd mvm_d_vocproc_cmd; struct apr_hdr cvp_destroy_session_cmd; int ret = 0; void *apr_mvm, *apr_cvp; u16 mvm_handle, cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; apr_cvp = common.apr_q6_cvp; if (!apr_mvm || !apr_cvp) { pr_err("%s: apr_mvm or apr_cvp is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); cvp_handle = voice_get_cvp_handle(v); /* stop playback or recording */ v->music_info.force = 1; voice_cvs_stop_playback(v); voice_cvs_stop_record(v); /* send stop voice cmd */ voice_send_stop_voice_cmd(v); /* send stop dtmf detecton cmd */ if (v->dtmf_rx_detect_en) voice_send_dtmf_rx_detection_cmd(v, 0); /* reset LCH mode */ v->lch_mode = 0; /* clear mute setting */ v->dev_rx.dev_mute = common.default_mute_val; v->dev_tx.dev_mute = common.default_mute_val; v->stream_rx.stream_mute = common.default_mute_val; v->stream_tx.stream_mute = common.default_mute_val; /* detach VOCPROC and wait for response from mvm */ mvm_d_vocproc_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_d_vocproc_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_d_vocproc_cmd) - APR_HDR_SIZE); pr_debug("mvm_d_vocproc_cmd pkt size = %d\n", mvm_d_vocproc_cmd.hdr.pkt_size); mvm_d_vocproc_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); mvm_d_vocproc_cmd.hdr.dest_port = mvm_handle; mvm_d_vocproc_cmd.hdr.token = 0; mvm_d_vocproc_cmd.hdr.opcode = VSS_IMVM_CMD_DETACH_VOCPROC; mvm_d_vocproc_cmd.mvm_detach_cvp_handle.handle = cvp_handle; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mvm_d_vocproc_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_DETACH_VOCPROC\n"); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } voice_send_cvp_deregister_vol_cal_cmd(v); voice_send_cvp_deregister_cal_cmd(v); voice_send_cvp_deregister_dev_cfg_cmd(v); voice_send_cvs_deregister_cal_cmd(v); /* destrop cvp session */ cvp_destroy_session_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_destroy_session_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_destroy_session_cmd) - APR_HDR_SIZE); pr_debug("cvp_destroy_session_cmd pkt size = %d\n", cvp_destroy_session_cmd.pkt_size); cvp_destroy_session_cmd.src_port = voice_get_idx_for_session(v->session_id); cvp_destroy_session_cmd.dest_port = cvp_handle; cvp_destroy_session_cmd.token = 0; cvp_destroy_session_cmd.opcode = APRV2_IBASIC_CMD_DESTROY_SESSION; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_destroy_session_cmd); if (ret < 0) { pr_err("Fail in sending APRV2_IBASIC_CMD_DESTROY_SESSION\n"); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } rtac_remove_voice(voice_get_cvs_handle(v)); cvp_handle = 0; voice_set_cvp_handle(v, cvp_handle); return 0; fail: return -EINVAL; } static int voice_send_mvm_unmap_memory_physical_cmd(struct voice_data *v, uint32_t mem_handle) { struct vss_imemory_cmd_unmap_t mem_unmap; int ret = 0; void *apr_mvm; u16 mvm_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); return -EINVAL; } mvm_handle = voice_get_mvm_handle(v); mem_unmap.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mem_unmap.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mem_unmap) - APR_HDR_SIZE); mem_unmap.hdr.src_port = voice_get_idx_for_session(v->session_id); mem_unmap.hdr.dest_port = mvm_handle; mem_unmap.hdr.token = 0; mem_unmap.hdr.opcode = VSS_IMEMORY_CMD_UNMAP; mem_unmap.mem_handle = mem_handle; pr_debug("%s: mem_handle: ox%x\n", __func__, mem_unmap.mem_handle); v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *) &mem_unmap); if (ret < 0) { pr_err("mem_unmap op[0x%x]ret[%d]\n", mem_unmap.hdr.opcode, ret); goto fail; } ret = wait_event_timeout(v->mvm_wait, (v->mvm_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout %d\n", __func__, ret); goto fail; } return 0; fail: return ret; } static int voice_send_cvs_packet_exchange_config_cmd(struct voice_data *v) { struct vss_istream_cmd_set_oob_packet_exchange_config_t packet_exchange_config_pkt; int ret = 0; uint64_t *dec_buf; uint64_t *enc_buf; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } dec_buf = (uint64_t *)v->shmem_info.sh_buf.buf[0].phys; enc_buf = (uint64_t *)v->shmem_info.sh_buf.buf[1].phys; apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); packet_exchange_config_pkt.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); packet_exchange_config_pkt.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(packet_exchange_config_pkt) - APR_HDR_SIZE); packet_exchange_config_pkt.hdr.src_port = voice_get_idx_for_session(v->session_id); packet_exchange_config_pkt.hdr.dest_port = cvs_handle; packet_exchange_config_pkt.hdr.token = 0; packet_exchange_config_pkt.hdr.opcode = VSS_ISTREAM_CMD_SET_OOB_PACKET_EXCHANGE_CONFIG; packet_exchange_config_pkt.mem_handle = v->shmem_info.mem_handle; packet_exchange_config_pkt.dec_buf_addr = (uint32_t)dec_buf; packet_exchange_config_pkt.dec_buf_size = 4096; packet_exchange_config_pkt.enc_buf_addr = (uint32_t)enc_buf; packet_exchange_config_pkt.enc_buf_size = 4096; pr_debug("%s: dec buf: add %p, size %d, enc buf: add %p, size %d\n", __func__, dec_buf, packet_exchange_config_pkt.dec_buf_size, enc_buf, packet_exchange_config_pkt.enc_buf_size); v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &packet_exchange_config_pkt); if (ret < 0) { pr_err("Failed to send packet exchange config cmd %d\n", ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) pr_err("%s: wait_event timeout %d\n", __func__, ret); return 0; fail: return -EINVAL; } static int voice_send_cvs_data_exchange_mode_cmd(struct voice_data *v) { struct vss_istream_cmd_set_packet_exchange_mode_t data_exchange_pkt; int ret = 0; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); data_exchange_pkt.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); data_exchange_pkt.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(data_exchange_pkt) - APR_HDR_SIZE); data_exchange_pkt.hdr.src_port = voice_get_idx_for_session(v->session_id); data_exchange_pkt.hdr.dest_port = cvs_handle; data_exchange_pkt.hdr.token = 0; data_exchange_pkt.hdr.opcode = VSS_ISTREAM_CMD_SET_PACKET_EXCHANGE_MODE; data_exchange_pkt.mode = VSS_ISTREAM_PACKET_EXCHANGE_MODE_OUT_OF_BAND; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &data_exchange_pkt); if (ret < 0) { pr_err("Failed to send data exchange mode %d\n", ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) pr_err("%s: wait_event timeout %d\n", __func__, ret); return 0; fail: return -EINVAL; } static int voice_send_stream_mute_cmd(struct voice_data *v) { struct cvs_set_mute_cmd cvs_mute_cmd; int ret = 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); goto fail; } /* send mute/unmute to cvs */ cvs_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_mute_cmd) - APR_HDR_SIZE); cvs_mute_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_mute_cmd.hdr.dest_port = voice_get_cvs_handle(v); cvs_mute_cmd.hdr.token = 0; cvs_mute_cmd.hdr.opcode = VSS_IVOLUME_CMD_MUTE_V2; cvs_mute_cmd.cvs_set_mute.direction = VSS_IVOLUME_DIRECTION_TX; cvs_mute_cmd.cvs_set_mute.mute_flag = v->stream_tx.stream_mute; cvs_mute_cmd.cvs_set_mute.ramp_duration_ms = DEFAULT_MUTE_RAMP_DURATION; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvs, (uint32_t *) &cvs_mute_cmd); if (ret < 0) { pr_err("%s: Error %d sending stream mute\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_device_mute_cmd(struct voice_data *v, uint16_t direction, uint16_t mute_flag) { struct cvp_set_mute_cmd cvp_mute_cmd; int ret = 0; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); goto fail; } if (!common.apr_q6_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); goto fail; } cvp_mute_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_mute_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_mute_cmd) - APR_HDR_SIZE); cvp_mute_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_mute_cmd.hdr.dest_port = voice_get_cvp_handle(v); cvp_mute_cmd.hdr.token = 0; cvp_mute_cmd.hdr.opcode = VSS_IVOLUME_CMD_MUTE_V2; cvp_mute_cmd.cvp_set_mute.direction = direction; cvp_mute_cmd.cvp_set_mute.mute_flag = mute_flag; cvp_mute_cmd.cvp_set_mute.ramp_duration_ms = DEFAULT_MUTE_RAMP_DURATION; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(common.apr_q6_cvp, (uint32_t *) &cvp_mute_cmd); if (ret < 0) { pr_err("%s: Error %d sending rx device cmd\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: Command timeout\n", __func__); goto fail; } return 0; fail: return -EINVAL; } static int voice_send_vol_index_cmd(struct voice_data *v) { struct cvp_set_rx_volume_index_cmd cvp_vol_cmd; int ret = 0; void *apr_cvp; u16 cvp_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvp = common.apr_q6_cvp; if (!apr_cvp) { pr_err("%s: apr_cvp is NULL.\n", __func__); return -EINVAL; } cvp_handle = voice_get_cvp_handle(v); /* send volume index to cvp */ cvp_vol_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvp_vol_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvp_vol_cmd) - APR_HDR_SIZE); cvp_vol_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); cvp_vol_cmd.hdr.dest_port = cvp_handle; cvp_vol_cmd.hdr.token = 0; cvp_vol_cmd.hdr.opcode = VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX; cvp_vol_cmd.cvp_set_vol_idx.vol_index = v->dev_rx.volume; v->cvp_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvp, (uint32_t *) &cvp_vol_cmd); if (ret < 0) { pr_err("Fail in sending RX VOL INDEX\n"); return -EINVAL; } ret = wait_event_timeout(v->cvp_wait, (v->cvp_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); return -EINVAL; } return 0; } static int voice_cvs_start_record(struct voice_data *v, uint32_t rec_mode) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct cvs_start_record_cmd cvs_start_record; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (!v->rec_info.recording) { cvs_start_record.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_start_record.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_start_record) - APR_HDR_SIZE); cvs_start_record.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_start_record.hdr.dest_port = cvs_handle; cvs_start_record.hdr.token = 0; cvs_start_record.hdr.opcode = VSS_IRECORD_CMD_START; cvs_start_record.rec_mode.port_id = VSS_IRECORD_PORT_ID_DEFAULT; if (rec_mode == VOC_REC_UPLINK) { cvs_start_record.rec_mode.rx_tap_point = VSS_IRECORD_TAP_POINT_NONE; cvs_start_record.rec_mode.tx_tap_point = VSS_IRECORD_TAP_POINT_STREAM_END; } else if (rec_mode == VOC_REC_DOWNLINK) { cvs_start_record.rec_mode.rx_tap_point = VSS_IRECORD_TAP_POINT_STREAM_END; cvs_start_record.rec_mode.tx_tap_point = VSS_IRECORD_TAP_POINT_NONE; } else if (rec_mode == VOC_REC_BOTH) { cvs_start_record.rec_mode.rx_tap_point = VSS_IRECORD_TAP_POINT_STREAM_END; cvs_start_record.rec_mode.tx_tap_point = VSS_IRECORD_TAP_POINT_STREAM_END; } else { pr_err("%s: Invalid in-call rec_mode %d\n", __func__, rec_mode); ret = -EINVAL; goto fail; } v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_record); if (ret < 0) { pr_err("%s: Error %d sending START_RECORD\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->rec_info.recording = 1; } else { pr_debug("%s: Start record already sent\n", __func__); } return 0; fail: return ret; } static int voice_cvs_stop_record(struct voice_data *v) { int ret = 0; void *apr_cvs; u16 cvs_handle; struct apr_hdr cvs_stop_record; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (v->rec_info.recording) { cvs_stop_record.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_stop_record.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_stop_record) - APR_HDR_SIZE); cvs_stop_record.src_port = voice_get_idx_for_session(v->session_id); cvs_stop_record.dest_port = cvs_handle; cvs_stop_record.token = 0; cvs_stop_record.opcode = VSS_IRECORD_CMD_STOP; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_record); if (ret < 0) { pr_err("%s: Error %d sending STOP_RECORD\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->rec_info.recording = 0; } else { pr_debug("%s: Stop record already sent\n", __func__); } return 0; fail: return ret; } int voc_start_record(uint32_t port_id, uint32_t set) { int ret = 0; int rec_mode = 0; u16 cvs_handle; int i, rec_set = 0; for (i = 0; i < MAX_VOC_SESSIONS; i++) { struct voice_data *v = &common.voice[i]; pr_debug("%s: i:%d port_id: %d, set: %d\n", __func__, i, port_id, set); mutex_lock(&v->lock); rec_mode = v->rec_info.rec_mode; rec_set = set; if (set) { if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { pr_debug("%s: i=%d, rec mode already set.\n", __func__, i); mutex_unlock(&v->lock); if (i < MAX_VOC_SESSIONS) continue; else return 0; } if (port_id == VOICE_RECORD_TX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { rec_mode = VOC_REC_UPLINK; v->rec_route_state.ul_flag = 1; } else if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); rec_mode = VOC_REC_BOTH; v->rec_route_state.ul_flag = 1; } } else if (port_id == VOICE_RECORD_RX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { rec_mode = VOC_REC_DOWNLINK; v->rec_route_state.dl_flag = 1; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag == 0)) { voice_cvs_stop_record(v); rec_mode = VOC_REC_BOTH; v->rec_route_state.dl_flag = 1; } } rec_set = 1; } else { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag == 0)) { pr_debug("%s: i=%d, rec already stops.\n", __func__, i); mutex_unlock(&v->lock); if (i < MAX_VOC_SESSIONS) continue; else return 0; } if (port_id == VOICE_RECORD_TX) { if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag == 0)) { v->rec_route_state.ul_flag = 0; rec_set = 0; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); v->rec_route_state.ul_flag = 0; rec_mode = VOC_REC_DOWNLINK; rec_set = 1; } } else if (port_id == VOICE_RECORD_RX) { if ((v->rec_route_state.ul_flag == 0) && (v->rec_route_state.dl_flag != 0)) { v->rec_route_state.dl_flag = 0; rec_set = 0; } else if ((v->rec_route_state.ul_flag != 0) && (v->rec_route_state.dl_flag != 0)) { voice_cvs_stop_record(v); v->rec_route_state.dl_flag = 0; rec_mode = VOC_REC_UPLINK; rec_set = 1; } } } pr_debug("%s: i=%d, mode =%d, set =%d\n", __func__, i, rec_mode, rec_set); cvs_handle = voice_get_cvs_handle(v); if (cvs_handle != 0) { if (rec_set) ret = voice_cvs_start_record(v, rec_mode); else ret = voice_cvs_stop_record(v); } /* Cache the value */ v->rec_info.rec_enable = rec_set; v->rec_info.rec_mode = rec_mode; mutex_unlock(&v->lock); } return ret; } static int voice_cvs_start_playback(struct voice_data *v) { int ret = 0; struct cvs_start_playback_cmd cvs_start_playback; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (!v->music_info.playing && v->music_info.count) { cvs_start_playback.hdr.hdr_field = APR_HDR_FIELD( APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_start_playback.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_start_playback) - APR_HDR_SIZE); cvs_start_playback.hdr.src_port = voice_get_idx_for_session(v->session_id); cvs_start_playback.hdr.dest_port = cvs_handle; cvs_start_playback.hdr.token = 0; cvs_start_playback.hdr.opcode = VSS_IPLAYBACK_CMD_START; cvs_start_playback.playback_mode.port_id = VSS_IPLAYBACK_PORT_ID_DEFAULT; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_start_playback); if (ret < 0) { pr_err("%s: Error %d sending START_PLAYBACK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->music_info.playing = 1; } else { pr_debug("%s: Start playback already sent\n", __func__); } return 0; fail: return ret; } static int voice_cvs_stop_playback(struct voice_data *v) { int ret = 0; struct apr_hdr cvs_stop_playback; void *apr_cvs; u16 cvs_handle; if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL.\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); if (v->music_info.playing && ((!v->music_info.count) || (v->music_info.force))) { cvs_stop_playback.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); cvs_stop_playback.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(cvs_stop_playback) - APR_HDR_SIZE); cvs_stop_playback.src_port = voice_get_idx_for_session(v->session_id); cvs_stop_playback.dest_port = cvs_handle; cvs_stop_playback.token = 0; cvs_stop_playback.opcode = VSS_IPLAYBACK_CMD_STOP; v->cvs_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_cvs, (uint32_t *) &cvs_stop_playback); if (ret < 0) { pr_err("%s: Error %d sending STOP_PLAYBACK\n", __func__, ret); goto fail; } ret = wait_event_timeout(v->cvs_wait, (v->cvs_state == CMD_STATUS_SUCCESS), msecs_to_jiffies(TIMEOUT_MS)); if (!ret) { pr_err("%s: wait_event timeout\n", __func__); goto fail; } v->music_info.playing = 0; v->music_info.force = 0; } else { pr_debug("%s: Stop playback already sent\n", __func__); } return 0; fail: return ret; } int voc_start_playback(uint32_t set) { int ret = 0; u16 cvs_handle; int i; for (i = 0; i < MAX_VOC_SESSIONS; i++) { struct voice_data *v = &common.voice[i]; mutex_lock(&v->lock); v->music_info.play_enable = set; if (set) v->music_info.count++; else v->music_info.count--; pr_debug("%s: music_info count =%d\n", __func__, v->music_info.count); cvs_handle = voice_get_cvs_handle(v); if (cvs_handle != 0) { if (set) ret = voice_cvs_start_playback(v); else ret = voice_cvs_stop_playback(v); } mutex_unlock(&v->lock); } return ret; } int voc_disable_cvp(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_RUN) { rtac_remove_voice(voice_get_cvs_handle(v)); /* send cmd to dsp to disable vocproc */ ret = voice_send_disable_vocproc_cmd(v); if (ret < 0) { pr_err("%s: disable vocproc failed\n", __func__); goto fail; } voice_send_cvp_deregister_vol_cal_cmd(v); voice_send_cvp_deregister_cal_cmd(v); voice_send_cvp_deregister_dev_cfg_cmd(v); v->voc_state = VOC_CHANGE; } fail: mutex_unlock(&v->lock); return ret; } int voc_enable_cvp(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: Invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_CHANGE) { ret = voice_send_set_device_cmd(v); if (ret < 0) { pr_err("%s: Set device failed\n", __func__); goto fail; } voice_send_cvp_register_dev_cfg_cmd(v); voice_send_cvp_register_cal_cmd(v); voice_send_cvp_register_vol_cal_cmd(v); if (v->lch_mode == VOICE_LCH_START) { pr_debug("%s: TX and RX mute ON\n", __func__); voice_send_device_mute_cmd(v, VSS_IVOLUME_DIRECTION_TX, VSS_IVOLUME_MUTE_ON); voice_send_device_mute_cmd(v, VSS_IVOLUME_DIRECTION_RX, VSS_IVOLUME_MUTE_ON); } else if (v->lch_mode == VOICE_LCH_STOP) { pr_debug("%s: TX and RX mute OFF\n", __func__); voice_send_device_mute_cmd(v, VSS_IVOLUME_DIRECTION_TX, VSS_IVOLUME_MUTE_OFF); voice_send_device_mute_cmd(v, VSS_IVOLUME_DIRECTION_RX, VSS_IVOLUME_MUTE_OFF); /* Reset lch mode when VOICE_LCH_STOP is recieved */ v->lch_mode = 0; } else { pr_debug("%s: Mute commands not sent for lch_mode=%d\n", __func__, v->lch_mode); } ret = voice_send_enable_vocproc_cmd(v); if (ret < 0) { pr_err("%s: Enable vocproc failed %d\n", __func__, ret); goto fail; } /* Send tty mode if tty device is used */ voice_send_tty_mode_cmd(v); /* enable slowtalk */ if (v->st_enable) voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, v->st_enable); rtac_add_voice(voice_get_cvs_handle(v), voice_get_cvp_handle(v), v->dev_rx.port_id, v->dev_tx.port_id, v->session_id); v->voc_state = VOC_RUN; } fail: mutex_unlock(&v->lock); return ret; } static int voice_set_packet_exchange_mode_and_config(uint32_t session_id, uint32_t mode) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } if (v->voc_state != VOC_RUN) ret = voice_send_cvs_data_exchange_mode_cmd(v); if (ret) { pr_err("%s: Error voice_send_data_exchange_mode_cmd %d\n", __func__, ret); goto fail; } ret = voice_send_cvs_packet_exchange_config_cmd(v); if (ret) { pr_err("%s: Error: voice_send_packet_exchange_config_cmd %d\n", __func__, ret); goto fail; } return ret; fail: return -EINVAL; } int voc_set_tx_mute(uint32_t session_id, uint32_t dir, uint32_t mute) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->stream_tx.stream_mute = mute; if ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY)) ret = voice_send_stream_mute_cmd(v); mutex_unlock(&v->lock); return ret; } int voc_set_rx_device_mute(uint32_t session_id, uint32_t mute) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dev_rx.dev_mute = mute; if (v->voc_state == VOC_RUN) ret = voice_send_device_mute_cmd(v, VSS_IVOLUME_DIRECTION_RX, v->dev_rx.dev_mute); mutex_unlock(&v->lock); return ret; } int voc_get_rx_device_mute(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); ret = v->dev_rx.dev_mute; mutex_unlock(&v->lock); return ret; } int voc_set_tty_mode(uint32_t session_id, uint8_t tty_mode) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->tty_mode = tty_mode; mutex_unlock(&v->lock); return ret; } uint8_t voc_get_tty_mode(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); ret = v->tty_mode; mutex_unlock(&v->lock); return ret; } int voc_set_pp_enable(uint32_t session_id, uint32_t module_id, uint32_t enable) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (module_id == MODULE_ID_VOICE_MODULE_ST) v->st_enable = enable; if (v->voc_state == VOC_RUN) { if (module_id == MODULE_ID_VOICE_MODULE_ST) ret = voice_send_set_pp_enable_cmd(v, MODULE_ID_VOICE_MODULE_ST, enable); } mutex_unlock(&v->lock); return ret; } int voc_get_pp_enable(uint32_t session_id, uint32_t module_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (module_id == MODULE_ID_VOICE_MODULE_ST) ret = v->st_enable; mutex_unlock(&v->lock); return ret; } int voc_set_rx_vol_index(uint32_t session_id, uint32_t dir, uint32_t vol_idx) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); v->dev_rx.volume = vol_idx; if ((v->voc_state == VOC_RUN) || (v->voc_state == VOC_CHANGE) || (v->voc_state == VOC_STANDBY)) ret = voice_send_vol_index_cmd(v); mutex_unlock(&v->lock); return ret; } int voc_set_rxtx_port(uint32_t session_id, uint32_t port_id, uint32_t dev_type) { struct voice_data *v = voice_get_session(session_id); if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } pr_debug("%s: port_id=%d, type=%d\n", __func__, port_id, dev_type); mutex_lock(&v->lock); if (dev_type == DEV_RX) v->dev_rx.port_id = q6audio_get_port_id(port_id); else v->dev_tx.port_id = q6audio_get_port_id(port_id); mutex_unlock(&v->lock); return 0; } int voc_set_route_flag(uint32_t session_id, uint8_t path_dir, uint8_t set) { struct voice_data *v = voice_get_session(session_id); if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } pr_debug("%s: path_dir=%d, set=%d\n", __func__, path_dir, set); mutex_lock(&v->lock); if (path_dir == RX_PATH) v->voc_route_state.rx_route_flag = set; else v->voc_route_state.tx_route_flag = set; mutex_unlock(&v->lock); return 0; } uint8_t voc_get_route_flag(uint32_t session_id, uint8_t path_dir) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return 0; } mutex_lock(&v->lock); if (path_dir == RX_PATH) ret = v->voc_route_state.rx_route_flag; else ret = v->voc_route_state.tx_route_flag; mutex_unlock(&v->lock); return ret; } int voc_end_voice_call(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_RUN || v->voc_state == VOC_ERROR || v->voc_state == VOC_CHANGE || v->voc_state == VOC_STANDBY) { pr_debug("%s: VOC_STATE: %d\n", __func__, v->voc_state); ret = voice_destroy_vocproc(v); if (ret < 0) pr_err("%s: destroy voice failed\n", __func__); voice_destroy_mvm_cvs_session(v); v->voc_state = VOC_RELEASE; } else { pr_err("%s: Error: End voice called in state %d\n", __func__, v->voc_state); ret = -EINVAL; } mutex_unlock(&v->lock); return ret; } int voc_standby_voice_call(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); struct apr_hdr mvm_standby_voice_cmd; void *apr_mvm; u16 mvm_handle; int ret = 0; pr_debug("%s: voc state=%d", __func__, v->voc_state); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (v->voc_state == VOC_RUN) { apr_mvm = common.apr_q6_mvm; if (!apr_mvm) { pr_err("%s: apr_mvm is NULL.\n", __func__); ret = -EINVAL; goto fail; } mvm_handle = voice_get_mvm_handle(v); mvm_standby_voice_cmd.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); mvm_standby_voice_cmd.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(mvm_standby_voice_cmd) - APR_HDR_SIZE); pr_debug("send mvm_standby_voice_cmd pkt size = %d\n", mvm_standby_voice_cmd.pkt_size); mvm_standby_voice_cmd.src_port = voice_get_idx_for_session(v->session_id); mvm_standby_voice_cmd.dest_port = mvm_handle; mvm_standby_voice_cmd.token = 0; mvm_standby_voice_cmd.opcode = VSS_IMVM_CMD_STANDBY_VOICE; v->mvm_state = CMD_STATUS_FAIL; ret = apr_send_pkt(apr_mvm, (uint32_t *)&mvm_standby_voice_cmd); if (ret < 0) { pr_err("Fail in sending VSS_IMVM_CMD_STANDBY_VOICE\n"); ret = -EINVAL; goto fail; } v->voc_state = VOC_STANDBY; } fail: return ret; } int voc_set_lch(uint32_t session_id, enum voice_lch_mode lch_mode) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: Invalid session_id 0x%x\n", __func__, session_id); ret = -EINVAL; goto done; } mutex_lock(&v->lock); if (v->lch_mode == lch_mode) { pr_debug("%s: Session %d already in LCH mode %d\n", __func__, session_id, lch_mode); mutex_unlock(&v->lock); goto done; } v->lch_mode = lch_mode; mutex_unlock(&v->lock); ret = voc_disable_cvp(session_id); if (ret < 0) { pr_err("%s: voc_disable_cvp failed ret=%d\n", __func__, ret); goto done; } /* Mute and topology_none will be set as part of voc_enable_cvp() */ ret = voc_enable_cvp(session_id); if (ret < 0) { pr_err("%s: voc_enable_cvp failed ret=%d\n", __func__, ret); goto done; } done: return ret; } int voc_resume_voice_call(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; ret = voice_send_start_voice_cmd(v); if (ret < 0) { pr_err("Fail in sending START_VOICE\n"); goto fail; } v->voc_state = VOC_RUN; return 0; fail: return -EINVAL; } int voc_start_voice_call(uint32_t session_id) { struct voice_data *v = voice_get_session(session_id); int ret = 0; if (v == NULL) { pr_err("%s: invalid session_id 0x%x\n", __func__, session_id); return -EINVAL; } mutex_lock(&v->lock); if (v->voc_state == VOC_ERROR) { pr_debug("%s: VOC in ERR state\n", __func__); voice_destroy_mvm_cvs_session(v); v->voc_state = VOC_INIT; } if ((v->voc_state == VOC_INIT) || (v->voc_state == VOC_RELEASE)) { ret = voice_apr_register(); if (ret < 0) { pr_err("%s: apr register failed\n", __func__); goto fail; } ret = voice_create_mvm_cvs_session(v); if (ret < 0) { pr_err("create mvm and cvs failed\n"); goto fail; } /* Memory map the calibration memory block. */ ret = voice_mem_map_cal_block(v); if (ret < 0) { pr_err("%s: Memory map of cal block failed %d\n", __func__, ret); /* Allow call to continue, call quality will be bad. */ } if (is_voip_session(session_id)) { ret = voice_map_memory_physical_cmd(v, &v->shmem_info.memtbl, v->shmem_info.sh_buf.buf[0].phys, v->shmem_info.sh_buf.buf[0].size * NUM_OF_BUFFERS, VOIP_MEM_MAP_TOKEN); if (ret) { pr_err("%s: mvm_map_memory_phy failed %d\n", __func__, ret); goto fail; } ret = voice_set_packet_exchange_mode_and_config( session_id, VSS_ISTREAM_PACKET_EXCHANGE_MODE_OUT_OF_BAND); if (ret) { pr_err("%s: Err: exchange_mode_and_config %d\n", __func__, ret); goto fail; } } ret = voice_send_dual_control_cmd(v); if (ret < 0) { pr_err("Err Dual command failed\n"); goto fail; } ret = voice_setup_vocproc(v); if (ret < 0) { pr_err("setup voice failed\n"); goto fail; } ret = voice_send_vol_index_cmd(v); if (ret < 0) pr_err("voice volume failed\n"); ret = voice_send_stream_mute_cmd(v); if (ret < 0) pr_err("voice mute failed\n"); ret = voice_send_start_voice_cmd(v); if (ret < 0) { pr_err("start voice failed\n"); goto fail; } v->voc_state = VOC_RUN; } else { pr_err("%s: Error: Start voice called in state %d\n", __func__, v->voc_state); ret = -EINVAL; goto fail; } fail: mutex_unlock(&v->lock); return ret; } void voc_register_mvs_cb(ul_cb_fn ul_cb, dl_cb_fn dl_cb, void *private_data) { common.mvs_info.ul_cb = ul_cb; common.mvs_info.dl_cb = dl_cb; common.mvs_info.private_data = private_data; } void voc_register_dtmf_rx_detection_cb(dtmf_rx_det_cb_fn dtmf_rx_ul_cb, void *private_data) { common.dtmf_info.dtmf_rx_ul_cb = dtmf_rx_ul_cb; common.dtmf_info.private_data = private_data; } void voc_config_vocoder(uint32_t media_type, uint32_t rate, uint32_t network_type, uint32_t dtx_mode) { common.mvs_info.media_type = media_type; common.mvs_info.rate = rate; common.mvs_info.network_type = network_type; common.mvs_info.dtx_mode = dtx_mode; } static int32_t qdsp_mvm_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__, data->payload_size, data->opcode); if (data->opcode == RESET_EVENTS) { if (data->reset_proc == APR_DEST_MODEM) { pr_debug("%s: Received MODEM reset event\n", __func__); } else { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_mvm); c->apr_q6_mvm = NULL; /* clean up memory handle */ c->cal_mem_handle = 0; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) { c->voice[i].mvm_handle = 0; c->voice[i].shmem_info.mem_handle = 0; } } voc_set_error_state(data->reset_proc); return 0; } pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port); v = voice_get_session_by_idx(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_debug("%x %x\n", ptr[0], ptr[1]); /* ping mvm service ACK */ switch (ptr[0]) { case VSS_IMVM_CMD_CREATE_PASSIVE_CONTROL_SESSION: case VSS_IMVM_CMD_CREATE_FULL_CONTROL_SESSION: /* Passive session is used for CS call * Full session is used for VoIP call. */ pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); if (!ptr[1]) { pr_debug("%s: MVM handle is %d\n", __func__, data->src_port); voice_set_mvm_handle(v, data->src_port); } else pr_err("got NACK for sending MVM create session\n"); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); break; case VSS_IMVM_CMD_START_VOICE: case VSS_IMVM_CMD_ATTACH_VOCPROC: case VSS_IMVM_CMD_STOP_VOICE: case VSS_IMVM_CMD_DETACH_VOCPROC: case VSS_ISTREAM_CMD_SET_TTY_MODE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_IMVM_CMD_ATTACH_STREAM: case VSS_IMVM_CMD_DETACH_STREAM: case VSS_ICOMMON_CMD_SET_NETWORK: case VSS_ICOMMON_CMD_SET_VOICE_TIMING: case VSS_IMVM_CMD_SET_POLICY_DUAL_CONTROL: case VSS_IMVM_CMD_SET_CAL_NETWORK: case VSS_IMVM_CMD_SET_CAL_MEDIA_TYPE: case VSS_IMEMORY_CMD_MAP_PHYSICAL: case VSS_IMEMORY_CMD_UNMAP: case VSS_IMVM_CMD_PAUSE_VOICE: case VSS_IMVM_CMD_STANDBY_VOICE: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); break; default: pr_debug("%s: not match cmd = 0x%x\n", __func__, ptr[0]); break; } } } else if (data->opcode == VSS_IMEMORY_RSP_MAP) { pr_debug("%s, Revd VSS_IMEMORY_RSP_MAP response\n", __func__); if (data->payload_size && data->token == VOIP_MEM_MAP_TOKEN) { ptr = data->payload; if (ptr[0]) { v->shmem_info.mem_handle = ptr[0]; pr_debug("%s: shared mem_handle: 0x[%x]\n", __func__, v->shmem_info.mem_handle); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); } } else if (data->payload_size && data->token == VOC_CAL_MEM_MAP_TOKEN) { ptr = data->payload; if (ptr[0]) { c->cal_mem_handle = ptr[0]; pr_debug("%s: cal mem handle 0x%x\n", __func__, c->cal_mem_handle); v->mvm_state = CMD_STATUS_SUCCESS; wake_up(&v->mvm_wait); } } else { pr_err("%s: Unknown mem map token %d\n", __func__, data->token); } } return 0; } static int32_t qdsp_cvs_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; pr_debug("%s: session_id 0x%x\n", __func__, data->dest_port); pr_debug("%s: Payload Length = %d, opcode=%x\n", __func__, data->payload_size, data->opcode); if (data->opcode == RESET_EVENTS) { if (data->reset_proc == APR_DEST_MODEM) { pr_debug("%s: Received Modem reset event\n", __func__); } else { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_cvs); c->apr_q6_cvs = NULL; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) c->voice[i].cvs_handle = 0; } voc_set_error_state(data->reset_proc); return 0; } v = voice_get_session_by_idx(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_debug("%x %x\n", ptr[0], ptr[1]); if (ptr[1] != 0) { pr_err("%s: cmd = 0x%x returned error = 0x%x\n", __func__, ptr[0], ptr[1]); } /*response from CVS */ switch (ptr[0]) { case VSS_ISTREAM_CMD_CREATE_PASSIVE_CONTROL_SESSION: case VSS_ISTREAM_CMD_CREATE_FULL_CONTROL_SESSION: if (!ptr[1]) { pr_debug("%s: CVS handle is %d\n", __func__, data->src_port); voice_set_cvs_handle(v, data->src_port); } else pr_err("got NACK for sending CVS create session\n"); v->cvs_state = CMD_STATUS_SUCCESS; wake_up(&v->cvs_wait); break; case VSS_IVOLUME_CMD_MUTE_V2: case VSS_ISTREAM_CMD_SET_MEDIA_TYPE: case VSS_ISTREAM_CMD_VOC_AMR_SET_ENC_RATE: case VSS_ISTREAM_CMD_VOC_AMRWB_SET_ENC_RATE: case VSS_ISTREAM_CMD_SET_ENC_DTX_MODE: case VSS_ISTREAM_CMD_CDMA_SET_ENC_MINMAX_RATE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_ISTREAM_CMD_REGISTER_CALIBRATION_DATA_V2: case VSS_ISTREAM_CMD_DEREGISTER_CALIBRATION_DATA: case VSS_ICOMMON_CMD_MAP_MEMORY: case VSS_ICOMMON_CMD_UNMAP_MEMORY: case VSS_ICOMMON_CMD_SET_UI_PROPERTY: case VSS_IPLAYBACK_CMD_START: case VSS_IPLAYBACK_CMD_STOP: case VSS_IRECORD_CMD_START: case VSS_IRECORD_CMD_STOP: case VSS_ISTREAM_CMD_SET_PACKET_EXCHANGE_MODE: case VSS_ISTREAM_CMD_SET_OOB_PACKET_EXCHANGE_CONFIG: case VSS_ISTREAM_CMD_SET_RX_DTMF_DETECTION: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); v->cvs_state = CMD_STATUS_SUCCESS; wake_up(&v->cvs_wait); break; case VOICE_CMD_SET_PARAM: pr_debug("%s: VOICE_CMD_SET_PARAM\n", __func__); rtac_make_voice_callback(RTAC_CVS, ptr, data->payload_size); break; case VOICE_CMD_GET_PARAM: pr_debug("%s: VOICE_CMD_GET_PARAM\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ /* VOICE_EVT_GET_PARAM_ACK */ if (ptr[1] != 0) { pr_err("%s: CVP get param error = %d, resuming\n", __func__, ptr[1]); rtac_make_voice_callback(RTAC_CVP, data->payload, data->payload_size); } break; default: pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); break; } } } else if (data->opcode == VSS_ISTREAM_EVT_OOB_NOTIFY_ENC_BUFFER_READY) { int ret = 0; u16 cvs_handle; uint32_t *cvs_voc_pkt; struct cvs_enc_buffer_consumed_cmd send_enc_buf_consumed_cmd; void *apr_cvs; pr_debug("Encoder buffer is ready\n"); apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); send_enc_buf_consumed_cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); send_enc_buf_consumed_cmd.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(send_enc_buf_consumed_cmd) - APR_HDR_SIZE); send_enc_buf_consumed_cmd.hdr.src_port = voice_get_idx_for_session(v->session_id); send_enc_buf_consumed_cmd.hdr.dest_port = cvs_handle; send_enc_buf_consumed_cmd.hdr.token = 0; send_enc_buf_consumed_cmd.hdr.opcode = VSS_ISTREAM_EVT_OOB_NOTIFY_ENC_BUFFER_CONSUMED; cvs_voc_pkt = v->shmem_info.sh_buf.buf[1].data; if (cvs_voc_pkt != NULL && common.mvs_info.ul_cb != NULL) { common.mvs_info.ul_cb((uint8_t *)&cvs_voc_pkt[3], cvs_voc_pkt[2], common.mvs_info.private_data); } else pr_err("%s: cvs_voc_pkt or ul_cb is NULL\n", __func__); ret = apr_send_pkt(apr_cvs, (uint32_t *) &send_enc_buf_consumed_cmd); if (ret < 0) { pr_err("%s: Err send ENC_BUF_CONSUMED_NOTIFY %d\n", __func__, ret); goto fail; } } else if (data->opcode == VSS_ISTREAM_EVT_SEND_ENC_BUFFER) { pr_debug("Recd VSS_ISTREAM_EVT_SEND_ENC_BUFFER\n"); } else if (data->opcode == VSS_ISTREAM_EVT_OOB_NOTIFY_DEC_BUFFER_REQUEST) { int ret = 0; u16 cvs_handle; uint32_t *cvs_voc_pkt; struct cvs_dec_buffer_ready_cmd send_dec_buf; void *apr_cvs; apr_cvs = common.apr_q6_cvs; if (!apr_cvs) { pr_err("%s: apr_cvs is NULL\n", __func__); return -EINVAL; } cvs_handle = voice_get_cvs_handle(v); send_dec_buf.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER); send_dec_buf.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE, sizeof(send_dec_buf) - APR_HDR_SIZE); send_dec_buf.hdr.src_port = voice_get_idx_for_session(v->session_id); send_dec_buf.hdr.dest_port = cvs_handle; send_dec_buf.hdr.token = 0; send_dec_buf.hdr.opcode = VSS_ISTREAM_EVT_OOB_NOTIFY_DEC_BUFFER_READY; cvs_voc_pkt = (uint32_t *)(v->shmem_info.sh_buf.buf[0].data); if (cvs_voc_pkt != NULL && common.mvs_info.dl_cb != NULL) { /* Set timestamp to 0 and advance the pointer */ cvs_voc_pkt[0] = 0; /* Set media_type and advance the pointer */ cvs_voc_pkt[1] = common.mvs_info.media_type; common.mvs_info.dl_cb( (uint8_t *)&cvs_voc_pkt[2], common.mvs_info.private_data); ret = apr_send_pkt(apr_cvs, (uint32_t *) &send_dec_buf); if (ret < 0) { pr_err("%s: Err send DEC_BUF_READY_NOTIFI %d\n", __func__, ret); goto fail; } } else { pr_debug("%s: voc_pkt or dl_cb is NULL\n", __func__); goto fail; } } else if (data->opcode == VSS_ISTREAM_EVT_REQUEST_DEC_BUFFER) { pr_debug("Recd VSS_ISTREAM_EVT_REQUEST_DEC_BUFFER\n"); } else if (data->opcode == VSS_ISTREAM_EVT_SEND_DEC_BUFFER) { pr_debug("Send dec buf resp\n"); } else if (data->opcode == APR_RSP_ACCEPTED) { ptr = data->payload; if (ptr[0]) pr_debug("%s: APR_RSP_ACCEPTED for 0x%x:\n", __func__, ptr[0]); } else if (data->opcode == VSS_ISTREAM_EVT_NOT_READY) { pr_debug("Recd VSS_ISTREAM_EVT_NOT_READY\n"); } else if (data->opcode == VSS_ISTREAM_EVT_READY) { pr_debug("Recd VSS_ISTREAM_EVT_READY\n"); } else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) { pr_debug("%s: VOICE_EVT_GET_PARAM_ACK\n", __func__); ptr = data->payload; if (ptr[0] != 0) { pr_err("%s: VOICE_EVT_GET_PARAM_ACK returned error = 0x%x\n", __func__, ptr[0]); } rtac_make_voice_callback(RTAC_CVS, data->payload, data->payload_size); } else if (data->opcode == VSS_ISTREAM_EVT_RX_DTMF_DETECTED) { struct vss_istream_evt_rx_dtmf_detected *dtmf_rx_detected; uint32_t *voc_pkt = data->payload; uint32_t pkt_len = data->payload_size; if ((voc_pkt != NULL) && (pkt_len == sizeof(struct vss_istream_evt_rx_dtmf_detected))) { dtmf_rx_detected = (struct vss_istream_evt_rx_dtmf_detected *) voc_pkt; pr_debug("RX_DTMF_DETECTED low_freq=%d high_freq=%d\n", dtmf_rx_detected->low_freq, dtmf_rx_detected->high_freq); if (c->dtmf_info.dtmf_rx_ul_cb) c->dtmf_info.dtmf_rx_ul_cb((uint8_t *)voc_pkt, voc_get_session_name(v->session_id), c->dtmf_info.private_data); } else { pr_err("Invalid packet\n"); } } else pr_debug("Unknown opcode 0x%x\n", data->opcode); fail: return 0; } static int32_t qdsp_cvp_callback(struct apr_client_data *data, void *priv) { uint32_t *ptr = NULL; struct common_data *c = NULL; struct voice_data *v = NULL; int i = 0; if ((data == NULL) || (priv == NULL)) { pr_err("%s: data or priv is NULL\n", __func__); return -EINVAL; } c = priv; if (data->opcode == RESET_EVENTS) { if (data->reset_proc == APR_DEST_MODEM) { pr_debug("%s: Received Modem reset event\n", __func__); } else { pr_debug("%s: Reset event received in Voice service\n", __func__); apr_reset(c->apr_q6_cvp); c->apr_q6_cvp = NULL; /* Sub-system restart is applicable to all sessions. */ for (i = 0; i < MAX_VOC_SESSIONS; i++) c->voice[i].cvp_handle = 0; } voc_set_error_state(data->reset_proc); return 0; } v = voice_get_session_by_idx(data->dest_port); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } if (data->opcode == APR_BASIC_RSP_RESULT) { if (data->payload_size) { ptr = data->payload; pr_debug("%x %x\n", ptr[0], ptr[1]); if (ptr[1] != 0) { pr_err("%s: cmd = 0x%x returned error = 0x%x\n", __func__, ptr[0], ptr[1]); } switch (ptr[0]) { case VSS_IVOCPROC_CMD_CREATE_FULL_CONTROL_SESSION_V2: /*response from CVP */ pr_debug("%s: cmd = 0x%x\n", __func__, ptr[0]); if (!ptr[1]) { voice_set_cvp_handle(v, data->src_port); pr_debug("status: %d, cvphdl=%d\n", ptr[1], data->src_port); } else pr_err("got NACK from CVP create session response\n"); v->cvp_state = CMD_STATUS_SUCCESS; wake_up(&v->cvp_wait); break; case VSS_IVOCPROC_CMD_SET_DEVICE_V2: case VSS_IVOCPROC_CMD_SET_RX_VOLUME_INDEX: case VSS_IVOCPROC_CMD_ENABLE: case VSS_IVOCPROC_CMD_DISABLE: case APRV2_IBASIC_CMD_DESTROY_SESSION: case VSS_IVOCPROC_CMD_REGISTER_VOL_CALIBRATION_DATA: case VSS_IVOCPROC_CMD_DEREGISTER_VOL_CALIBRATION_DATA: case VSS_IVOCPROC_CMD_REGISTER_CALIBRATION_DATA_V2: case VSS_IVOCPROC_CMD_DEREGISTER_CALIBRATION_DATA: case VSS_IVOCPROC_CMD_REGISTER_DEVICE_CONFIG: case VSS_IVOCPROC_CMD_DEREGISTER_DEVICE_CONFIG: case VSS_ICOMMON_CMD_MAP_MEMORY: case VSS_ICOMMON_CMD_UNMAP_MEMORY: case VSS_IVOLUME_CMD_MUTE_V2: v->cvp_state = CMD_STATUS_SUCCESS; wake_up(&v->cvp_wait); break; case VOICE_CMD_SET_PARAM: pr_debug("%s: VOICE_CMD_SET_PARAM\n", __func__); rtac_make_voice_callback(RTAC_CVP, ptr, data->payload_size); break; case VOICE_CMD_GET_PARAM: pr_debug("%s: VOICE_CMD_GET_PARAM\n", __func__); /* Should only come here if there is an APR */ /* error or malformed APR packet. Otherwise */ /* response will be returned as */ /* VOICE_EVT_GET_PARAM_ACK */ if (ptr[1] != 0) { pr_err("%s: CVP get param error = %d, resuming\n", __func__, ptr[1]); rtac_make_voice_callback(RTAC_CVP, data->payload, data->payload_size); } break; default: pr_debug("%s: not match cmd = 0x%x\n", __func__, ptr[0]); break; } } } else if (data->opcode == VOICE_EVT_GET_PARAM_ACK) { pr_debug("%s: VOICE_EVT_GET_PARAM_ACK\n", __func__); ptr = data->payload; if (ptr[0] != 0) { pr_err("%s: VOICE_EVT_GET_PARAM_ACK returned error = 0x%x\n", __func__, ptr[0]); } rtac_make_voice_callback(RTAC_CVP, data->payload, data->payload_size); } return 0; } static int voice_alloc_oob_shared_mem(void) { int cnt = 0; int rc = 0; int len; void *mem_addr; dma_addr_t phys; int bufsz = BUFFER_BLOCK_SIZE; int bufcnt = NUM_OF_BUFFERS; struct voice_data *v = voice_get_session( common.voice[VOC_PATH_FULL].session_id); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } rc = msm_audio_ion_alloc("voip_client", &(v->shmem_info.sh_buf.client), &(v->shmem_info.sh_buf.handle), bufsz*bufcnt, (ion_phys_addr_t *)&phys, (size_t *)&len, &mem_addr); if (rc) { pr_err("%s: audio ION alloc failed, rc = %d\n", __func__, rc); return -EINVAL; } while (cnt < bufcnt) { v->shmem_info.sh_buf.buf[cnt].data = mem_addr + (cnt * bufsz); v->shmem_info.sh_buf.buf[cnt].phys = phys + (cnt * bufsz); v->shmem_info.sh_buf.buf[cnt].size = bufsz; cnt++; } pr_debug("%s buf[0].data:[%p], buf[0].phys:[%p], &buf[0].phys:[%p],\n", __func__, (void *)v->shmem_info.sh_buf.buf[0].data, (void *)v->shmem_info.sh_buf.buf[0].phys, (void *)&v->shmem_info.sh_buf.buf[0].phys); pr_debug("%s: buf[1].data:[%p], buf[1].phys[%p], &buf[1].phys[%p]\n", __func__, (void *)v->shmem_info.sh_buf.buf[1].data, (void *)v->shmem_info.sh_buf.buf[1].phys, (void *)&v->shmem_info.sh_buf.buf[1].phys); memset((void *)v->shmem_info.sh_buf.buf[0].data, 0, (bufsz * bufcnt)); return 0; } static int voice_alloc_oob_mem_table(void) { int rc = 0; int len; struct voice_data *v = voice_get_session( common.voice[VOC_PATH_FULL].session_id); if (v == NULL) { pr_err("%s: v is NULL\n", __func__); return -EINVAL; } rc = msm_audio_ion_alloc("voip_client", &(v->shmem_info.memtbl.client), &(v->shmem_info.memtbl.handle), sizeof(struct vss_imemory_table_t), (ion_phys_addr_t *)&v->shmem_info.memtbl.phys, (size_t *)&len, &(v->shmem_info.memtbl.data)); if (rc) { pr_err("%s: audio ION alloc failed, rc = %d\n", __func__, rc); return -EINVAL; } v->shmem_info.memtbl.size = sizeof(struct vss_imemory_table_t); pr_debug("%s data[%p]phys[%p][%p]\n", __func__, (void *)v->shmem_info.memtbl.data, (void *)v->shmem_info.memtbl.phys, (void *)&v->shmem_info.memtbl.phys); return 0; } static int voice_alloc_cal_mem_map_table(void) { int ret = 0; int len; ret = msm_audio_ion_alloc("voip_client", &(common.cal_mem_map_table.client), &(common.cal_mem_map_table.handle), sizeof(struct vss_imemory_table_t), (ion_phys_addr_t *)&common.cal_mem_map_table.phys, (size_t *) &len, &(common.cal_mem_map_table.data)); if (ret) { pr_err("%s: audio ION alloc failed, rc = %d\n", __func__, ret); return -EINVAL; } common.cal_mem_map_table.size = sizeof(struct vss_imemory_table_t); pr_debug("%s: data 0x%x phys 0x%x\n", __func__, (unsigned int) common.cal_mem_map_table.data, common.cal_mem_map_table.phys); return 0; } static int __init voice_init(void) { int rc = 0, i = 0; memset(&common, 0, sizeof(struct common_data)); /* set default value */ common.default_mute_val = 0; /* default is un-mute */ common.default_vol_val = 0; common.default_sample_val = 8000; /* Initialize MVS info. */ common.mvs_info.network_type = VSS_NETWORK_ID_DEFAULT; mutex_init(&common.common_lock); /* Initialize session id with vsid */ init_session_id(); for (i = 0; i < MAX_VOC_SESSIONS; i++) { /* initialize dev_rx and dev_tx */ common.voice[i].dev_rx.volume = common.default_vol_val; common.voice[i].dev_rx.dev_mute = common.default_mute_val; common.voice[i].dev_tx.dev_mute = common.default_mute_val; common.voice[i].stream_rx.stream_mute = common.default_mute_val; common.voice[i].stream_tx.stream_mute = common.default_mute_val; common.voice[i].dev_tx.port_id = 0x100B; common.voice[i].dev_rx.port_id = 0x100A; common.voice[i].sidetone_gain = 0x512; common.voice[i].dtmf_rx_detect_en = 0; common.voice[i].lch_mode = 0; common.voice[i].voc_state = VOC_INIT; init_waitqueue_head(&common.voice[i].mvm_wait); init_waitqueue_head(&common.voice[i].cvs_wait); init_waitqueue_head(&common.voice[i].cvp_wait); mutex_init(&common.voice[i].lock); } /* Allocate shared memory for OOB Voip */ rc = voice_alloc_oob_shared_mem(); if (rc < 0) pr_err("failed to alloc shared memory for OOB %d\n", rc); else { /* Allocate mem map table for OOB */ rc = voice_alloc_oob_mem_table(); if (rc < 0) pr_err("failed to alloc mem map talbe %d\n", rc); } /* Allocate memory for calibration memory map table. */ rc = voice_alloc_cal_mem_map_table(); return rc; } late_initcall(voice_init);
upworkstar/AndroidAmazon
sound/soc/msm/qdsp6v2/q6voice.c
C
gpl-2.0
133,119
/* * Copyright 2005 Eric Anholt * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Authors: * Eric Anholt <[email protected]> * */ #include "sis_context.h" #include "sis_state.h" #include "sis_tris.h" #include "sis_lock.h" #include "sis_tex.h" #include "sis_reg.h" #include "context.h" #include "enums.h" #include "colormac.h" #include "swrast/swrast.h" #include "vbo/vbo.h" #include "tnl/tnl.h" #include "swrast_setup/swrast_setup.h" #include "tnl/t_pipeline.h" /* ============================================================= * Alpha blending */ static void sis6326DDAlphaFunc( GLcontext *ctx, GLenum func, GLfloat ref ) { sisContextPtr smesa = SIS_CONTEXT(ctx); GLubyte refbyte; __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; CLAMPED_FLOAT_TO_UBYTE(refbyte, ref); current->hwAlpha = refbyte << 16; /* Alpha Test function */ switch (func) { case GL_NEVER: current->hwAlpha |= S_ASET_PASS_NEVER; break; case GL_LESS: current->hwAlpha |= S_ASET_PASS_LESS; break; case GL_EQUAL: current->hwAlpha |= S_ASET_PASS_EQUAL; break; case GL_LEQUAL: current->hwAlpha |= S_ASET_PASS_LEQUAL; break; case GL_GREATER: current->hwAlpha |= S_ASET_PASS_GREATER; break; case GL_NOTEQUAL: current->hwAlpha |= S_ASET_PASS_NOTEQUAL; break; case GL_GEQUAL: current->hwAlpha |= S_ASET_PASS_GEQUAL; break; case GL_ALWAYS: current->hwAlpha |= S_ASET_PASS_ALWAYS; break; } prev->hwAlpha = current->hwAlpha; smesa->GlobalFlag |= GFLAG_ALPHASETTING; } static void sis6326DDBlendFuncSeparate( GLcontext *ctx, GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorA, GLenum dfactorA ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; current->hwDstSrcBlend = 0; switch (dfactorRGB) { case GL_ZERO: current->hwDstSrcBlend |= S_DBLEND_ZERO; break; case GL_ONE: current->hwDstSrcBlend |= S_DBLEND_ONE; break; case GL_SRC_COLOR: current->hwDstSrcBlend |= S_DBLEND_SRC_COLOR; break; case GL_ONE_MINUS_SRC_COLOR: current->hwDstSrcBlend |= S_DBLEND_INV_SRC_COLOR; break; case GL_SRC_ALPHA: current->hwDstSrcBlend |= S_DBLEND_SRC_ALPHA; break; case GL_ONE_MINUS_SRC_ALPHA: current->hwDstSrcBlend |= S_DBLEND_INV_SRC_ALPHA; break; case GL_DST_ALPHA: current->hwDstSrcBlend |= S_DBLEND_DST_ALPHA; break; case GL_ONE_MINUS_DST_ALPHA: current->hwDstSrcBlend |= S_DBLEND_INV_DST_ALPHA; break; } switch (sfactorRGB) { case GL_ZERO: current->hwDstSrcBlend |= S_SBLEND_ZERO; break; case GL_ONE: current->hwDstSrcBlend |= S_SBLEND_ONE; break; case GL_SRC_ALPHA: current->hwDstSrcBlend |= S_SBLEND_SRC_ALPHA; break; case GL_ONE_MINUS_SRC_ALPHA: current->hwDstSrcBlend |= S_SBLEND_INV_SRC_ALPHA; break; case GL_DST_ALPHA: current->hwDstSrcBlend |= S_SBLEND_DST_ALPHA; break; case GL_ONE_MINUS_DST_ALPHA: current->hwDstSrcBlend |= S_SBLEND_INV_DST_ALPHA; break; case GL_DST_COLOR: current->hwDstSrcBlend |= S_SBLEND_DST_COLOR; break; case GL_ONE_MINUS_DST_COLOR: current->hwDstSrcBlend |= S_SBLEND_INV_DST_COLOR; break; case GL_SRC_ALPHA_SATURATE: current->hwDstSrcBlend |= S_SBLEND_SRC_ALPHA_SAT; break; } if (current->hwDstSrcBlend != prev->hwDstSrcBlend) { prev->hwDstSrcBlend = current->hwDstSrcBlend; smesa->GlobalFlag |= GFLAG_DSTBLEND; } } /* ============================================================= * Depth testing */ static void sis6326DDDepthFunc( GLcontext *ctx, GLenum func ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; current->hwZ &= ~MASK_6326_ZTestMode; switch (func) { case GL_LESS: current->hwZ |= S_ZSET_PASS_LESS; break; case GL_GEQUAL: current->hwZ |= S_ZSET_PASS_GEQUAL; break; case GL_LEQUAL: current->hwZ |= S_ZSET_PASS_LEQUAL; break; case GL_GREATER: current->hwZ |= S_ZSET_PASS_GREATER; break; case GL_NOTEQUAL: current->hwZ |= S_ZSET_PASS_NOTEQUAL; break; case GL_EQUAL: current->hwZ |= S_ZSET_PASS_EQUAL; break; case GL_ALWAYS: current->hwZ |= S_ZSET_PASS_ALWAYS; break; case GL_NEVER: current->hwZ |= S_ZSET_PASS_NEVER; break; } if (current->hwZ != prev->hwZ) { prev->hwZ = current->hwZ; smesa->GlobalFlag |= GFLAG_ZSETTING; } } static void sis6326DDDepthMask( GLcontext *ctx, GLboolean flag ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *current = &smesa->current; if (ctx->Depth.Test) current->hwCapEnable |= S_ENABLE_ZWrite; else current->hwCapEnable &= ~S_ENABLE_ZWrite; } /* ============================================================= * Fog */ static void sis6326DDFogfv( GLcontext *ctx, GLenum pname, const GLfloat *params ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *current = &smesa->current; __GLSiSHardware *prev = &smesa->prev; GLint fogColor; switch(pname) { case GL_FOG_COLOR: fogColor = FLOAT_TO_UBYTE( ctx->Fog.Color[0] ) << 16; fogColor |= FLOAT_TO_UBYTE( ctx->Fog.Color[1] ) << 8; fogColor |= FLOAT_TO_UBYTE( ctx->Fog.Color[2] ); current->hwFog = 0x01000000 | fogColor; if (current->hwFog != prev->hwFog) { prev->hwFog = current->hwFog; smesa->GlobalFlag |= GFLAG_FOGSETTING; } break; } } /* ============================================================= * Clipping */ void sis6326UpdateClipping(GLcontext *ctx) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; GLint x1, y1, x2, y2; x1 = 0; y1 = 0; x2 = smesa->width - 1; y2 = smesa->height - 1; if (ctx->Scissor.Enabled) { if (ctx->Scissor.X > x1) x1 = ctx->Scissor.X; if (ctx->Scissor.Y > y1) y1 = ctx->Scissor.Y; if (ctx->Scissor.X + ctx->Scissor.Width - 1 < x2) x2 = ctx->Scissor.X + ctx->Scissor.Width - 1; if (ctx->Scissor.Y + ctx->Scissor.Height - 1 < y2) y2 = ctx->Scissor.Y + ctx->Scissor.Height - 1; } y1 = Y_FLIP(y1); y2 = Y_FLIP(y2); /*current->clipTopBottom = (y2 << 13) | y1; current->clipLeftRight = (x1 << 13) | x2;*/ /* XXX */ current->clipTopBottom = (0 << 13) | smesa->height; current->clipLeftRight = (0 << 13) | smesa->width; if ((current->clipTopBottom != prev->clipTopBottom) || (current->clipLeftRight != prev->clipLeftRight)) { prev->clipTopBottom = current->clipTopBottom; prev->clipLeftRight = current->clipLeftRight; smesa->GlobalFlag |= GFLAG_CLIPPING; } } static void sis6326DDScissor( GLcontext *ctx, GLint x, GLint y, GLsizei w, GLsizei h ) { if (ctx->Scissor.Enabled) sis6326UpdateClipping( ctx ); } /* ============================================================= * Culling */ static void sis6326UpdateCull( GLcontext *ctx ) { /* XXX culling */ } static void sis6326DDCullFace( GLcontext *ctx, GLenum mode ) { sis6326UpdateCull( ctx ); } static void sis6326DDFrontFace( GLcontext *ctx, GLenum mode ) { sis6326UpdateCull( ctx ); } /* ============================================================= * Masks */ static void sis6326DDColorMask( GLcontext *ctx, GLboolean r, GLboolean g, GLboolean b, GLboolean a ) { sisContextPtr smesa = SIS_CONTEXT(ctx); if (r && g && b && ((ctx->Visual.alphaBits == 0) || a)) { FALLBACK(smesa, SIS_FALLBACK_WRITEMASK, 0); } else { FALLBACK(smesa, SIS_FALLBACK_WRITEMASK, 1); } } /* ============================================================= * Rendering attributes */ static void sis6326UpdateSpecular(GLcontext *ctx) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *current = &smesa->current; if (NEED_SECONDARY_COLOR(ctx)) current->hwCapEnable |= S_ENABLE_Specular; else current->hwCapEnable &= ~S_ENABLE_Specular; } static void sis6326DDLightModelfv(GLcontext *ctx, GLenum pname, const GLfloat *param) { if (pname == GL_LIGHT_MODEL_COLOR_CONTROL) { sis6326UpdateSpecular(ctx); } } static void sis6326DDShadeModel( GLcontext *ctx, GLenum mode ) { sisContextPtr smesa = SIS_CONTEXT(ctx); /* Signal to sisRasterPrimitive to recalculate dwPrimitiveSet */ smesa->hw_primitive = -1; } /* ============================================================= * Window position */ /* ============================================================= * Viewport */ static void sis6326CalcViewport( GLcontext *ctx ) { sisContextPtr smesa = SIS_CONTEXT(ctx); const GLfloat *v = ctx->Viewport._WindowMap.m; GLfloat *m = smesa->hw_viewport; /* See also sis_translate_vertex. */ m[MAT_SX] = v[MAT_SX]; m[MAT_TX] = v[MAT_TX] + SUBPIXEL_X; m[MAT_SY] = - v[MAT_SY]; m[MAT_TY] = - v[MAT_TY] + smesa->driDrawable->h + SUBPIXEL_Y; m[MAT_SZ] = v[MAT_SZ] * smesa->depth_scale; m[MAT_TZ] = v[MAT_TZ] * smesa->depth_scale; } static void sis6326DDViewport( GLcontext *ctx, GLint x, GLint y, GLsizei width, GLsizei height ) { sis6326CalcViewport( ctx ); } static void sis6326DDDepthRange( GLcontext *ctx, GLclampd nearval, GLclampd farval ) { sis6326CalcViewport( ctx ); } /* ============================================================= * Miscellaneous */ static void sis6326DDLogicOpCode( GLcontext *ctx, GLenum opcode ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; if (!ctx->Color.ColorLogicOpEnabled) return; current->hwDstSet &= ~MASK_ROP2; switch (opcode) { case GL_CLEAR: current->hwDstSet |= LOP_CLEAR; break; case GL_SET: current->hwDstSet |= LOP_SET; break; case GL_COPY: current->hwDstSet |= LOP_COPY; break; case GL_COPY_INVERTED: current->hwDstSet |= LOP_COPY_INVERTED; break; case GL_NOOP: current->hwDstSet |= LOP_NOOP; break; case GL_INVERT: current->hwDstSet |= LOP_INVERT; break; case GL_AND: current->hwDstSet |= LOP_AND; break; case GL_NAND: current->hwDstSet |= LOP_NAND; break; case GL_OR: current->hwDstSet |= LOP_OR; break; case GL_NOR: current->hwDstSet |= LOP_NOR; break; case GL_XOR: current->hwDstSet |= LOP_XOR; break; case GL_EQUIV: current->hwDstSet |= LOP_EQUIV; break; case GL_AND_REVERSE: current->hwDstSet |= LOP_AND_REVERSE; break; case GL_AND_INVERTED: current->hwDstSet |= LOP_AND_INVERTED; break; case GL_OR_REVERSE: current->hwDstSet |= LOP_OR_REVERSE; break; case GL_OR_INVERTED: current->hwDstSet |= LOP_OR_INVERTED; break; } if (current->hwDstSet != prev->hwDstSet) { prev->hwDstSet = current->hwDstSet; smesa->GlobalFlag |= GFLAG_DESTSETTING; } } void sis6326DDDrawBuffer( GLcontext *ctx, GLenum mode ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; if(getenv("SIS_DRAW_FRONT")) ctx->DrawBuffer->_ColorDrawBufferMask[0] = GL_FRONT_LEFT; /* * _DrawDestMask is easier to cope with than <mode>. */ current->hwDstSet &= ~MASK_DstBufferPitch; switch ( ctx->DrawBuffer->_ColorDrawBufferMask[0] ) { case BUFFER_BIT_FRONT_LEFT: current->hwOffsetDest = smesa->front.offset; current->hwDstSet |= smesa->front.pitch; FALLBACK( smesa, SIS_FALLBACK_DRAW_BUFFER, GL_FALSE ); break; case BUFFER_BIT_BACK_LEFT: current->hwOffsetDest = smesa->back.offset; current->hwDstSet |= smesa->back.pitch; FALLBACK( smesa, SIS_FALLBACK_DRAW_BUFFER, GL_FALSE ); break; default: /* GL_NONE or GL_FRONT_AND_BACK or stereo left&right, etc */ FALLBACK( smesa, SIS_FALLBACK_DRAW_BUFFER, GL_TRUE ); return; } if (current->hwDstSet != prev->hwDstSet) { prev->hwDstSet = current->hwDstSet; smesa->GlobalFlag |= GFLAG_DESTSETTING; } if (current->hwOffsetDest != prev->hwOffsetDest) { prev->hwOffsetDest = current->hwOffsetDest; smesa->GlobalFlag |= GFLAG_DESTSETTING; } } /* ============================================================= * Polygon stipple */ /* ============================================================= * Render mode */ /* ============================================================= * State enable/disable */ static void sis6326DDEnable( GLcontext *ctx, GLenum cap, GLboolean state ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *current = &smesa->current; switch (cap) { case GL_ALPHA_TEST: if (state) current->hwCapEnable |= S_ENABLE_AlphaTest; else current->hwCapEnable &= ~S_ENABLE_AlphaTest; break; case GL_BLEND: /* TODO: */ if (state) /* if (state & !ctx->Color.ColorLogicOpEnabled) */ current->hwCapEnable |= S_ENABLE_Blend; else current->hwCapEnable &= ~S_ENABLE_Blend; break; case GL_CULL_FACE: /* XXX culling */ break; case GL_DEPTH_TEST: if (state && smesa->depth.offset != 0) current->hwCapEnable |= S_ENABLE_ZTest; else current->hwCapEnable &= ~S_ENABLE_ZTest; sis6326DDDepthMask( ctx, ctx->Depth.Mask ); break; case GL_DITHER: if (state) current->hwCapEnable |= S_ENABLE_Dither; else current->hwCapEnable &= ~S_ENABLE_Dither; break; case GL_FOG: if (state) current->hwCapEnable |= S_ENABLE_Fog; else current->hwCapEnable &= ~S_ENABLE_Fog; break; case GL_COLOR_LOGIC_OP: if (state) sis6326DDLogicOpCode( ctx, ctx->Color.LogicOp ); else sis6326DDLogicOpCode( ctx, GL_COPY ); break; case GL_SCISSOR_TEST: sis6326UpdateClipping( ctx ); break; case GL_STENCIL_TEST: if (state) { FALLBACK(smesa, SIS_FALLBACK_STENCIL, 1); } else { FALLBACK(smesa, SIS_FALLBACK_STENCIL, 0); } break; case GL_LIGHTING: case GL_COLOR_SUM_EXT: sis6326UpdateSpecular(ctx); break; } } /* ============================================================= * State initialization, management */ /* Called before beginning of rendering. */ void sis6326UpdateHWState( GLcontext *ctx ) { sisContextPtr smesa = SIS_CONTEXT(ctx); __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; if (smesa->NewGLState & _NEW_TEXTURE) sisUpdateTextureState( ctx ); if (current->hwCapEnable ^ prev->hwCapEnable) { prev->hwCapEnable = current->hwCapEnable; smesa->GlobalFlag |= GFLAG_ENABLESETTING; } if (smesa->GlobalFlag & GFLAG_RENDER_STATES) sis_update_render_state( smesa ); if (smesa->GlobalFlag & GFLAG_TEXTURE_STATES) sis_update_texture_state( smesa ); } static void sis6326DDInvalidateState( GLcontext *ctx, GLuint new_state ) { sisContextPtr smesa = SIS_CONTEXT(ctx); _swrast_InvalidateState( ctx, new_state ); _swsetup_InvalidateState( ctx, new_state ); _vbo_InvalidateState( ctx, new_state ); _tnl_InvalidateState( ctx, new_state ); smesa->NewGLState |= new_state; } /* Initialize the context's hardware state. */ void sis6326DDInitState( sisContextPtr smesa ) { __GLSiSHardware *prev = &smesa->prev; __GLSiSHardware *current = &smesa->current; GLcontext *ctx = smesa->glCtx; /* add Texture Perspective Enable */ current->hwCapEnable = S_ENABLE_TextureCache | S_ENABLE_TexturePerspective | S_ENABLE_Dither; /* Z test mode is LESS */ current->hwZ = S_ZSET_PASS_LESS | S_ZSET_FORMAT_16; if (ctx->Visual.depthBits > 0) current->hwCapEnable |= S_ENABLE_ZWrite; /* Alpha test mode is ALWAYS, alpha ref value is 0 */ current->hwAlpha = S_ASET_PASS_ALWAYS; /* ROP2 is COPYPEN */ current->hwDstSet = LOP_COPY; /* LinePattern is 0, Repeat Factor is 0 */ current->hwLinePattern = 0x00008000; /* Src blend is BLEND_ONE, Dst blend is D3DBLEND_ZERO */ current->hwDstSrcBlend = S_SBLEND_ONE | S_DBLEND_ZERO; switch (smesa->bytesPerPixel) { case 2: current->hwDstSet |= DST_FORMAT_RGB_565; break; case 4: current->hwDstSet |= DST_FORMAT_ARGB_8888; break; } smesa->depth_scale = 1.0 / (GLfloat)0xffff; smesa->clearTexCache = GL_TRUE; smesa->clearColorPattern = 0; sis6326UpdateZPattern(smesa, 1.0); sis6326UpdateCull(ctx); /* Set initial fog settings. Start and end are the same case. */ sis6326DDFogfv( ctx, GL_FOG_DENSITY, &ctx->Fog.Density ); sis6326DDFogfv( ctx, GL_FOG_END, &ctx->Fog.End ); sis6326DDFogfv( ctx, GL_FOG_MODE, NULL ); memcpy(prev, current, sizeof(__GLSiSHardware)); } /* Initialize the driver's state functions. */ void sis6326DDInitStateFuncs( GLcontext *ctx ) { ctx->Driver.UpdateState = sis6326DDInvalidateState; ctx->Driver.Clear = sis6326DDClear; ctx->Driver.ClearColor = sis6326DDClearColor; ctx->Driver.ClearDepth = sis6326DDClearDepth; ctx->Driver.AlphaFunc = sis6326DDAlphaFunc; ctx->Driver.BlendFuncSeparate = sis6326DDBlendFuncSeparate; ctx->Driver.ColorMask = sis6326DDColorMask; ctx->Driver.CullFace = sis6326DDCullFace; ctx->Driver.DepthMask = sis6326DDDepthMask; ctx->Driver.DepthFunc = sis6326DDDepthFunc; ctx->Driver.DepthRange = sis6326DDDepthRange; ctx->Driver.DrawBuffer = sis6326DDDrawBuffer; ctx->Driver.Enable = sis6326DDEnable; ctx->Driver.FrontFace = sis6326DDFrontFace; ctx->Driver.Fogfv = sis6326DDFogfv; ctx->Driver.LogicOpcode = sis6326DDLogicOpCode; ctx->Driver.Scissor = sis6326DDScissor; ctx->Driver.ShadeModel = sis6326DDShadeModel; ctx->Driver.LightModelfv = sis6326DDLightModelfv; ctx->Driver.Viewport = sis6326DDViewport; }
ZHAW-INES/rioxo-uClinux-dist
lib/mesa/src/mesa/drivers/dri/sis/sis6326_state.c
C
gpl-2.0
19,463
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_31) on Wed May 15 10:56:37 EEST 2013 --> <TITLE> ITouchHandler (AChartEngine) </TITLE> <META NAME="date" CONTENT="2013-05-15"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ITouchHandler (AChartEngine)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ITouchHandler.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../org/achartengine/GraphicalView.html" title="class in org.achartengine"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../org/achartengine/TouchHandler.html" title="class in org.achartengine"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?org/achartengine/ITouchHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ITouchHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.achartengine</FONT> <BR> Interface ITouchHandler</H2> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../org/achartengine/TouchHandler.html" title="class in org.achartengine">TouchHandler</A>, <A HREF="../../org/achartengine/TouchHandlerOld.html" title="class in org.achartengine">TouchHandlerOld</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>ITouchHandler</B></DL> </PRE> <P> The interface to be implemented by the touch handlers. <P> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../org/achartengine/ITouchHandler.html#addPanListener(org.achartengine.tools.PanListener)">addPanListener</A></B>(<A HREF="../../org/achartengine/tools/PanListener.html" title="interface in org.achartengine.tools">PanListener</A>&nbsp;listener)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adds a new pan listener.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../org/achartengine/ITouchHandler.html#addZoomListener(org.achartengine.tools.ZoomListener)">addZoomListener</A></B>(<A HREF="../../org/achartengine/tools/ZoomListener.html" title="interface in org.achartengine.tools">ZoomListener</A>&nbsp;listener)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adds a new zoom listener.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../org/achartengine/ITouchHandler.html#handleTouch(android.view.MotionEvent)">handleTouch</A></B>(android.view.MotionEvent&nbsp;event)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Handles the touch event.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../org/achartengine/ITouchHandler.html#removePanListener(org.achartengine.tools.PanListener)">removePanListener</A></B>(<A HREF="../../org/achartengine/tools/PanListener.html" title="interface in org.achartengine.tools">PanListener</A>&nbsp;listener)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Removes a pan listener.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../org/achartengine/ITouchHandler.html#removeZoomListener(org.achartengine.tools.ZoomListener)">removeZoomListener</A></B>(<A HREF="../../org/achartengine/tools/ZoomListener.html" title="interface in org.achartengine.tools">ZoomListener</A>&nbsp;listener)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Removes a zoom listener.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="handleTouch(android.view.MotionEvent)"><!-- --></A><H3> handleTouch</H3> <PRE> boolean <B>handleTouch</B>(android.view.MotionEvent&nbsp;event)</PRE> <DL> <DD>Handles the touch event. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>event</CODE> - the touch event <DT><B>Returns:</B><DD>true if the event was handled</DL> </DD> </DL> <HR> <A NAME="addZoomListener(org.achartengine.tools.ZoomListener)"><!-- --></A><H3> addZoomListener</H3> <PRE> void <B>addZoomListener</B>(<A HREF="../../org/achartengine/tools/ZoomListener.html" title="interface in org.achartengine.tools">ZoomListener</A>&nbsp;listener)</PRE> <DL> <DD>Adds a new zoom listener. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>listener</CODE> - zoom listener</DL> </DD> </DL> <HR> <A NAME="removeZoomListener(org.achartengine.tools.ZoomListener)"><!-- --></A><H3> removeZoomListener</H3> <PRE> void <B>removeZoomListener</B>(<A HREF="../../org/achartengine/tools/ZoomListener.html" title="interface in org.achartengine.tools">ZoomListener</A>&nbsp;listener)</PRE> <DL> <DD>Removes a zoom listener. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>listener</CODE> - zoom listener</DL> </DD> </DL> <HR> <A NAME="addPanListener(org.achartengine.tools.PanListener)"><!-- --></A><H3> addPanListener</H3> <PRE> void <B>addPanListener</B>(<A HREF="../../org/achartengine/tools/PanListener.html" title="interface in org.achartengine.tools">PanListener</A>&nbsp;listener)</PRE> <DL> <DD>Adds a new pan listener. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>listener</CODE> - pan listener</DL> </DD> </DL> <HR> <A NAME="removePanListener(org.achartengine.tools.PanListener)"><!-- --></A><H3> removePanListener</H3> <PRE> void <B>removePanListener</B>(<A HREF="../../org/achartengine/tools/PanListener.html" title="interface in org.achartengine.tools">PanListener</A>&nbsp;listener)</PRE> <DL> <DD>Removes a pan listener. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>listener</CODE> - pan listener</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ITouchHandler.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../org/achartengine/GraphicalView.html" title="class in org.achartengine"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../org/achartengine/TouchHandler.html" title="class in org.achartengine"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?org/achartengine/ITouchHandler.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ITouchHandler.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &#169; 2009 - 2011 4ViewSoft. All Rights Reserved.</i> </BODY> </HTML>
tfwalther/climbingguide
libs_archive/achartengine-1.1.0-javadocs/org/achartengine/ITouchHandler.html
HTML
gpl-2.0
12,528
module Admin class JobsController < AdminController def initialize(repository = Delayed::Job) @repository = repository super() end def index @jobs = @repository.order(created_at: :desc) end def show @job = @repository.find(params[:id]) end def update @job = @repository.find(params[:id]) @job.invoke_job redirect_to admin_jobs_path end def destroy @job = @repository.find(params[:id]) @job.destroy redirect_to admin_jobs_path end end end
mokhan/cakeside
app/controllers/admin/jobs_controller.rb
Ruby
gpl-2.0
546
/** Copyright (C) SYSTAP, LLC 2006-2012. 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.bigdata.rdf.graph.analytics; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.openrdf.model.Value; import org.openrdf.sail.SailConnection; import com.bigdata.rdf.graph.IGASContext; import com.bigdata.rdf.graph.IGASEngine; import com.bigdata.rdf.graph.IGASState; import com.bigdata.rdf.graph.IGASStats; import com.bigdata.rdf.graph.IGraphAccessor; import com.bigdata.rdf.graph.analytics.CC.VS; import com.bigdata.rdf.graph.impl.sail.AbstractSailGraphTestCase; /** * Test class for Breadth First Search (BFS) traversal. * * @see BFS * * @author <a href="mailto:[email protected]">Bryan Thompson</a> */ public class TestCC extends AbstractSailGraphTestCase { public TestCC() { } public TestCC(String name) { super(name); } public void testCC() throws Exception { /* * Load two graphs. These graphs are not connected with one another (no * shared vertices). This means that each graph will be its own * connected component (all vertices in each source graph are * connected within that source graph). */ final SmallGraphProblem p1 = setupSmallGraphProblem(); final SSSPGraphProblem p2 = setupSSSPGraphProblem(); final IGASEngine gasEngine = getGraphFixture() .newGASEngine(1/* nthreads */); try { final SailConnection cxn = getGraphFixture().getSail() .getConnection(); try { final IGraphAccessor graphAccessor = getGraphFixture() .newGraphAccessor(cxn); final CC gasProgram = new CC(); final IGASContext<CC.VS, CC.ES, Value> gasContext = gasEngine .newGASContext(graphAccessor, gasProgram); final IGASState<CC.VS, CC.ES, Value> gasState = gasContext .getGASState(); // Converge. final IGASStats stats = gasContext.call(); if(log.isInfoEnabled()) log.info(stats); /* * Check the #of connected components that are self-reported and * the #of vertices in each connected component. This helps to * detect vertices that should have been visited but were not * due to the initial frontier. E.g., "DC" will not be reported * as a connected component of size (1) unless it gets into the * initial frontier (it has no edges, only an attribute). */ final Map<Value, AtomicInteger> labels = gasProgram .getConnectedComponents(gasState); // the size of the connected component for this vertex. { final VS valueState = gasState.getState(p1.getFoafPerson()); final Value label = valueState != null?valueState.getLabel():null; assertEquals(4, labels.get(label).get()); } // the size of the connected component for this vertex. { final VS valueState = gasState.getState(p2.get_v1()); final Value label = valueState != null?valueState.getLabel():null; final AtomicInteger ai = labels.get(label); final int count = ai!=null?ai.get():-1; assertEquals(5, count); } if (false) { /* * The size of the connected component for this vertex. * * Note: The vertex sampling code ignores self-loops and * ignores vertices that do not have ANY edges. Thus "DC" is * not put into the frontier and is not visited. */ final Value label = gasState.getState(p1.getDC()) .getLabel(); assertNotNull(label); /* * If DC was not put into the initial frontier, then it will * be missing here. */ assertNotNull(labels.get(label)); assertEquals(1, labels.get(label).get()); } // the #of connected components. assertEquals(2, labels.size()); /* * Most vertices in problem1 have the same label (the exception * is DC, which is it its own connected component). */ Value label1 = null; for (Value v : p1.getVertices()) { final CC.VS vs = gasState.getState(v); if (log.isInfoEnabled()) log.info("v=" + v + ", label=" + vs.getLabel()); if(v.equals(p1.getDC())) { /* * This vertex is in its own connected component and is * therefore labeled by itself. */ assertEquals("vertex=" + v, v, vs.getLabel()); continue; } if (label1 == null) { label1 = vs.getLabel(); assertNotNull(label1); } assertEquals("vertex=" + v, label1, vs.getLabel()); } // All vertices in problem2 have the same label. Value label2 = null; for (Value v : p2.getVertices()) { final CC.VS vs = gasState.getState(v); if (log.isInfoEnabled()) log.info("v=" + v + ", label=" + vs.getLabel()); if (label2 == null) { label2 = vs.getLabel(); assertNotNull(label2); } assertEquals("vertex=" + v, label2, vs.getLabel()); } // The labels for the two connected components are distinct. assertNotSame(label1, label2); } finally { try { cxn.rollback(); } finally { cxn.close(); } } } finally { gasEngine.shutdownNow(); } } }
blazegraph/database
bigdata-gas/src/test/java/com/bigdata/rdf/graph/analytics/TestCC.java
Java
gpl-2.0
7,408
/* * include/linux/dvs_suite.h * * Copyright (C) 2010 Sookyoung Kim <[email protected]> */ #ifndef _LINUX_DVS_SUITE_H #define _LINUX_DVS_SUITE_H /*************************************************************************** * Headers ***************************************************************************/ #include <asm/current.h> /* For current macro */ #include <asm/div64.h> /* For division */ #include <linux/mm.h> #include <linux/vmalloc.h> #include <linux/spinlock.h> #include <linux/errno.h> /* For EAGAIN and EWOULDBLOCK */ #include <linux/kernel.h> /* For printk */ #include <linux/sched.h> /* For struct task_struct and wait_event* macros */ #include <linux/slab.h> /* For kmalloc and kfree */ #include <linux/string.h> /* To use string functions */ #include <linux/times.h> /* For struct timeval and do_gettimeofday */ #include <linux/cred.h> /* To get uid */ #include <linux/workqueue.h> #include <plat/omap_device.h> #include <plat/omap-pm.h> /* * Including resource34xx.h here causes build error. * This is the reason why we moved ds_update_cpu_op() from here to resource34xx.c. */ //#include "../../arch/arm/mach-omap2/resource34xx.h" /* For set_opp() */ //#include "../../../system/core/include/private/android_filesystem_config.h" /* For AID_* */ /*************************************************************************** * Definitions ***************************************************************************/ /* The 4 operating points (CPU_OP) supported by Hub (LU3000)'s OMAP3630 CPU_OP 0: (1000 MHz, 1.35V), Scaling factor 1 = 0x1000 in fixed point number CPU_OP 1: ( 800 MHz, 1.26V), Scaling factor 0.8 = 0xccc CPU_OP 2: ( 600 MHz, 1.10V), Scaling factor 0.6 = 0x999 CPU_OP 3: ( 300 MHz, 0.93V), Scaling factor 0.3 = 0x4cc set_opp(&vdd1_opp, VDD1_OPP4) set_opp(&vdd1_opp, VDD1_OPP3) set_opp(&vdd1_opp, VDD1_OPP2) set_opp(&vdd1_opp, VDD1_OPP1) */ /* The number of CPU_OPs to use */ #define DS_CPU_OP_LIMIT 4 /* To cope with touch and key inputs */ #define DS_TOUCH_TIMEOUT_COUNT_MAX 7 /* The CPU_OP indices */ #define DS_CPU_OP_INDEX_0 1000000000 #define DS_CPU_OP_INDEX_1 800000000 #define DS_CPU_OP_INDEX_2 600000000 #define DS_CPU_OP_INDEX_3 300000000 #define DS_CPU_OP_INDEX_MAX DS_CPU_OP_INDEX_0 #define DS_CPU_OP_INDEX_N2MAX DS_CPU_OP_INDEX_1 #define DS_CPU_OP_INDEX_N2MIN DS_CPU_OP_INDEX_2 #define DS_CPU_OP_INDEX_MIN DS_CPU_OP_INDEX_3 /* The scaling factors */ /* These values mean the U(20,12) fixed point numbers' 12bit fractions. * In this format, * ------ Decimal part ------ -- Fraction -- * 1 = 0000 0000 0000 0000 0001 0000 0000 0000 = 0x00001000 * 0.5 = 0000 0000 0000 0000 0000 1000 0000 0000 = 0x00000800 * 0.25 = 0000 0000 0000 0000 0000 0100 0000 0000 = 0x00000400 * 0.125 = 0000 0000 0000 0000 0000 0010 0000 0000 = 0x00000200 * 0.0625 = 0000 0000 0000 0000 0000 0001 0000 0000 = 0x00000100 * 0.03125 = 0000 0000 0000 0000 0000 0000 1000 0000 = 0x00000080 * 0.015625 = 0000 0000 0000 0000 0000 0000 0100 0000 = 0x00000040 * 0.0078125 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000020 * 0.00390625 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000010 * 0.0019553125 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000008 * 0.0009765625 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000004 * 0.00048828125 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000002 * 0.000244140625 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x00000001 * * Ex) * 0.75 = 0.5 + 0.25 = 0000 0000 0000 0000 0000 1100 0000 0000 = 0x00000c00 */ #define DS_CPU_OP_SF_0 0x1000 // 1 #define DS_CPU_OP_SF_1 0xccc // 0.8 #define DS_CPU_OP_SF_2 0x999 // 0.6 #define DS_CPU_OP_SF_3 0x4cc // 0.3 /* The conversion macros between index and mhz/mv */ #if 0 // To do. The following is for Pentium M #define DS_MHZMV2INDEX(mhz, mv) ((((mhz)/100)<<8)|(((mv)-700)/16)) #endif /* WARNING! Not precise! */ #define DS_INDEX2MHZ(index) \ ((index)==1000000000 ? 1000 : \ ((index)==800000000 ? 800 : \ ((index)==600000000 ? 600 : 300))) #define DS_INDEX2MHZPRECISE(index) \ ((index)==1000000000 ? 1000 : \ ((index)==800000000 ? 800 : \ ((index)==600000000 ? 600 : 300))) #if 0 // To do. The following is for Pentium M #define DS_INDEX2MV(index) (((int)(index)&0xff)*16+700) #endif #define DS_INDEX2NR(index) \ ((index)==1000000000 ? 0 : \ ((index)==800000000 ? 1 : \ ((index)==600000000 ? 2 : 3))) #define DS_INDEX2SF(index) \ ((index)==1000000000 ? 0x1000 : \ ((index)==800000000 ? 0xccc : \ ((index)==600000000 ? 0x999 : 0x4cc))) /* For ds_status.cpu_mode */ #define DS_CPU_MODE_IDLE 0 #define DS_CPU_MODE_TASK 1 #define DS_CPU_MODE_SCHEDULE 2 #define DS_CPU_MODE_DVS_SUITE 4 /* For ds_configuration.sched_scheme */ #define DS_SCHED_LINUX_NATIVE 0 #define DS_SCHED_GPSCHED 1 /* For ds_configuration.dvs_scheme */ // For now, dvs_scheme of Swift is fixed to DS_DVS_GPSCHEDVS. #define DS_DVS_NO_DVS 0 #define DS_DVS_MIN 1 #define DS_DVS_GPSCHEDVS 2 #define DS_DVS_MANUAL 99 /* For do_dvs_suite() */ #define DS_ENTRY_RET_FROM_SYSTEM_CALL 0 #define DS_ENTRY_SWITCH_TO 1 /* The macro to convert an unsigned long type to U(20,12) fixed point. Result is U(20,12) fixed point. */ #define DS_ULONG2FP12(x) ((x)<<12) /* The macro to extract the integer part of the given U(20,12) fixed point number. Result is unsigned long. */ #define DS_GETFP12INT(x) (((x)&0xfffff000)>>12) /* The macro to extract the fraction part of the given U(20,12) fixed point number. Result is U(20,12) fixed point. */ #define DS_GETFP12FRA(x) ((x)&0x00000fff) /* Definitions for compare44bits() */ #define DS_LARGER 1 #define DS_EQUAL 0 #define DS_SMALLER -1 /* A representative HRT task in a Smartphone is voice call. * To do. Implement it in the future. For this time, we ignore such a HRT task. */ #define DS_CONDITION_FOR_HRT 0 /* Process static priority */ #define DS_LINUX_DEFAULT_STATIC_PRIO 120 //#define DS_HRT_STATIC_PRIO 100 // 100 nice -20 #define DS_HRT_STATIC_PRIO 105 // 100 nice -15 #define DS_DBSRT_STATIC_PRIO 110 // 110 nice -10 #define DS_RBSRT_STATIC_PRIO 115 // 115 nice -5 #define DS_NRT_STATIC_PRIO 120 // 120 nice 0 #define DS_IDLE_PRIO 140 //#define DS_HRT_NICE -20 // -20 #define DS_HRT_NICE -15 // -15 #define DS_DBSRT_NICE -10 // -10 #define DS_RBSRT_NICE -5 // -5 #define DS_NRT_NICE 0 // 0 /* Process rt_priority. p->prio = p->normal_prio = 99 - p->rt_priority for SCHED_RR tasks. p->prio = p->normal_prio = p->static_prio for SCHED_NORMAL tasks. */ #define DS_HRT_RR_PRIO 29 // p->prio = 70 #define DS_DBSRT_RR_PRIO 19 // p->prio = 80 #define DS_RBSRT_RR_PRIO 9 // p->prio = 90 /* Scheduler type. */ #define DS_SCHED_NORMAL 0 #define DS_SCHED_RR 1 /* Process type. */ #define DS_HRT_TASK 1 // HRT #define DS_SRT_UI_SERVER_TASK 2 // DBSRT #define DS_SRT_UI_CLIENT_TASK 3 // DBSRT #define DS_SRT_KERNEL_THREAD 4 // RBSRT #define DS_SRT_DAEMON_TASK 5 // RBSRT #define DS_NRT_TASK 6 // NRT #define DS_MIN_RT_SCHED_TYPE DS_SRT_UI_CLIENT_TASK /* If a DS_SRT_UI_CLIENT_TASK does not interact with DS_SRT_UI_SERVER_TASK * for over DS_SRT_UI_IPC_TIMEOUT, we re-define its type. * The new type depends on conditions. */ #define DS_SRT_UI_IPC_NO 3 // #define DS_SRT_UI_IPC_TIMEOUT 500000 // 500 msec. It should not be larger than 1sec. #define DS_TOUCH_TIMEOUT 980000 // 980 msec. Don't touch this. LG standard. /* The maximum allowable number of PID. 0 ~ 32767. */ #define DS_PID_LIMIT 32768 /* Definitions for AIDVS */ /* DS_AIDVS_SPEEDUP_THRESHOLD and DS_AIDVS_SPEEDUP_INTERVAL * should be less than 1000000 */ #define DS_AIDVS_MOVING_AVG_WEIGHT 3 /* 3 */ #define DS_AIDVS_INTERVALS_IN_AN_WINDOW 100 /* 100 intervals in an window */ #define DS_AIDVS_SPEEDUP_THRESHOLD 100000 /* 100 msec in fse */ #define DS_AIDVS_SPEEDUP_INTERVAL 100000 /* 100 msec in fse */ /* Definitions for GPScheDVS */ /* Following THRESHOLD and INTERVAL values should be less than 1000000. */ #define DS_GPSCHEDVS_L0_INTERVALS_IN_AN_WINDOW 100 /* Max. intervals in an window */ #define DS_GPSCHEDVS_L0_MIN_WINDOW_LENGTH 10000 /* 10 msec in elapsed */ #define DS_GPSCHEDVS_L0_SPEEDUP_THRESHOLD 3000 /* 3 msec in fse */ #define DS_GPSCHEDVS_L0_SPEEDUP_INTERVAL 3000 /* 3 msec in fse */ #define DS_GPSCHEDVS_L1_INTERVALS_IN_AN_WINDOW 100 /* Max. intervals in an window */ #define DS_GPSCHEDVS_L1_MIN_WINDOW_LENGTH 30000 /* 25 msec in elapsed */ #define DS_GPSCHEDVS_L1_SPEEDUP_THRESHOLD 5000 /* 5 msec in fse */ #define DS_GPSCHEDVS_L1_SPEEDUP_INTERVAL 5000 /* 5 msec in fse */ #define DS_GPSCHEDVS_L2_INTERVALS_IN_AN_WINDOW 100 /* Max. intervals in an window */ #define DS_GPSCHEDVS_L2_MIN_WINDOW_LENGTH 40000 /* 50 msec in elapsed */ #define DS_GPSCHEDVS_L2_SPEEDUP_THRESHOLD 50000 /* 10 msec in fse */ #define DS_GPSCHEDVS_L2_SPEEDUP_INTERVAL 50000 /* 10 msec in fse */ #define DS_GPSCHEDVS_L3_INTERVALS_IN_AN_WINDOW 100 /* Max. intervals in an window */ #define DS_GPSCHEDVS_L3_MIN_WINDOW_LENGTH 80000 /* 100 msec in elapsed */ #define DS_GPSCHEDVS_L3_SPEEDUP_THRESHOLD 100000 /* 20 msec in fse */ #define DS_GPSCHEDVS_L3_SPEEDUP_INTERVAL 100000 /* 20 msec in fse */ #define DS_MIN_CPU_OP_UPDATE_INTERVAL_U 10000 /* 10 msec */ #define DS_MIN_CPU_OP_UPDATE_INTERVAL_D 10000 /* 10 msec */ #define DS_INIT_DELAY_SEC 20 /* 20 seconds */ #define DS_POST_EARLY_SUSPEND_TIMEOUT_USEC 2000000 /* 2 seconds */ /*************************************************************************** * Variables and data structures ***************************************************************************/ extern struct timeval ds_timeval; typedef struct dvs_suite_configuration DS_CONF; typedef struct dvs_suite_status DS_STAT; typedef struct dvs_suite_counter DS_COUNT; typedef struct dvs_suite_parameter DS_PARAM; typedef struct ds_aidvs_interval_structure DS_AIDVS_INTERVAL_STRUCT; typedef struct ds_aidvs_status_structure DS_AIDVS_STAT_STRUCT; typedef struct ds_aidvs_l3_status_structure DS_AIDVS_L3_STAT_STRUCT; typedef struct ds_aidvs_l2_status_structure DS_AIDVS_L2_STAT_STRUCT; typedef struct ds_aidvs_l1_status_structure DS_AIDVS_L1_STAT_STRUCT; typedef struct ds_aidvs_l0_status_structure DS_AIDVS_L0_STAT_STRUCT; typedef struct ds_gpschedvs_status_structure DS_GPSCHEDVS_STAT_STRUCT; ////////////////////////////////////////////////////////////////////////////////////// /* The dvs_suite configuration structure. All the fields of this structure are adjusted by the Loadable Kernel Module (LKM) dvs_suite_mod. Field dvs_scheme tells the DVS scheme to force. Possible values are as follows: 0: Constantly forcing the maximum CPU_OP., i.e., CPU_OP0. 1: Constantly forcing the minimum CPU_OP., i.e., CPU_OP4 for Swift 2: AIDVS 3: GPScheDVS 99: MANUAL Field on_dvs tells whether to force the chosen DVS scheme or not. If on_dvs is set, the DVS scheme indicated by field dvs_scheme is forced. If on_dvs is reset, the maximum CPU_OP is forced as default. */ struct dvs_suite_configuration { /* For scheduling scheme */ int sched_scheme; /* For dvs_suite */ int dvs_scheme; int on_dvs; /* For DVS schemes */ /* GPSDVS and GPScheDVS strategies 0: System energy centric strategy. 1: CPU power centric strategy. */ int gpsdvs_strategy; int gpschedvs_strategy; int aidvs_interval_window_size; unsigned long aidvs_speedup_threshold; unsigned long aidvs_speedup_interval; }; extern DS_CONF ds_configuration; //////////////////////////////////////////////////////////////////////////////////////////// /* The current system status. Field ds_initialized indicates that whether dvs_suite is initialized or not. The initialization process sets ds_status.cpu_op_index to what the CPU is currently running at. Field flag_time_base_initialized indicates whether tv_usec_base were initialized or not. Field tv_usec_base holds the last read ds_timeval.tv_usec value. We use do_gettimeofday() to get the elapsed real time. Field cpu_op_index indicates the current CPU_OP index. Field cpu_op_index_sf indicates the current CPU_OP scalinf factor. Field cpu_op_index_nr indicates the integer number corresponding to the current CPU_OP index. They are 0 for CPU_OP_INDEX_0, 1 for CPU_OP_INDEX_1, and so forth. Field cpu_op_mhz indicates the MHz value in fixed point format corresponding to the current CPU_OP index. Field cpu_mode indicates the current cpu mode among that cpu is idle (0: DS_CPU_MODE_IDLE), cpu is busy while running a task (1: DS_CPU_MODE_TASK), cpu is busy while performing schedule() (2: DS_CPU_MODE_SCHEDULE), and cpu is busy while running dvs_suite related codes (4: DS_CPU_MODE_DVS_SUITE). Fields current_dvs_scheme and dvs_is_on hold the current state of the corresponding fields in ds_configuration and are used to check if the corresponding feature should be initialized or not. Field flag_just_mm_interacted indicates the fact that the current task just made an interaction with media server for a multimedia transaction. Field flag_just_uie_interacted indicates the fact that the current task just made an interaction with system server for an user input event transaction. Field ms_pid is the pid of media server. Field ss_pid is the pid of system server. Field *pti[DS_PID_LIMIT] is the array holding the pointers to per task information data structures. The index for pti is the PID of tasks. This data structure is used to trace the type of tasks. */ struct dvs_suite_status { int flag_run_dvs; int ds_initialized; int flag_time_base_initialized; unsigned long tv_sec_curr; unsigned long tv_usec_curr; unsigned long tv_sec_base; unsigned long tv_usec_base; unsigned int cpu_op_index; unsigned int cpu_op_sf; int cpu_op_index_nr; int cpu_op_mhz; int cpu_mode; int flag_update_cpu_op; unsigned int target_cpu_op_index; unsigned long cpu_op_last_update_sec; unsigned long cpu_op_last_update_usec; int current_dvs_scheme; int scheduler[DS_PID_LIMIT]; int type[DS_PID_LIMIT]; int type_fixed[DS_PID_LIMIT]; int type_need_to_be_changed[DS_PID_LIMIT]; int tgid[DS_PID_LIMIT]; char tg_owner_comm[DS_PID_LIMIT][16]; int tgid_type_changed[DS_PID_LIMIT]; int tgid_type_change_causer[DS_PID_LIMIT]; unsigned long ipc_timeout_sec[DS_PID_LIMIT]; unsigned long ipc_timeout_usec[DS_PID_LIMIT]; int flag_touch_timeout_count; unsigned long touch_timeout_sec; unsigned long touch_timeout_usec; int flag_mutex_lock_on_clock_state; int mutex_lock_on_clock_state_cnt; int flag_correct_cpu_op_update_path; int flag_post_early_suspend; unsigned long post_early_suspend_sec; unsigned long post_early_suspend_usec; int flag_do_post_early_suspend; unsigned long mpu_min_freq_to_lock; unsigned long l3_min_freq_to_lock; unsigned long iva_min_freq_to_lock; }; extern DS_STAT ds_status; //////////////////////////////////////////////////////////////////////////////////////////// /* The data structure holding various counters. The first type of counters are time counters which holds the fractions of busy (= task + context switch + dvs suite, i.e. the overhead) and idle time at each CPU_OP. Additionally, the full speed equivalent sec and usec values are calculated and stored. fp12_*_fse_fraction holds the fraction smaller than 1 usec in U(20,12) fixed point format. elapsed_sec and elapsed_usec hold the total elapsed time (wall clock time) since the system was booted. The second type of counters hold the occurrence number of certain events such as CPU_OP transitions, schedules, and total number of system calls and interrupts. */ struct dvs_suite_counter { unsigned long elapsed_sec; unsigned long elapsed_usec; #if 0 unsigned long idle_sec[DS_CPU_OP_LIMIT]; unsigned long idle_usec[DS_CPU_OP_LIMIT]; unsigned long idle_total_sec; unsigned long idle_total_usec; unsigned long busy_sec[DS_CPU_OP_LIMIT]; unsigned long busy_usec[DS_CPU_OP_LIMIT]; #endif unsigned long busy_total_sec; unsigned long busy_total_usec; unsigned long busy_fse_sec; unsigned long busy_fse_usec; unsigned long busy_fse_usec_fra_fp12; #if 0 unsigned long busy_task_sec[DS_CPU_OP_LIMIT]; unsigned long busy_task_usec[DS_CPU_OP_LIMIT]; unsigned long busy_task_total_sec; unsigned long busy_task_total_usec; unsigned long busy_task_fse_sec; unsigned long busy_task_fse_usec; unsigned long busy_task_fse_usec_fra_fp12; /* The busy time caused by HRT tasks */ unsigned long busy_hrt_task_sec; unsigned long busy_hrt_task_usec; unsigned long busy_hrt_task_fse_sec; unsigned long busy_hrt_task_fse_usec; unsigned long busy_hrt_task_fse_usec_fra_fp12; /* The busy time caused by DBSRT tasks */ unsigned long busy_dbsrt_task_sec; unsigned long busy_dbsrt_task_usec; unsigned long busy_dbsrt_task_fse_sec; unsigned long busy_dbsrt_task_fse_usec; unsigned long busy_dbsrt_task_fse_usec_fra_fp12; /* The busy time caused by RBSRT tasks */ unsigned long busy_rbsrt_task_sec; unsigned long busy_rbsrt_task_usec; unsigned long busy_rbsrt_task_fse_sec; unsigned long busy_rbsrt_task_fse_usec; unsigned long busy_rbsrt_task_fse_usec_fra_fp12; /* The busy time caused by NRT tasks */ unsigned long busy_nrt_task_sec; unsigned long busy_nrt_task_usec; unsigned long busy_nrt_task_fse_sec; unsigned long busy_nrt_task_fse_usec; unsigned long busy_nrt_task_fse_usec_fra_fp12; unsigned long busy_schedule_sec[DS_CPU_OP_LIMIT]; unsigned long busy_schedule_usec[DS_CPU_OP_LIMIT]; unsigned long busy_schedule_total_sec; unsigned long busy_schedule_total_usec; unsigned long busy_schedule_fse_sec; unsigned long busy_schedule_fse_usec; unsigned long busy_schedule_fse_usec_fra_fp12; unsigned long busy_dvs_suite_sec[DS_CPU_OP_LIMIT]; unsigned long busy_dvs_suite_usec[DS_CPU_OP_LIMIT]; unsigned long busy_dvs_suite_total_sec; unsigned long busy_dvs_suite_total_usec; unsigned long busy_dvs_suite_fse_sec; unsigned long busy_dvs_suite_fse_usec; unsigned long busy_dvs_suite_fse_usec_fra_fp12; unsigned long ds_cpu_op_adjustment_no; unsigned long schedule_no; unsigned long ret_from_system_call_no; #endif }; extern DS_COUNT ds_counter; /* The parameters for do_dvs_suite(). Field entry_type indicates where do_dvs_suite() was called. entry_type DS_ENTRY_RET_FROM_SYSTEM_CALL indicates that do_dvs_suite() was called at the beginning of ENTRY(ret_from_system_call) defined in linux/arch/i386/kernel/entry.S. entry_type DS_ENTRY_SWITCH_TO indicates that do_dvs_suite() was called at the end of __switch_to() macro defined in linux/arch/i386/kernel/process.c. Fields prev_p and next_p are set only before calling do_dvs_suite() in __switch_to() macro. When calling do_dvs_suite() from ENTRY(ret_from_system_call), these fields should be ignored. */ struct dvs_suite_parameter { int entry_type; struct task_struct *prev_p; struct task_struct *next_p; }; extern DS_PARAM ds_parameter; //////////////////////////////////////////////////////////////////////////////////////////// /* * Variables for AIDVS. */ struct ds_aidvs_interval_structure { unsigned long time_usec_interval; unsigned long time_usec_work_fse; unsigned long time_usec_work; // struct ds_aidvs_interval_structure *next; }; struct ds_aidvs_status_structure { int base_initialized; int flag_in_busy_half; unsigned long time_usec_interval; unsigned long time_usec_interval_inc_base; unsigned long time_sec_interval_inc_base; unsigned long time_usec_work_fse; unsigned long time_usec_work_fse_inc_base; unsigned long time_usec_work_fse_lasting; unsigned long time_usec_work; unsigned long time_usec_work_inc_base; unsigned long time_usec_work_lasting; DS_AIDVS_INTERVAL_STRUCT interval_window_array[DS_AIDVS_INTERVALS_IN_AN_WINDOW]; int interval_window_index; // DS_AIDVS_INTERVAL_STRUCT *interval_window_head; // DS_AIDVS_INTERVAL_STRUCT *interval_window_tail; unsigned long time_usec_interval_in_window; unsigned long time_usec_work_fse_in_window; unsigned long time_usec_work_in_window; int consecutive_speedup_count; unsigned long utilization_int_ulong; unsigned long utilization_fra_fp12; unsigned long time_usec_util_calc_base; unsigned long time_sec_util_calc_base; unsigned int cpu_op_index; }; extern DS_AIDVS_STAT_STRUCT ds_aidvs_status; /* * Variables for GPScheDVS. */ struct ds_gpschedvs_status_structure { int current_strategy; /* Workload includes HRT + DBSRT + RBSRT + NRT tasks, i.e., all tasks. */ DS_AIDVS_STAT_STRUCT aidvs_l3_status; /* Workload includes HRT + DBSRT + RBSRT tasks */ DS_AIDVS_STAT_STRUCT aidvs_l2_status; /* Workload includes HRT + DBSRT tasks */ DS_AIDVS_STAT_STRUCT aidvs_l1_status; /* Workload includes HRT tasks */ DS_AIDVS_STAT_STRUCT aidvs_l0_status; }; extern DS_GPSCHEDVS_STAT_STRUCT ds_gpschedvs_status; //////////////////////////////////////////////////////////////////////////////////////////// /* * Other global vairables */ /*************************************************************************** * Function definitions ***************************************************************************/ extern void ds_fpmul12(unsigned long, unsigned long, unsigned long *); extern void ds_fpdiv12(unsigned long, unsigned long, unsigned long *, unsigned long *); extern void ds_div32(unsigned long, unsigned long, unsigned long *, unsigned long *); extern int ds_find_first1_in_integer_part(unsigned long); extern int ds_find_first1_in_fraction_part(unsigned long); extern int ds_compare45bits(int, unsigned long, unsigned long, int, unsigned long, unsigned long); extern int ds_shiftleft44bits(int, unsigned long, unsigned long, int, int *, unsigned long *, unsigned long *); extern int ds_subtract44bits(int, unsigned long, unsigned long, int, unsigned long, unsigned long, int *, unsigned long *, unsigned long *); extern int ds_fpmul(unsigned long, unsigned long, unsigned long, unsigned long, unsigned long *, unsigned long *); extern int ds_fpdiv(unsigned long, unsigned long, unsigned long, unsigned long, unsigned long *, unsigned long *); extern unsigned int ds_get_next_high_cpu_op_index(unsigned long, unsigned long); extern unsigned int ds_get_next_low_cpu_op_index(unsigned long, unsigned long); /* * The functions for each DVS scheme. */ /* AIDVS */ extern int ds_do_dvs_aidvs(unsigned int *, DS_AIDVS_STAT_STRUCT *, int, int, unsigned long, unsigned long, unsigned long); /* GPScheDVS */ extern int ds_do_dvs_gpschedvs(unsigned int *); /* * Wrappers to be used in the existing kernel codes * to call the main dvs suite function. */ extern asmlinkage void ld_update_cpu_op(void); extern int ld_initialize_dvs_suite(int); extern int ld_update_time_counter(void); extern int ld_update_priority_normal(struct task_struct *); extern void ld_do_dvs_suite(void); /* * The main dvs suite function. */ extern int ds_initialize_dvs_suite(int); extern int ds_initialize_iaqos_trace(void); extern int ds_initialize_cmqos_trace(void); extern int ds_initialize_job_trace(void); extern int ds_initialize_dvs_scheme(int); extern int ds_update_time_counter(void); extern int ds_update_priority_normal(struct task_struct *); extern int ds_update_priority_rt(struct task_struct *); //extern void ds_update_cpu_op(void); extern asmlinkage void ds_update_cpu_op(void); extern int ds_detect_task_type(void); extern void do_dvs_suite(void); #endif /* !(_LINUX_DVS_SUITE_H) */
playfulgod/Kernel_AS85-LG-Ignite
include/linux/dvs_suite.h
C
gpl-2.0
23,525
/* * Copyright (C) 2016 robert * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pl.rcebula.code_generation.final_steps; import java.util.ArrayList; import java.util.List; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IField; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IntermediateCode; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.Line; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.StringField; /** * * @author robert */ public class AddInformationsAboutModules { private final IntermediateCode ic; private final List<String> modulesName; public AddInformationsAboutModules(IntermediateCode ic, List<String> modulesName) { this.ic = ic; this.modulesName = modulesName; analyse(); } private void analyse() { // tworzymy pola List<IField> fields = new ArrayList<>(); for (String m : modulesName) { IField f = new StringField(m); fields.add(f); } // wstawiamy pustą linię na początek ic.insertLine(Line.generateEmptyStringLine(), 0); // tworzymy linię i wstawiamy na początek Line line = new Line(fields); ic.insertLine(line, 0); } }
bercik/BIO
impl/bioc/src/pl/rcebula/code_generation/final_steps/AddInformationsAboutModules.java
Java
gpl-2.0
1,977
/***************************************************************************** Copyright (c) 1996, 2010, Innobase Oy. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *****************************************************************************/ /**************************************************//** @file dict/dict0load.c Loads to the memory cache database object definitions from dictionary tables Created 4/24/1996 Heikki Tuuri *******************************************************/ #include "dict0load.h" #include "mysql_version.h" #ifdef UNIV_NONINL #include "dict0load.ic" #endif #include "btr0pcur.h" #include "btr0btr.h" #include "page0page.h" #include "mach0data.h" #include "dict0dict.h" #include "dict0boot.h" #include "rem0cmp.h" #include "srv0start.h" #include "srv0srv.h" #include "ha_prototypes.h" /* innobase_casedn_str() */ /** Following are six InnoDB system tables */ static const char* SYSTEM_TABLE_NAME[] = { "SYS_TABLES", "SYS_INDEXES", "SYS_COLUMNS", "SYS_FIELDS", "SYS_FOREIGN", "SYS_FOREIGN_COLS" }; /****************************************************************//** Compare the name of an index column. @return TRUE if the i'th column of index is 'name'. */ static ibool name_of_col_is( /*===========*/ const dict_table_t* table, /*!< in: table */ const dict_index_t* index, /*!< in: index */ ulint i, /*!< in: index field offset */ const char* name) /*!< in: name to compare to */ { ulint tmp = dict_col_get_no(dict_field_get_col( dict_index_get_nth_field( index, i))); return(strcmp(name, dict_table_get_col_name(table, tmp)) == 0); } /********************************************************************//** Finds the first table name in the given database. @return own: table name, NULL if does not exist; the caller must free the memory in the string! */ UNIV_INTERN char* dict_get_first_table_name_in_db( /*============================*/ const char* name) /*!< in: database name which ends in '/' */ { dict_table_t* sys_tables; btr_pcur_t pcur; dict_index_t* sys_index; dtuple_t* tuple; mem_heap_t* heap; dfield_t* dfield; const rec_t* rec; const byte* field; ulint len; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); heap = mem_heap_create(1000); mtr_start(&mtr); sys_tables = dict_table_get_low("SYS_TABLES"); sys_index = UT_LIST_GET_FIRST(sys_tables->indexes); ut_a(!dict_table_is_comp(sys_tables)); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); dfield_set_data(dfield, name, ut_strlen(name)); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); loop: rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur)) { /* Not found */ btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); return(NULL); } field = rec_get_nth_field_old(rec, 0, &len); if (len < strlen(name) || ut_memcmp(name, field, strlen(name)) != 0) { /* Not found */ btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); return(NULL); } if (!rec_get_deleted_flag(rec, 0)) { /* We found one */ char* table_name = mem_strdupl((char*) field, len); btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); return(table_name); } btr_pcur_move_to_next_user_rec(&pcur, &mtr); goto loop; } /********************************************************************//** Prints to the standard output information on all tables found in the data dictionary system table. */ UNIV_INTERN void dict_print(void) /*============*/ { dict_table_t* table; btr_pcur_t pcur; const rec_t* rec; mem_heap_t* heap; mtr_t mtr; /* Enlarge the fatal semaphore wait timeout during the InnoDB table monitor printout */ mutex_enter(&kernel_mutex); srv_fatal_semaphore_wait_threshold += 7200; /* 2 hours */ mutex_exit(&kernel_mutex); heap = mem_heap_create(1000); mutex_enter(&(dict_sys->mutex)); mtr_start(&mtr); rec = dict_startscan_system(&pcur, &mtr, SYS_TABLES); while (rec) { const char* err_msg; err_msg = dict_process_sys_tables_rec( heap, rec, &table, DICT_TABLE_LOAD_FROM_CACHE | DICT_TABLE_UPDATE_STATS); mtr_commit(&mtr); if (!err_msg) { dict_table_print_low(table); } else { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: %s\n", err_msg); } mem_heap_empty(heap); mtr_start(&mtr); rec = dict_getnext_system(&pcur, &mtr); } mtr_commit(&mtr); mutex_exit(&(dict_sys->mutex)); mem_heap_free(heap); /* Restore the fatal semaphore wait timeout */ mutex_enter(&kernel_mutex); srv_fatal_semaphore_wait_threshold -= 7200; /* 2 hours */ mutex_exit(&kernel_mutex); } /********************************************************************//** This function gets the next system table record as it scans the table. @return the next record if found, NULL if end of scan */ static const rec_t* dict_getnext_system_low( /*====================*/ btr_pcur_t* pcur, /*!< in/out: persistent cursor to the record*/ mtr_t* mtr) /*!< in: the mini-transaction */ { rec_t* rec = NULL; while (!rec || rec_get_deleted_flag(rec, 0)) { btr_pcur_move_to_next_user_rec(pcur, mtr); rec = btr_pcur_get_rec(pcur); if (!btr_pcur_is_on_user_rec(pcur)) { /* end of index */ btr_pcur_close(pcur); return(NULL); } } /* Get a record, let's save the position */ btr_pcur_store_position(pcur, mtr); return(rec); } /********************************************************************//** This function opens a system table, and return the first record. @return first record of the system table */ UNIV_INTERN const rec_t* dict_startscan_system( /*==================*/ btr_pcur_t* pcur, /*!< out: persistent cursor to the record */ mtr_t* mtr, /*!< in: the mini-transaction */ dict_system_id_t system_id) /*!< in: which system table to open */ { dict_table_t* system_table; dict_index_t* clust_index; const rec_t* rec; ut_a(system_id < SYS_NUM_SYSTEM_TABLES); system_table = dict_table_get_low(SYSTEM_TABLE_NAME[system_id]); clust_index = UT_LIST_GET_FIRST(system_table->indexes); btr_pcur_open_at_index_side(TRUE, clust_index, BTR_SEARCH_LEAF, pcur, TRUE, mtr); rec = dict_getnext_system_low(pcur, mtr); return(rec); } /********************************************************************//** This function gets the next system table record as it scans the table. @return the next record if found, NULL if end of scan */ UNIV_INTERN const rec_t* dict_getnext_system( /*================*/ btr_pcur_t* pcur, /*!< in/out: persistent cursor to the record */ mtr_t* mtr) /*!< in: the mini-transaction */ { const rec_t* rec; /* Restore the position */ btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr); /* Get the next record */ rec = dict_getnext_system_low(pcur, mtr); return(rec); } /********************************************************************//** This function processes one SYS_TABLES record and populate the dict_table_t struct for the table. Extracted out of dict_print() to be used by both monitor table output and information schema innodb_sys_tables output. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_tables_rec( /*========================*/ mem_heap_t* heap, /*!< in/out: temporary memory heap */ const rec_t* rec, /*!< in: SYS_TABLES record */ dict_table_t** table, /*!< out: dict_table_t to fill */ dict_table_info_t status) /*!< in: status bit controls options such as whether we shall look for dict_table_t from cache first */ { ulint len; const char* field; const char* err_msg = NULL; char* table_name; field = (const char*) rec_get_nth_field_old(rec, 0, &len); ut_a(!rec_get_deleted_flag(rec, 0)); /* Get the table name */ table_name = mem_heap_strdupl(heap, field, len); /* If DICT_TABLE_LOAD_FROM_CACHE is set, first check whether there is cached dict_table_t struct first */ if (status & DICT_TABLE_LOAD_FROM_CACHE) { *table = dict_table_get_low(table_name); if (!(*table)) { err_msg = "Table not found in cache"; } } else { err_msg = dict_load_table_low(table_name, rec, table); } if (err_msg) { return(err_msg); } if ((status & DICT_TABLE_UPDATE_STATS) && dict_table_get_first_index(*table)) { /* Update statistics if DICT_TABLE_UPDATE_STATS is set */ dict_update_statistics(*table, FALSE /* update even if initialized */); } return(NULL); } /********************************************************************//** This function parses a SYS_INDEXES record and populate a dict_index_t structure with the information from the record. For detail information about SYS_INDEXES fields, please refer to dict_boot() function. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_indexes_rec( /*=========================*/ mem_heap_t* heap, /*!< in/out: heap memory */ const rec_t* rec, /*!< in: current SYS_INDEXES rec */ dict_index_t* index, /*!< out: index to be filled */ table_id_t* table_id) /*!< out: index table id */ { const char* err_msg; byte* buf; buf = mem_heap_alloc(heap, 8); /* Parse the record, and get "dict_index_t" struct filled */ err_msg = dict_load_index_low(buf, NULL, heap, rec, FALSE, &index); *table_id = mach_read_from_8(buf); return(err_msg); } /********************************************************************//** This function parses a SYS_COLUMNS record and populate a dict_column_t structure with the information from the record. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_columns_rec( /*=========================*/ mem_heap_t* heap, /*!< in/out: heap memory */ const rec_t* rec, /*!< in: current SYS_COLUMNS rec */ dict_col_t* column, /*!< out: dict_col_t to be filled */ table_id_t* table_id, /*!< out: table id */ const char** col_name) /*!< out: column name */ { const char* err_msg; /* Parse the record, and get "dict_col_t" struct filled */ err_msg = dict_load_column_low(NULL, heap, column, table_id, col_name, rec); return(err_msg); } /********************************************************************//** This function parses a SYS_FIELDS record and populates a dict_field_t structure with the information from the record. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_fields_rec( /*========================*/ mem_heap_t* heap, /*!< in/out: heap memory */ const rec_t* rec, /*!< in: current SYS_FIELDS rec */ dict_field_t* sys_field, /*!< out: dict_field_t to be filled */ ulint* pos, /*!< out: Field position */ index_id_t* index_id, /*!< out: current index id */ index_id_t last_id) /*!< in: previous index id */ { byte* buf; byte* last_index_id; const char* err_msg; buf = mem_heap_alloc(heap, 8); last_index_id = mem_heap_alloc(heap, 8); mach_write_to_8(last_index_id, last_id); err_msg = dict_load_field_low(buf, NULL, sys_field, pos, last_index_id, heap, rec, NULL, 0); *index_id = mach_read_from_8(buf); return(err_msg); } #ifdef FOREIGN_NOT_USED /********************************************************************//** This function parses a SYS_FOREIGN record and populate a dict_foreign_t structure with the information from the record. For detail information about SYS_FOREIGN fields, please refer to dict_load_foreign() function. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_foreign_rec( /*=========================*/ mem_heap_t* heap, /*!< in/out: heap memory */ const rec_t* rec, /*!< in: current SYS_FOREIGN rec */ dict_foreign_t* foreign) /*!< out: dict_foreign_t struct to be filled */ { ulint len; const byte* field; ulint n_fields_and_type; if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return("delete-marked record in SYS_FOREIGN"); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 6)) { return("wrong number of columns in SYS_FOREIGN record"); } field = rec_get_nth_field_old(rec, 0/*ID*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { err_len: return("incorrect column length in SYS_FOREIGN"); } /* This recieves a dict_foreign_t* that points to a stack variable. So mem_heap_free(foreign->heap) is not used as elsewhere. Since the heap used here is freed elsewhere, foreign->heap is not assigned. */ foreign->id = mem_heap_strdupl(heap, (const char*) field, len); rec_get_nth_field_offs_old(rec, 1/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 2/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } /* The _lookup versions of the referenced and foreign table names are not assigned since they are not used in this dict_foreign_t */ field = rec_get_nth_field_old(rec, 3/*FOR_NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } foreign->foreign_table_name = mem_heap_strdupl( heap, (const char*) field, len); field = rec_get_nth_field_old(rec, 4/*REF_NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } foreign->referenced_table_name = mem_heap_strdupl( heap, (const char*) field, len); field = rec_get_nth_field_old(rec, 5/*N_COLS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } n_fields_and_type = mach_read_from_4(field); foreign->type = (unsigned int) (n_fields_and_type >> 24); foreign->n_fields = (unsigned int) (n_fields_and_type & 0x3FFUL); return(NULL); } #endif /* FOREIGN_NOT_USED */ #ifdef FOREIGN_NOT_USED /********************************************************************//** This function parses a SYS_FOREIGN_COLS record and extract necessary information from the record and return to caller. @return error message, or NULL on success */ UNIV_INTERN const char* dict_process_sys_foreign_col_rec( /*=============================*/ mem_heap_t* heap, /*!< in/out: heap memory */ const rec_t* rec, /*!< in: current SYS_FOREIGN_COLS rec */ const char** name, /*!< out: foreign key constraint name */ const char** for_col_name, /*!< out: referencing column name */ const char** ref_col_name, /*!< out: referenced column name in referenced table */ ulint* pos) /*!< out: column position */ { ulint len; const byte* field; if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return("delete-marked record in SYS_FOREIGN_COLS"); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 6)) { return("wrong number of columns in SYS_FOREIGN_COLS record"); } field = rec_get_nth_field_old(rec, 0/*ID*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { err_len: return("incorrect column length in SYS_FOREIGN_COLS"); } *name = mem_heap_strdupl(heap, (char*) field, len); field = rec_get_nth_field_old(rec, 1/*POS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } *pos = mach_read_from_4(field); rec_get_nth_field_offs_old(rec, 2/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 3/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } field = rec_get_nth_field_old(rec, 4/*FOR_COL_NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } *for_col_name = mem_heap_strdupl(heap, (char*) field, len); field = rec_get_nth_field_old(rec, 5/*REF_COL_NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } *ref_col_name = mem_heap_strdupl(heap, (char*) field, len); return(NULL); } #endif /* FOREIGN_NOT_USED */ /********************************************************************//** Determine the flags of a table described in SYS_TABLES. @return compressed page size in kilobytes; or 0 if the tablespace is uncompressed, ULINT_UNDEFINED on error */ static ulint dict_sys_tables_get_flags( /*======================*/ const rec_t* rec) /*!< in: a record of SYS_TABLES */ { const byte* field; ulint len; ulint n_cols; ulint flags; field = rec_get_nth_field_old(rec, 5, &len); ut_a(len == 4); flags = mach_read_from_4(field); if (UNIV_LIKELY(flags == DICT_TABLE_ORDINARY)) { return(0); } field = rec_get_nth_field_old(rec, 4/*N_COLS*/, &len); n_cols = mach_read_from_4(field); if (UNIV_UNLIKELY(!(n_cols & 0x80000000UL))) { /* New file formats require ROW_FORMAT=COMPACT. */ return(ULINT_UNDEFINED); } switch (flags & (DICT_TF_FORMAT_MASK | DICT_TF_COMPACT)) { default: case DICT_TF_FORMAT_51 << DICT_TF_FORMAT_SHIFT: case DICT_TF_FORMAT_51 << DICT_TF_FORMAT_SHIFT | DICT_TF_COMPACT: /* flags should be DICT_TABLE_ORDINARY, or DICT_TF_FORMAT_MASK should be nonzero. */ return(ULINT_UNDEFINED); case DICT_TF_FORMAT_ZIP << DICT_TF_FORMAT_SHIFT | DICT_TF_COMPACT: #if DICT_TF_FORMAT_MAX > DICT_TF_FORMAT_ZIP # error "missing case labels for DICT_TF_FORMAT_ZIP .. DICT_TF_FORMAT_MAX" #endif /* We support this format. */ break; } if (UNIV_UNLIKELY((flags & DICT_TF_ZSSIZE_MASK) > (DICT_TF_ZSSIZE_MAX << DICT_TF_ZSSIZE_SHIFT))) { /* Unsupported compressed page size. */ return(ULINT_UNDEFINED); } if (UNIV_UNLIKELY(flags & (~0 << DICT_TF_BITS))) { /* Some unused bits are set. */ return(ULINT_UNDEFINED); } return(flags); } /********************************************************************//** In a crash recovery we already have all the tablespace objects created. This function compares the space id information in the InnoDB data dictionary to what we already read with fil_load_single_table_tablespaces(). In a normal startup, we create the tablespace objects for every table in InnoDB's data dictionary, if the corresponding .ibd file exists. We also scan the biggest space id, and store it to fil_system. */ UNIV_INTERN void dict_check_tablespaces_and_store_max_id( /*====================================*/ ibool in_crash_recovery) /*!< in: are we doing a crash recovery */ { dict_table_t* sys_tables; dict_index_t* sys_index; btr_pcur_t pcur; const rec_t* rec; ulint max_space_id; mtr_t mtr; mutex_enter(&(dict_sys->mutex)); mtr_start(&mtr); sys_tables = dict_table_get_low("SYS_TABLES"); sys_index = UT_LIST_GET_FIRST(sys_tables->indexes); ut_a(!dict_table_is_comp(sys_tables)); max_space_id = mtr_read_ulint(dict_hdr_get(&mtr) + DICT_HDR_MAX_SPACE_ID, MLOG_4BYTES, &mtr); fil_set_max_space_id_if_bigger(max_space_id); btr_pcur_open_at_index_side(TRUE, sys_index, BTR_SEARCH_LEAF, &pcur, TRUE, &mtr); loop: btr_pcur_move_to_next_user_rec(&pcur, &mtr); rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur)) { /* end of index */ btr_pcur_close(&pcur); mtr_commit(&mtr); /* We must make the tablespace cache aware of the biggest known space id */ /* printf("Biggest space id in data dictionary %lu\n", max_space_id); */ fil_set_max_space_id_if_bigger(max_space_id); mutex_exit(&(dict_sys->mutex)); return; } if (!rec_get_deleted_flag(rec, 0)) { /* We found one */ const byte* field; ulint len; ulint space_id; ulint flags; char* name; field = rec_get_nth_field_old(rec, 0, &len); name = mem_strdupl((char*) field, len); flags = dict_sys_tables_get_flags(rec); if (UNIV_UNLIKELY(flags == ULINT_UNDEFINED)) { field = rec_get_nth_field_old(rec, 5, &len); flags = mach_read_from_4(field); ut_print_timestamp(stderr); fputs(" InnoDB: Error: table ", stderr); ut_print_filename(stderr, name); fprintf(stderr, "\n" "InnoDB: in InnoDB data dictionary" " has unknown type %lx.\n", (ulong) flags); goto loop; } field = rec_get_nth_field_old(rec, 9, &len); ut_a(len == 4); space_id = mach_read_from_4(field); btr_pcur_store_position(&pcur, &mtr); mtr_commit(&mtr); if (space_id == 0) { /* The system tablespace always exists. */ } else if (in_crash_recovery) { /* Check that the tablespace (the .ibd file) really exists; print a warning to the .err log if not. Do not print warnings for temporary tables. */ ibool is_temp; field = rec_get_nth_field_old(rec, 4, &len); if (0x80000000UL & mach_read_from_4(field)) { /* ROW_FORMAT=COMPACT: read the is_temp flag from SYS_TABLES.MIX_LEN. */ field = rec_get_nth_field_old(rec, 7, &len); is_temp = mach_read_from_4(field) & DICT_TF2_TEMPORARY; } else { /* For tables created with old versions of InnoDB, SYS_TABLES.MIX_LEN may contain garbage. Such tables would always be in ROW_FORMAT=REDUNDANT. Pretend that all such tables are non-temporary. That is, do not suppress error printouts about temporary tables not being found. */ is_temp = FALSE; } fil_space_for_table_exists_in_mem( space_id, name, is_temp, TRUE, !is_temp); } else { /* It is a normal database startup: create the space object and check that the .ibd file exists. */ fil_open_single_table_tablespace(FALSE, space_id, flags, name); } mem_free(name); if (space_id > max_space_id) { max_space_id = space_id; } mtr_start(&mtr); btr_pcur_restore_position(BTR_SEARCH_LEAF, &pcur, &mtr); } goto loop; } /********************************************************************//** Loads a table column definition from a SYS_COLUMNS record to dict_table_t. @return error message, or NULL on success */ UNIV_INTERN const char* dict_load_column_low( /*=================*/ dict_table_t* table, /*!< in/out: table, could be NULL if we just populate a dict_column_t struct with information from a SYS_COLUMNS record */ mem_heap_t* heap, /*!< in/out: memory heap for temporary storage */ dict_col_t* column, /*!< out: dict_column_t to fill, or NULL if table != NULL */ table_id_t* table_id, /*!< out: table id */ const char** col_name, /*!< out: column name */ const rec_t* rec) /*!< in: SYS_COLUMNS record */ { char* name; const byte* field; ulint len; ulint mtype; ulint prtype; ulint col_len; ulint pos; ut_ad(table || column); if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return("delete-marked record in SYS_COLUMNS"); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 9)) { return("wrong number of columns in SYS_COLUMNS record"); } field = rec_get_nth_field_old(rec, 0/*TABLE_ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { err_len: return("incorrect column length in SYS_COLUMNS"); } if (table_id) { *table_id = mach_read_from_8(field); } else if (UNIV_UNLIKELY(table->id != mach_read_from_8(field))) { return("SYS_COLUMNS.TABLE_ID mismatch"); } field = rec_get_nth_field_old(rec, 1/*POS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } pos = mach_read_from_4(field); if (UNIV_UNLIKELY(table && table->n_def != pos)) { return("SYS_COLUMNS.POS mismatch"); } rec_get_nth_field_offs_old(rec, 2/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 3/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } field = rec_get_nth_field_old(rec, 4/*NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } name = mem_heap_strdupl(heap, (const char*) field, len); if (col_name) { *col_name = name; } field = rec_get_nth_field_old(rec, 5/*MTYPE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } mtype = mach_read_from_4(field); field = rec_get_nth_field_old(rec, 6/*PRTYPE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } prtype = mach_read_from_4(field); if (dtype_get_charset_coll(prtype) == 0 && dtype_is_string_type(mtype)) { /* The table was created with < 4.1.2. */ if (dtype_is_binary_string_type(mtype, prtype)) { /* Use the binary collation for string columns of binary type. */ prtype = dtype_form_prtype( prtype, DATA_MYSQL_BINARY_CHARSET_COLL); } else { /* Use the default charset for other than binary columns. */ prtype = dtype_form_prtype( prtype, data_mysql_default_charset_coll); } } field = rec_get_nth_field_old(rec, 7/*LEN*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } col_len = mach_read_from_4(field); field = rec_get_nth_field_old(rec, 8/*PREC*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } if (!column) { dict_mem_table_add_col(table, heap, name, mtype, prtype, col_len); } else { dict_mem_fill_column_struct(column, pos, mtype, prtype, col_len); } return(NULL); } /********************************************************************//** Loads definitions for table columns. */ static void dict_load_columns( /*==============*/ dict_table_t* table, /*!< in/out: table */ mem_heap_t* heap) /*!< in/out: memory heap for temporary storage */ { dict_table_t* sys_columns; dict_index_t* sys_index; btr_pcur_t pcur; dtuple_t* tuple; dfield_t* dfield; const rec_t* rec; byte* buf; ulint i; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); mtr_start(&mtr); sys_columns = dict_table_get_low("SYS_COLUMNS"); sys_index = UT_LIST_GET_FIRST(sys_columns->indexes); ut_a(!dict_table_is_comp(sys_columns)); ut_a(name_of_col_is(sys_columns, sys_index, 4, "NAME")); ut_a(name_of_col_is(sys_columns, sys_index, 8, "PREC")); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); buf = mem_heap_alloc(heap, 8); mach_write_to_8(buf, table->id); dfield_set_data(dfield, buf, 8); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); for (i = 0; i + DATA_N_SYS_COLS < (ulint) table->n_cols; i++) { const char* err_msg; rec = btr_pcur_get_rec(&pcur); ut_a(btr_pcur_is_on_user_rec(&pcur)); err_msg = dict_load_column_low(table, heap, NULL, NULL, NULL, rec); if (err_msg) { fprintf(stderr, "InnoDB: %s\n", err_msg); ut_error; } btr_pcur_move_to_next_user_rec(&pcur, &mtr); } btr_pcur_close(&pcur); mtr_commit(&mtr); } /** Error message for a delete-marked record in dict_load_field_low() */ static const char* dict_load_field_del = "delete-marked record in SYS_FIELDS"; static const char* dict_load_field_too_big = "column prefix exceeds maximum" " limit"; /********************************************************************//** Loads an index field definition from a SYS_FIELDS record to dict_index_t. @return error message, or NULL on success */ UNIV_INTERN const char* dict_load_field_low( /*================*/ byte* index_id, /*!< in/out: index id (8 bytes) an "in" value if index != NULL and "out" if index == NULL */ dict_index_t* index, /*!< in/out: index, could be NULL if we just populate a dict_field_t struct with information from a SYS_FIELDSS record */ dict_field_t* sys_field, /*!< out: dict_field_t to be filled */ ulint* pos, /*!< out: Field position */ byte* last_index_id, /*!< in: last index id */ mem_heap_t* heap, /*!< in/out: memory heap for temporary storage */ const rec_t* rec, /*!< in: SYS_FIELDS record */ char* addition_err_str,/*!< out: additional error message that requires information to be filled, or NULL */ ulint err_str_len) /*!< in: length of addition_err_str in bytes */ { const byte* field; ulint len; ulint pos_and_prefix_len; ulint prefix_len; ibool first_field; ulint position; /* Either index or sys_field is supplied, not both */ ut_a((!index) || (!sys_field)); if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return(dict_load_field_del); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 5)) { return("wrong number of columns in SYS_FIELDS record"); } field = rec_get_nth_field_old(rec, 0/*INDEX_ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { err_len: return("incorrect column length in SYS_FIELDS"); } if (!index) { ut_a(last_index_id); memcpy(index_id, (const char*)field, 8); first_field = memcmp(index_id, last_index_id, 8); } else { first_field = (index->n_def == 0); if (memcmp(field, index_id, 8)) { return("SYS_FIELDS.INDEX_ID mismatch"); } } field = rec_get_nth_field_old(rec, 1/*POS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } rec_get_nth_field_offs_old(rec, 2/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 3/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } /* The next field stores the field position in the index and a possible column prefix length if the index field does not contain the whole column. The storage format is like this: if there is at least one prefix field in the index, then the HIGH 2 bytes contain the field number (index->n_def) and the low 2 bytes the prefix length for the field. Otherwise the field number (index->n_def) is contained in the 2 LOW bytes. */ pos_and_prefix_len = mach_read_from_4(field); if (index && UNIV_UNLIKELY ((pos_and_prefix_len & 0xFFFFUL) != index->n_def && (pos_and_prefix_len >> 16 & 0xFFFF) != index->n_def)) { return("SYS_FIELDS.POS mismatch"); } if (first_field || pos_and_prefix_len > 0xFFFFUL) { prefix_len = pos_and_prefix_len & 0xFFFFUL; position = (pos_and_prefix_len & 0xFFFF0000UL) >> 16; } else { prefix_len = 0; position = pos_and_prefix_len & 0xFFFFUL; } field = rec_get_nth_field_old(rec, 4, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { goto err_len; } if (prefix_len > REC_VERSION_56_MAX_INDEX_COL_LEN) { if (addition_err_str) { ut_snprintf(addition_err_str, err_str_len, "index field '%s' has a prefix length" " of %lu bytes", mem_heap_strdupl( heap, (const char*) field, len), (ulong) prefix_len); } return(dict_load_field_too_big); } if (index) { dict_mem_index_add_field( index, mem_heap_strdupl(heap, (const char*) field, len), prefix_len); } else { ut_a(sys_field); ut_a(pos); sys_field->name = mem_heap_strdupl( heap, (const char*) field, len); sys_field->prefix_len = prefix_len; *pos = position; } return(NULL); } /********************************************************************//** Loads definitions for index fields. @return DB_SUCCESS if ok, DB_CORRUPTION if corruption */ static ulint dict_load_fields( /*=============*/ dict_index_t* index, /*!< in/out: index whose fields to load */ mem_heap_t* heap) /*!< in: memory heap for temporary storage */ { dict_table_t* sys_fields; dict_index_t* sys_index; btr_pcur_t pcur; dtuple_t* tuple; dfield_t* dfield; const rec_t* rec; byte* buf; ulint i; mtr_t mtr; ulint error; ut_ad(mutex_own(&(dict_sys->mutex))); mtr_start(&mtr); sys_fields = dict_table_get_low("SYS_FIELDS"); sys_index = UT_LIST_GET_FIRST(sys_fields->indexes); ut_a(!dict_table_is_comp(sys_fields)); ut_a(name_of_col_is(sys_fields, sys_index, 4, "COL_NAME")); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); buf = mem_heap_alloc(heap, 8); mach_write_to_8(buf, index->id); dfield_set_data(dfield, buf, 8); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); for (i = 0; i < index->n_fields; i++) { const char* err_msg; char addition_err_str[1024]; rec = btr_pcur_get_rec(&pcur); ut_a(btr_pcur_is_on_user_rec(&pcur)); err_msg = dict_load_field_low(buf, index, NULL, NULL, NULL, heap, rec, addition_err_str, sizeof(addition_err_str)); if (err_msg == dict_load_field_del) { /* There could be delete marked records in SYS_FIELDS because SYS_FIELDS.INDEX_ID can be updated by ALTER TABLE ADD INDEX. */ goto next_rec; } else if (err_msg) { if (err_msg == dict_load_field_too_big) { fprintf(stderr, "InnoDB: Error: load index" " '%s' failed.\n" "InnoDB: %s,\n" "InnoDB: which exceeds the" " maximum limit of %lu bytes.\n" "InnoDB: Please use server that" " supports long index prefix\n" "InnoDB: or turn on" " innodb_force_recovery to load" " the table\n", index->name, addition_err_str, (ulong) (REC_VERSION_56_MAX_INDEX_COL_LEN)); } else { fprintf(stderr, "InnoDB: %s\n", err_msg); } error = DB_CORRUPTION; goto func_exit; } next_rec: btr_pcur_move_to_next_user_rec(&pcur, &mtr); } error = DB_SUCCESS; func_exit: btr_pcur_close(&pcur); mtr_commit(&mtr); return(error); } /** Error message for a delete-marked record in dict_load_index_low() */ static const char* dict_load_index_del = "delete-marked record in SYS_INDEXES"; /** Error message for table->id mismatch in dict_load_index_low() */ static const char* dict_load_index_id_err = "SYS_INDEXES.TABLE_ID mismatch"; /********************************************************************//** Loads an index definition from a SYS_INDEXES record to dict_index_t. If allocate=TRUE, we will create a dict_index_t structure and fill it accordingly. If allocated=FALSE, the dict_index_t will be supplied by the caller and filled with information read from the record. @return error message, or NULL on success */ UNIV_INTERN const char* dict_load_index_low( /*================*/ byte* table_id, /*!< in/out: table id (8 bytes), an "in" value if allocate=TRUE and "out" when allocate=FALSE */ const char* table_name, /*!< in: table name */ mem_heap_t* heap, /*!< in/out: temporary memory heap */ const rec_t* rec, /*!< in: SYS_INDEXES record */ ibool allocate, /*!< in: TRUE=allocate *index, FALSE=fill in a pre-allocated *index */ dict_index_t** index) /*!< out,own: index, or NULL */ { const byte* field; ulint len; ulint name_len; char* name_buf; index_id_t id; ulint n_fields; ulint type; ulint space; if (allocate) { /* If allocate=TRUE, no dict_index_t will be supplied. Initialize "*index" to NULL */ *index = NULL; } if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return(dict_load_index_del); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 9)) { return("wrong number of columns in SYS_INDEXES record"); } field = rec_get_nth_field_old(rec, 0/*TABLE_ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { err_len: return("incorrect column length in SYS_INDEXES"); } if (!allocate) { /* We are reading a SYS_INDEXES record. Copy the table_id */ memcpy(table_id, (const char*)field, 8); } else if (memcmp(field, table_id, 8)) { /* Caller supplied table_id, verify it is the same id as on the index record */ return(dict_load_index_id_err); } field = rec_get_nth_field_old(rec, 1/*ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { goto err_len; } id = mach_read_from_8(field); rec_get_nth_field_offs_old(rec, 2/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 3/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } field = rec_get_nth_field_old(rec, 4/*NAME*/, &name_len); if (UNIV_UNLIKELY(name_len == UNIV_SQL_NULL)) { goto err_len; } name_buf = mem_heap_strdupl(heap, (const char*) field, name_len); field = rec_get_nth_field_old(rec, 5/*N_FIELDS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } n_fields = mach_read_from_4(field); field = rec_get_nth_field_old(rec, 6/*TYPE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } type = mach_read_from_4(field); field = rec_get_nth_field_old(rec, 7/*SPACE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } space = mach_read_from_4(field); field = rec_get_nth_field_old(rec, 8/*PAGE_NO*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } if (allocate) { *index = dict_mem_index_create(table_name, name_buf, space, type, n_fields); } else { ut_a(*index); dict_mem_fill_index_struct(*index, NULL, NULL, name_buf, space, type, n_fields); } (*index)->id = id; (*index)->page = mach_read_from_4(field); ut_ad((*index)->page); return(NULL); } /********************************************************************//** Loads definitions for table indexes. Adds them to the data dictionary cache. @return DB_SUCCESS if ok, DB_CORRUPTION if corruption of dictionary table or DB_UNSUPPORTED if table has unknown index type */ static ulint dict_load_indexes( /*==============*/ dict_table_t* table, /*!< in/out: table */ mem_heap_t* heap, /*!< in: memory heap for temporary storage */ dict_err_ignore_t ignore_err) /*!< in: error to be ignored when loading the index definition */ { dict_table_t* sys_indexes; dict_index_t* sys_index; btr_pcur_t pcur; dtuple_t* tuple; dfield_t* dfield; const rec_t* rec; byte* buf; mtr_t mtr; ulint error = DB_SUCCESS; ut_ad(mutex_own(&(dict_sys->mutex))); mtr_start(&mtr); sys_indexes = dict_table_get_low("SYS_INDEXES"); sys_index = UT_LIST_GET_FIRST(sys_indexes->indexes); ut_a(!dict_table_is_comp(sys_indexes)); ut_a(name_of_col_is(sys_indexes, sys_index, 4, "NAME")); ut_a(name_of_col_is(sys_indexes, sys_index, 8, "PAGE_NO")); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); buf = mem_heap_alloc(heap, 8); mach_write_to_8(buf, table->id); dfield_set_data(dfield, buf, 8); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); for (;;) { dict_index_t* index = NULL; const char* err_msg; if (!btr_pcur_is_on_user_rec(&pcur)) { break; } rec = btr_pcur_get_rec(&pcur); err_msg = dict_load_index_low(buf, table->name, heap, rec, TRUE, &index); ut_ad((index == NULL) == (err_msg != NULL)); if (err_msg == dict_load_index_id_err) { /* TABLE_ID mismatch means that we have run out of index definitions for the table. */ break; } else if (err_msg == dict_load_index_del) { /* Skip delete-marked records. */ goto next_rec; } else if (err_msg) { fprintf(stderr, "InnoDB: %s\n", err_msg); error = DB_CORRUPTION; goto func_exit; } ut_ad(index); /* We check for unsupported types first, so that the subsequent checks are relevant for the supported types. */ if (index->type & ~(DICT_CLUSTERED | DICT_UNIQUE)) { fprintf(stderr, "InnoDB: Error: unknown type %lu" " of index %s of table %s\n", (ulong) index->type, index->name, table->name); error = DB_UNSUPPORTED; dict_mem_index_free(index); goto func_exit; } else if (index->page == FIL_NULL) { fprintf(stderr, "InnoDB: Error: trying to load index %s" " for table %s\n" "InnoDB: but the index tree has been freed!\n", index->name, table->name); if (ignore_err & DICT_ERR_IGNORE_INDEX_ROOT) { /* If caller can tolerate this error, we will continue to load the index and let caller deal with this error. However mark the index and table corrupted */ index->corrupted = TRUE; table->corrupted = TRUE; fprintf(stderr, "InnoDB: Index is corrupt but forcing" " load into data dictionary\n"); } else { corrupted: dict_mem_index_free(index); error = DB_CORRUPTION; goto func_exit; } } else if (!dict_index_is_clust(index) && NULL == dict_table_get_first_index(table)) { fputs("InnoDB: Error: trying to load index ", stderr); ut_print_name(stderr, NULL, FALSE, index->name); fputs(" for table ", stderr); ut_print_name(stderr, NULL, TRUE, table->name); fputs("\nInnoDB: but the first index" " is not clustered!\n", stderr); goto corrupted; } else if (table->id < DICT_HDR_FIRST_ID && (dict_index_is_clust(index) || ((table == dict_sys->sys_tables) && !strcmp("ID_IND", index->name)))) { /* The index was created in memory already at booting of the database server */ dict_mem_index_free(index); } else { error = dict_load_fields(index, heap); if (error != DB_SUCCESS) { fprintf(stderr, "InnoDB: Error: load index '%s'" " for table '%s' failed\n", index->name, table->name); /* If the force recovery flag is set, and if the failed index is not the primary index, we will continue and open other indexes */ if (srv_force_recovery && !dict_index_is_clust(index)) { error = DB_SUCCESS; goto next_rec; } else { goto func_exit; } } error = dict_index_add_to_cache(table, index, index->page, FALSE); /* The data dictionary tables should never contain invalid index definitions. If we ignored this error and simply did not load this index definition, the .frm file would disagree with the index definitions inside InnoDB. */ if (UNIV_UNLIKELY(error != DB_SUCCESS)) { goto func_exit; } } next_rec: btr_pcur_move_to_next_user_rec(&pcur, &mtr); } func_exit: btr_pcur_close(&pcur); mtr_commit(&mtr); return(error); } /********************************************************************//** Loads a table definition from a SYS_TABLES record to dict_table_t. Does not load any columns or indexes. @return error message, or NULL on success */ UNIV_INTERN const char* dict_load_table_low( /*================*/ const char* name, /*!< in: table name */ const rec_t* rec, /*!< in: SYS_TABLES record */ dict_table_t** table) /*!< out,own: table, or NULL */ { const byte* field; ulint len; ulint space; ulint n_cols; ulint flags; if (UNIV_UNLIKELY(rec_get_deleted_flag(rec, 0))) { return("delete-marked record in SYS_TABLES"); } if (UNIV_UNLIKELY(rec_get_n_fields_old(rec) != 10)) { return("wrong number of columns in SYS_TABLES record"); } rec_get_nth_field_offs_old(rec, 0/*NAME*/, &len); if (UNIV_UNLIKELY(len < 1 || len == UNIV_SQL_NULL)) { err_len: return("incorrect column length in SYS_TABLES"); } rec_get_nth_field_offs_old(rec, 1/*DB_TRX_ID*/, &len); if (UNIV_UNLIKELY(len != DATA_TRX_ID_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 2/*DB_ROLL_PTR*/, &len); if (UNIV_UNLIKELY(len != DATA_ROLL_PTR_LEN && len != UNIV_SQL_NULL)) { goto err_len; } rec_get_nth_field_offs_old(rec, 3/*ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { goto err_len; } field = rec_get_nth_field_old(rec, 4/*N_COLS*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } n_cols = mach_read_from_4(field); rec_get_nth_field_offs_old(rec, 5/*TYPE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } rec_get_nth_field_offs_old(rec, 6/*MIX_ID*/, &len); if (UNIV_UNLIKELY(len != 8)) { goto err_len; } rec_get_nth_field_offs_old(rec, 7/*MIX_LEN*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } rec_get_nth_field_offs_old(rec, 8/*CLUSTER_ID*/, &len); if (UNIV_UNLIKELY(len != UNIV_SQL_NULL)) { goto err_len; } field = rec_get_nth_field_old(rec, 9/*SPACE*/, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } space = mach_read_from_4(field); /* Check if the tablespace exists and has the right name */ if (space != 0) { flags = dict_sys_tables_get_flags(rec); if (UNIV_UNLIKELY(flags == ULINT_UNDEFINED)) { field = rec_get_nth_field_old(rec, 5/*TYPE*/, &len); ut_ad(len == 4); /* this was checked earlier */ flags = mach_read_from_4(field); ut_print_timestamp(stderr); fputs(" InnoDB: Error: table ", stderr); ut_print_filename(stderr, name); fprintf(stderr, "\n" "InnoDB: in InnoDB data dictionary" " has unknown type %lx.\n", (ulong) flags); return("incorrect flags in SYS_TABLES"); } } else { flags = 0; } /* The high-order bit of N_COLS is the "compact format" flag. For tables in that format, MIX_LEN may hold additional flags. */ if (n_cols & 0x80000000UL) { ulint flags2; flags |= DICT_TF_COMPACT; field = rec_get_nth_field_old(rec, 7, &len); if (UNIV_UNLIKELY(len != 4)) { goto err_len; } flags2 = mach_read_from_4(field); if (flags2 & (~0 << (DICT_TF2_BITS - DICT_TF2_SHIFT))) { ut_print_timestamp(stderr); fputs(" InnoDB: Warning: table ", stderr); ut_print_filename(stderr, name); fprintf(stderr, "\n" "InnoDB: in InnoDB data dictionary" " has unknown flags %lx.\n", (ulong) flags2); flags2 &= ~(~0 << (DICT_TF2_BITS - DICT_TF2_SHIFT)); } flags |= flags2 << DICT_TF2_SHIFT; } /* See if the tablespace is available. */ *table = dict_mem_table_create(name, space, n_cols & ~0x80000000UL, flags); field = rec_get_nth_field_old(rec, 3/*ID*/, &len); ut_ad(len == 8); /* this was checked earlier */ (*table)->id = mach_read_from_8(field); (*table)->ibd_file_missing = FALSE; return(NULL); } /********************************************************************//** Loads a table definition and also all its index definitions, and also the cluster definition if the table is a member in a cluster. Also loads all foreign key constraints where the foreign key is in the table or where a foreign key references columns in this table. Adds all these to the data dictionary cache. @return table, NULL if does not exist; if the table is stored in an .ibd file, but the file does not exist, then we set the ibd_file_missing flag TRUE in the table object we return */ UNIV_INTERN dict_table_t* dict_load_table( /*============*/ const char* name, /*!< in: table name in the databasename/tablename format */ ibool cached, /*!< in: TRUE=add to cache, FALSE=do not */ dict_err_ignore_t ignore_err) /*!< in: error to be ignored when loading table and its indexes' definition */ { dict_table_t* table; dict_table_t* sys_tables; btr_pcur_t pcur; dict_index_t* sys_index; dtuple_t* tuple; mem_heap_t* heap; dfield_t* dfield; const rec_t* rec; const byte* field; ulint len; ulint err; const char* err_msg; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); heap = mem_heap_create(32000); mtr_start(&mtr); sys_tables = dict_table_get_low("SYS_TABLES"); sys_index = UT_LIST_GET_FIRST(sys_tables->indexes); ut_a(!dict_table_is_comp(sys_tables)); ut_a(name_of_col_is(sys_tables, sys_index, 3, "ID")); ut_a(name_of_col_is(sys_tables, sys_index, 4, "N_COLS")); ut_a(name_of_col_is(sys_tables, sys_index, 5, "TYPE")); ut_a(name_of_col_is(sys_tables, sys_index, 7, "MIX_LEN")); ut_a(name_of_col_is(sys_tables, sys_index, 9, "SPACE")); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); dfield_set_data(dfield, name, ut_strlen(name)); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur) || rec_get_deleted_flag(rec, 0)) { /* Not found */ err_exit: btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); return(NULL); } field = rec_get_nth_field_old(rec, 0, &len); /* Check if the table name in record is the searched one */ if (len != ut_strlen(name) || ut_memcmp(name, field, len) != 0) { goto err_exit; } err_msg = dict_load_table_low(name, rec, &table); if (err_msg) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: %s\n", err_msg); goto err_exit; } if (table->space == 0) { /* The system tablespace is always available. */ } else if (!fil_space_for_table_exists_in_mem( table->space, name, (table->flags >> DICT_TF2_SHIFT) & DICT_TF2_TEMPORARY, FALSE, FALSE)) { if (table->flags & (DICT_TF2_TEMPORARY << DICT_TF2_SHIFT)) { /* Do not bother to retry opening temporary tables. */ table->ibd_file_missing = TRUE; } else { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: error: space object of table "); ut_print_filename(stderr, name); fprintf(stderr, ",\n" "InnoDB: space id %lu did not exist in memory." " Retrying an open.\n", (ulong) table->space); /* Try to open the tablespace */ if (!fil_open_single_table_tablespace( TRUE, table->space, table->flags == DICT_TF_COMPACT ? 0 : table->flags & ~(~0 << DICT_TF_BITS), name)) { /* We failed to find a sensible tablespace file */ table->ibd_file_missing = TRUE; } } } btr_pcur_close(&pcur); mtr_commit(&mtr); dict_load_columns(table, heap); if (cached) { dict_table_add_to_cache(table, heap); } else { dict_table_add_system_columns(table, heap); } mem_heap_empty(heap); err = dict_load_indexes(table, heap, ignore_err); /* Initialize table foreign_child value. Its value could be changed when dict_load_foreigns() is called below */ table->fk_max_recusive_level = 0; /* If the force recovery flag is set, we open the table irrespective of the error condition, since the user may want to dump data from the clustered index. However we load the foreign key information only if all indexes were loaded. */ if (!cached) { } else if (err == DB_SUCCESS) { err = dict_load_foreigns(table->name, TRUE, TRUE); if (err != DB_SUCCESS) { dict_table_remove_from_cache(table); table = NULL; } else { table->fk_max_recusive_level = 0; } } else { dict_index_t* index; /* Make sure that at least the clustered index was loaded. Otherwise refuse to load the table */ index = dict_table_get_first_index(table); if (!srv_force_recovery || !index || !dict_index_is_clust(index)) { dict_table_remove_from_cache(table); table = NULL; } } #if 0 if (err != DB_SUCCESS && table != NULL) { mutex_enter(&dict_foreign_err_mutex); ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: could not make a foreign key" " definition to match\n" "InnoDB: the foreign key table" " or the referenced table!\n" "InnoDB: The data dictionary of InnoDB is corrupt." " You may need to drop\n" "InnoDB: and recreate the foreign key table" " or the referenced table.\n" "InnoDB: Submit a detailed bug report" " to http://bugs.mysql.com\n" "InnoDB: Latest foreign key error printout:\n%s\n", dict_foreign_err_buf); mutex_exit(&dict_foreign_err_mutex); } #endif /* 0 */ mem_heap_free(heap); return(table); } /***********************************************************************//** Loads a table object based on the table id. @return table; NULL if table does not exist */ UNIV_INTERN dict_table_t* dict_load_table_on_id( /*==================*/ table_id_t table_id) /*!< in: table id */ { byte id_buf[8]; btr_pcur_t pcur; mem_heap_t* heap; dtuple_t* tuple; dfield_t* dfield; dict_index_t* sys_table_ids; dict_table_t* sys_tables; const rec_t* rec; const byte* field; ulint len; dict_table_t* table; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); table = NULL; /* NOTE that the operation of this function is protected by the dictionary mutex, and therefore no deadlocks can occur with other dictionary operations. */ mtr_start(&mtr); /*---------------------------------------------------*/ /* Get the secondary index based on ID for table SYS_TABLES */ sys_tables = dict_sys->sys_tables; sys_table_ids = dict_table_get_next_index( dict_table_get_first_index(sys_tables)); ut_a(!dict_table_is_comp(sys_tables)); heap = mem_heap_create(256); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); /* Write the table id in byte format to id_buf */ mach_write_to_8(id_buf, table_id); dfield_set_data(dfield, id_buf, 8); dict_index_copy_types(tuple, sys_table_ids, 1); btr_pcur_open_on_user_rec(sys_table_ids, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur)) { /* Not found */ goto func_exit; } /* Find the first record that is not delete marked */ while (rec_get_deleted_flag(rec, 0)) { if (!btr_pcur_move_to_next_user_rec(&pcur, &mtr)) { goto func_exit; } rec = btr_pcur_get_rec(&pcur); } /*---------------------------------------------------*/ /* Now we have the record in the secondary index containing the table ID and NAME */ rec = btr_pcur_get_rec(&pcur); field = rec_get_nth_field_old(rec, 0, &len); ut_ad(len == 8); /* Check if the table id in record is the one searched for */ if (table_id != mach_read_from_8(field)) { goto func_exit; } /* Now we get the table name from the record */ field = rec_get_nth_field_old(rec, 1, &len); /* Load the table definition to memory */ table = dict_load_table(mem_heap_strdupl(heap, (char*) field, len), TRUE, DICT_ERR_IGNORE_NONE); func_exit: btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); return(table); } /********************************************************************//** This function is called when the database is booted. Loads system table index definitions except for the clustered index which is added to the dictionary cache at booting before calling this function. */ UNIV_INTERN void dict_load_sys_table( /*================*/ dict_table_t* table) /*!< in: system table */ { mem_heap_t* heap; ut_ad(mutex_own(&(dict_sys->mutex))); heap = mem_heap_create(1000); dict_load_indexes(table, heap, DICT_ERR_IGNORE_NONE); mem_heap_free(heap); } /********************************************************************//** Loads foreign key constraint col names (also for the referenced table). */ static void dict_load_foreign_cols( /*===================*/ const char* id, /*!< in: foreign constraint id as a null-terminated string */ dict_foreign_t* foreign)/*!< in: foreign constraint object */ { dict_table_t* sys_foreign_cols; dict_index_t* sys_index; btr_pcur_t pcur; dtuple_t* tuple; dfield_t* dfield; const rec_t* rec; const byte* field; ulint len; ulint i; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); foreign->foreign_col_names = mem_heap_alloc( foreign->heap, foreign->n_fields * sizeof(void*)); foreign->referenced_col_names = mem_heap_alloc( foreign->heap, foreign->n_fields * sizeof(void*)); mtr_start(&mtr); sys_foreign_cols = dict_table_get_low("SYS_FOREIGN_COLS"); sys_index = UT_LIST_GET_FIRST(sys_foreign_cols->indexes); ut_a(!dict_table_is_comp(sys_foreign_cols)); tuple = dtuple_create(foreign->heap, 1); dfield = dtuple_get_nth_field(tuple, 0); dfield_set_data(dfield, id, ut_strlen(id)); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); for (i = 0; i < foreign->n_fields; i++) { rec = btr_pcur_get_rec(&pcur); ut_a(btr_pcur_is_on_user_rec(&pcur)); ut_a(!rec_get_deleted_flag(rec, 0)); field = rec_get_nth_field_old(rec, 0, &len); ut_a(len == ut_strlen(id)); ut_a(ut_memcmp(id, field, len) == 0); field = rec_get_nth_field_old(rec, 1, &len); ut_a(len == 4); ut_a(i == mach_read_from_4(field)); field = rec_get_nth_field_old(rec, 4, &len); foreign->foreign_col_names[i] = mem_heap_strdupl( foreign->heap, (char*) field, len); field = rec_get_nth_field_old(rec, 5, &len); foreign->referenced_col_names[i] = mem_heap_strdupl( foreign->heap, (char*) field, len); btr_pcur_move_to_next_user_rec(&pcur, &mtr); } btr_pcur_close(&pcur); mtr_commit(&mtr); } /***********************************************************************//** Loads a foreign key constraint to the dictionary cache. @return DB_SUCCESS or error code */ static ulint dict_load_foreign( /*==============*/ const char* id, /*!< in: foreign constraint id as a null-terminated string */ ibool check_charsets, /*!< in: TRUE=check charset compatibility */ ibool check_recursive) /*!< in: Whether to record the foreign table parent count to avoid unlimited recursive load of chained foreign tables */ { dict_foreign_t* foreign; dict_table_t* sys_foreign; btr_pcur_t pcur; dict_index_t* sys_index; dtuple_t* tuple; mem_heap_t* heap2; dfield_t* dfield; const rec_t* rec; const byte* field; ulint len; ulint n_fields_and_type; mtr_t mtr; dict_table_t* for_table; dict_table_t* ref_table; ut_ad(mutex_own(&(dict_sys->mutex))); heap2 = mem_heap_create(1000); mtr_start(&mtr); sys_foreign = dict_table_get_low("SYS_FOREIGN"); sys_index = UT_LIST_GET_FIRST(sys_foreign->indexes); ut_a(!dict_table_is_comp(sys_foreign)); tuple = dtuple_create(heap2, 1); dfield = dtuple_get_nth_field(tuple, 0); dfield_set_data(dfield, id, ut_strlen(id)); dict_index_copy_types(tuple, sys_index, 1); btr_pcur_open_on_user_rec(sys_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur) || rec_get_deleted_flag(rec, 0)) { /* Not found */ fprintf(stderr, "InnoDB: Error A: cannot load foreign constraint %s\n", id); btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap2); return(DB_ERROR); } field = rec_get_nth_field_old(rec, 0, &len); /* Check if the id in record is the searched one */ if (len != ut_strlen(id) || ut_memcmp(id, field, len) != 0) { fprintf(stderr, "InnoDB: Error B: cannot load foreign constraint %s\n", id); btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap2); return(DB_ERROR); } /* Read the table names and the number of columns associated with the constraint */ mem_heap_free(heap2); foreign = dict_mem_foreign_create(); n_fields_and_type = mach_read_from_4( rec_get_nth_field_old(rec, 5, &len)); ut_a(len == 4); /* We store the type in the bits 24..29 of n_fields_and_type. */ foreign->type = (unsigned int) (n_fields_and_type >> 24); foreign->n_fields = (unsigned int) (n_fields_and_type & 0x3FFUL); foreign->id = mem_heap_strdup(foreign->heap, id); field = rec_get_nth_field_old(rec, 3, &len); foreign->foreign_table_name = mem_heap_strdupl( foreign->heap, (char*) field, len); dict_mem_foreign_table_name_lookup_set(foreign, TRUE); field = rec_get_nth_field_old(rec, 4, &len); foreign->referenced_table_name = mem_heap_strdupl( foreign->heap, (char*) field, len); dict_mem_referenced_table_name_lookup_set(foreign, TRUE); btr_pcur_close(&pcur); mtr_commit(&mtr); dict_load_foreign_cols(id, foreign); ref_table = dict_table_check_if_in_cache_low( foreign->referenced_table_name_lookup); /* We could possibly wind up in a deep recursive calls if we call dict_table_get_low() again here if there is a chain of tables concatenated together with foreign constraints. In such case, each table is both a parent and child of the other tables, and act as a "link" in such table chains. To avoid such scenario, we would need to check the number of ancesters the current table has. If that exceeds DICT_FK_MAX_CHAIN_LEN, we will stop loading the child table. Foreign constraints are loaded in a Breath First fashion, that is, the index on FOR_NAME is scanned first, and then index on REF_NAME. So foreign constrains in which current table is a child (foreign table) are loaded first, and then those constraints where current table is a parent (referenced) table. Thus we could check the parent (ref_table) table's reference count (fk_max_recusive_level) to know how deep the recursive call is. If the parent table (ref_table) is already loaded, and its fk_max_recusive_level is larger than DICT_FK_MAX_CHAIN_LEN, we will stop the recursive loading by skipping loading the child table. It will not affect foreign constraint check for DMLs since child table will be loaded at that time for the constraint check. */ if (!ref_table || ref_table->fk_max_recusive_level < DICT_FK_MAX_RECURSIVE_LOAD) { /* If the foreign table is not yet in the dictionary cache, we have to load it so that we are able to make type comparisons in the next function call. */ for_table = dict_table_get_low(foreign->foreign_table_name_lookup); if (for_table && ref_table && check_recursive) { /* This is to record the longest chain of ancesters this table has, if the parent has more ancesters than this table has, record it after add 1 (for this parent */ if (ref_table->fk_max_recusive_level >= for_table->fk_max_recusive_level) { for_table->fk_max_recusive_level = ref_table->fk_max_recusive_level + 1; } } } /* Note that there may already be a foreign constraint object in the dictionary cache for this constraint: then the following call only sets the pointers in it to point to the appropriate table and index objects and frees the newly created object foreign. Adding to the cache should always succeed since we are not creating a new foreign key constraint but loading one from the data dictionary. */ return(dict_foreign_add_to_cache(foreign, check_charsets)); } /***********************************************************************//** Loads foreign key constraints where the table is either the foreign key holder or where the table is referenced by a foreign key. Adds these constraints to the data dictionary. Note that we know that the dictionary cache already contains all constraints where the other relevant table is already in the dictionary cache. @return DB_SUCCESS or error code */ UNIV_INTERN ulint dict_load_foreigns( /*===============*/ const char* table_name, /*!< in: table name */ ibool check_recursive,/*!< in: Whether to check recursive load of tables chained by FK */ ibool check_charsets) /*!< in: TRUE=check charset compatibility */ { btr_pcur_t pcur; mem_heap_t* heap; dtuple_t* tuple; dfield_t* dfield; dict_index_t* sec_index; dict_table_t* sys_foreign; const rec_t* rec; const byte* field; ulint len; char* id ; ulint err; mtr_t mtr; ut_ad(mutex_own(&(dict_sys->mutex))); sys_foreign = dict_table_get_low("SYS_FOREIGN"); if (sys_foreign == NULL) { /* No foreign keys defined yet in this database */ fprintf(stderr, "InnoDB: Error: no foreign key system tables" " in the database\n"); return(DB_ERROR); } ut_a(!dict_table_is_comp(sys_foreign)); mtr_start(&mtr); /* Get the secondary index based on FOR_NAME from table SYS_FOREIGN */ sec_index = dict_table_get_next_index( dict_table_get_first_index(sys_foreign)); start_load: heap = mem_heap_create(256); tuple = dtuple_create(heap, 1); dfield = dtuple_get_nth_field(tuple, 0); dfield_set_data(dfield, table_name, ut_strlen(table_name)); dict_index_copy_types(tuple, sec_index, 1); btr_pcur_open_on_user_rec(sec_index, tuple, PAGE_CUR_GE, BTR_SEARCH_LEAF, &pcur, &mtr); loop: rec = btr_pcur_get_rec(&pcur); if (!btr_pcur_is_on_user_rec(&pcur)) { /* End of index */ goto load_next_index; } /* Now we have the record in the secondary index containing a table name and a foreign constraint ID */ rec = btr_pcur_get_rec(&pcur); field = rec_get_nth_field_old(rec, 0, &len); /* Check if the table name in the record is the one searched for; the following call does the comparison in the latin1_swedish_ci charset-collation, in a case-insensitive way. */ if (0 != cmp_data_data(dfield_get_type(dfield)->mtype, dfield_get_type(dfield)->prtype, dfield_get_data(dfield), dfield_get_len(dfield), field, len)) { goto load_next_index; } /* Since table names in SYS_FOREIGN are stored in a case-insensitive order, we have to check that the table name matches also in a binary string comparison. On Unix, MySQL allows table names that only differ in character case. If lower_case_table_names=2 then what is stored may not be the same case, but the previous comparison showed that they match with no-case. */ if ((innobase_get_lower_case_table_names() != 2) && (0 != ut_memcmp(field, table_name, len))) { goto next_rec; } if (rec_get_deleted_flag(rec, 0)) { goto next_rec; } /* Now we get a foreign key constraint id */ field = rec_get_nth_field_old(rec, 1, &len); id = mem_heap_strdupl(heap, (char*) field, len); btr_pcur_store_position(&pcur, &mtr); mtr_commit(&mtr); /* Load the foreign constraint definition to the dictionary cache */ err = dict_load_foreign(id, check_charsets, check_recursive); if (err != DB_SUCCESS) { btr_pcur_close(&pcur); mem_heap_free(heap); return(err); } mtr_start(&mtr); btr_pcur_restore_position(BTR_SEARCH_LEAF, &pcur, &mtr); next_rec: btr_pcur_move_to_next_user_rec(&pcur, &mtr); goto loop; load_next_index: btr_pcur_close(&pcur); mtr_commit(&mtr); mem_heap_free(heap); sec_index = dict_table_get_next_index(sec_index); if (sec_index != NULL) { mtr_start(&mtr); /* Switch to scan index on REF_NAME, fk_max_recusive_level already been updated when scanning FOR_NAME index, no need to update again */ check_recursive = FALSE; goto start_load; } return(DB_SUCCESS); }
cryptdb-org/mysql-5-5-14
storage/innobase/dict/dict0load.c
C
gpl-2.0
65,630
<html> <head> <title>A3 ALiVE</title> </head> <body> <h1>A3 ALiVE News</h1> <p> </p> <p> <br />Unable to retrieve the latest News Online!<br /><br /> <br /><a href="http://alivemod.com">Full Details</a> <br /></br ><br /> </p> <p> <br /> <br /> </p> </body> </html>
marceldev89/ALiVE.OS
addons/sys_newsfeed/newsfeed/news.html
HTML
gpl-2.0
265
<?php /* * * Copyright 2001, 2010 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun, Gabriel Fischer, Didier Blanqui * * This file is part of GEPI. * * GEPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GEPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GEPI; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // On empêche l'accès direct au fichier if (basename($_SERVER["SCRIPT_NAME"])==basename(__File__)){ die(); }; ?> <div id="result"> <div id="wrap" > <h3><font class="red">Bilans des incidents pour la période du: <?php echo $_SESSION['stats_periodes']['du'];?> au <?php echo $_SESSION['stats_periodes']['au'];?> </font> </h3> <?php ClassVue::afficheVue('parametres.php',$vars) ?> </div> <div id="tableaux"> <div id="banner"> <ul class="css-tabs" id="menutabs"> <?php $i=0; foreach ($incidents as $titre=>$incidents_titre) :?> <?php if($titre=='L\'Etablissement') { if($affichage_etab) : ?> <li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="Etablissement-onglet-01"><?php echo $titre;?></a></li> <li><a href="#tab<?php echo $i+1;?>" name="Etablissement-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a>&nbsp;&nbsp;</li> <?php $i=$i+2; endif; } else if ($titre=='Tous les élèves' ||$titre=='Tous les personnels' ) { ?> <li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="<?php echo $titre;?>-onglet-01"><?php echo $titre;?></a></li> <li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a>&nbsp;&nbsp;</li> <?php $i=$i+2; } else { ?> <li><a href="#tab<?php echo $i;?>" name="<?php echo $titre;?>-onglet-01" title="Bilan des incidents"> <?php if (isset($infos_individus[$titre])) { echo mb_substr($infos_individus[$titre]['prenom'],0,1).'.'.$infos_individus[$titre]['nom']; if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')'; } else echo $titre;?></a> </li> <?php if (isset($infos_individus[$titre]['classe'])|| !isset($infos_individus[$titre])) { ?> <li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse par élève" title="Synthèse par élève"/></a>&nbsp;&nbsp;</li> <?php $i=$i+2; } else { $i=$i+1; } } endforeach ?> </ul> </div> <div class="css-panes" id="containDiv"> <?php $i=0; foreach ($incidents as $titre=>$incidents_titre) { if ($titre!=='L\'Etablissement' || ($titre=='L\'Etablissement' && !is_null($affichage_etab) ) ) {?> <div class="panel" id="tab<?php echo $i;?>"> <?php if (isset($incidents_titre['error'])) {?> <table class="boireaus"> <tr ><td class="nouveau"><font class='titre'>Bilan des incidents concernant :</font> <?php if (isset($infos_individus[$titre])) { echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom']; if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')'; } else echo $titre;?> </td></tr> <tr><td class='nouveau'>Pas d'incidents avec les critères sélectionnés...</td></tr> </table><br /><br /> <?php echo'</div>';?> <?php if ($titre!=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels') {?> <div class="panel" id="tab<?php echo $i+1;?>"> <table class="boireaus"> <tr><td class="nouveau"><strong>Bilan individuel</strong> </td></tr> <tr><td class="nouveau">Pas d'incidents avec les critères sélectionnés...</td></tr> </table> </div> <?php $i=$i+2; } } else { ?> <table class="boireaus"> <tr > <td rowspan="6" colspan="5" class='nouveau'> <p><font class='titre'>Bilan des incidents concernant : </font> <?php if (isset($infos_individus[$titre])) { echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom']; if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')'; } else echo $titre;?> </p> <?php if($filtres_categories||$filtres_mesures||$filtres_roles||$filtres_sanctions) { ?><p>avec les filtres selectionnés</p><?php }?> </td> <td <?php if ($titre=='L\'Etablissement' ) {?> colspan="3" <?php }?> class='nouveau'><font class='titre'>Nombres d'incidents sur la période:</font> <?php echo $totaux[$titre]['incidents']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php echo round((100*($totaux[$titre]['incidents']/$totaux['L\'Etablissement']['incidents'])),2);?></td><?php } ?></tr> <tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures prises pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_prises']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_prises']) echo round((100*($totaux[$titre]['mesures_prises']/$totaux['L\'Etablissement']['mesures_prises'])),2); else echo'0';?></td><?php } ?></tr> <tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures demandées pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_demandees']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_demandees']) echo round((100*($totaux[$titre]['mesures_demandees']/$totaux['L\'Etablissement']['mesures_demandees'])),2); else echo'0';?></td><?php } ?></tr> <tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de sanctions prises pour ces incidents:</font> <?php echo $totaux[$titre]['sanctions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['sanctions']) echo round((100*($totaux[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions'])),2); else echo'0';?></td><?php } ?></tr> <tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total d'heures de retenues pour ces incidents:</font> <?php echo $totaux[$titre]['heures_retenues']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['heures_retenues']) echo round((100*($totaux[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues'])),2); else echo '0'; ?></td><?php } ?></tr> <tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de jours d'exclusions pour ces incidents:</font> <?php echo $totaux[$titre]['jours_exclusions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['jours_exclusions']) echo round((100*($totaux[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions'])),2); else echo '0'; ?></td><?php } ?></tr> </table> <?php if($mode_detaille) { ?> <table class="sortable resizable boireaus" id="table<?php echo $i;?>"> <thead> <tr><th><font class='titre'>Date</font></th><th class="text"><font class='titre'>Déclarant</font></th><th><font class='titre'>Heure</font></th><th class="text"><font class='titre'>Nature</font></th> <th><font class='titre' title="Catégories">Cat.</font></th><th class="text" ><font class='titre'>Description</font></th><th width="50%" class="nosort"><font class='titre'>Suivi</font></th></tr> </thead> <?php $alt_b=1; foreach($incidents_titre as $incident) { $alt_b=$alt_b*(-1);?> <tr class='lig<?php echo $alt_b;?>'><td><?php echo $incident->date; ?></td><td><?php echo $incident->declarant; ?></td><td><?php echo $incident->heure; ?></td> <td><?php echo $incident->nature; ?></td><td><?php if(!is_null($incident->id_categorie))echo $incident->sigle_categorie;else echo'-'; ?></td><td><?php echo $incident->description; ?></td> <td class="nouveau"><?php if(!isset($protagonistes[$incident->id_incident]))echo'<h3 class="red">Aucun protagoniste défini pour cet incident</h3>'; else { ?> <table class="boireaus" width="100%" > <?php foreach($protagonistes[$incident->id_incident] as $protagoniste) {?> <tr><td> <?php echo $protagoniste->prenom.' '.$protagoniste->nom.' <br/> '; echo $protagoniste->statut.' '; if($protagoniste->classe) echo $protagoniste->classe .' - '; else echo ' - ' ; if($protagoniste->qualite=="") echo'<font class="red">Aucun rôle affecté.</font><br />'; else echo $protagoniste->qualite.'<br />'; ?></td><td ><?php if (isset($mesures[$incident->id_incident][$protagoniste->login])) { ?> <p><strong>Mesures :</strong></p> <table class="boireaus" > <tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Mesure</font></th></tr> <?php $alt_c=1; foreach ($mesures[$incident->id_incident][$protagoniste->login] as $mesure) { $alt_c=$alt_c*(-1); ?> <tr class="lig<?php echo $alt_c;?>"><td><?php echo $mesure->mesure; ?></td> <td><?php echo $mesure->type.' par '.$mesure->login_u; ?></td></tr> <?php } ?> </table> <?php } if (isset($sanctions[$incident->id_incident][$protagoniste->login])) { ?> <p><strong>Sanctions :</strong></p> <table class="boireaus" width="100%"> <tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Effectuée</font></th><th><font class='titre'>Date</font></th> <th><font class='titre'>Durée</font></th> </tr> <?php $alt_d=1; foreach ($sanctions[$incident->id_incident][$protagoniste->login] as $sanction) { $alt_d=$alt_d*(-1); ?> <tr class="lig<?php echo $alt_d;?>"><td><?php echo $sanction->nature; ?></td> <td><?php echo $sanction->effectuee; ?></td> <td><?php if($sanction->nature=='retenue')echo $sanction->ret_date; if($sanction->nature=='exclusion')echo 'Du '.$sanction->exc_date_debut.' au '.$sanction->exc_date_fin; if($sanction->nature=='travail')echo 'Pour le '.$sanction->trv_date_retour;?> </td> <td><?php if($sanction->nature=='retenue') { echo $sanction->ret_duree.' heure'; if ($sanction->ret_duree >1) echo 's'; }else if($sanction->nature=='exclusion') { echo $sanction->exc_duree.' jour'; if ($sanction->exc_duree >1) echo 's'; }else{ echo'-'; } ?> </td> </tr> <?php } ?> </table> <?php } ?> </td></tr> <?php } ?></table> <?php } ?></td></tr> <?php } }?> </table> <br /><br /><a href="#wrap"><img src="apps/img/retour_haut.png" alt="simple" title="simplifié"/>Retour aux selections </a> </div> <?php if (isset($liste_eleves[$titre])): ?> <div class="panel" id="tab<?php echo $i+1;?>"> <table class="boireaus"> <tr><td class="nouveau" colspan="11"><strong>Bilan individuel</strong></td><td><a href="#" class="export_csv" name="<?php echo $temp_dir.'/separateur/'.$titre;?>"><img src="../../images/notes_app_csv.png" alt="export_csv"/></a></td></tr></table> <table class="sortable resizable "> <thead> <tr> <?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?> <th colspan="3" <?php } else { ?> <th colspan="2" <?php } ?> <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Individu</th> <th >Incidents</th><th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Mesures prises</th> <th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Sanctions prises</th> <th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Heures de retenues</th> <th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Jours d'exclusion</th> </tr> <tr> <th>Nom</th><th>Prénom</th> <?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?> <th class="text">Classe</th> <?php } ?> <th>Nombre</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th> </tr> </thead> <tbody> <?php $alt_b=1; foreach ($liste_eleves[$titre] as $eleve) { $alt_b=$alt_b*(-1);?> <tr <?php if ($alt_b==1) echo"class='alt'";?>> <td><a href="index.php?ctrl=Bilans&action=add_selection&login=<?php echo $eleve?>"><?php echo $totaux_indiv[$eleve]['nom']; ?></a></td> <td><?php // 20200718 echo "<span style='display:none'>".$totaux_indiv[$eleve]['prenom']."</span>"; echo "<div style='float:right; width:16px; margin-left:3px;'> <a href='../../eleves/visu_eleve.php?ele_login=".$eleve."&onglet=discipline' target='_blank' title=\"Voir la fiche élève dans un nouvel onglet.\"><img src='../../images/icons/ele_onglets.png' class='icone16' /></a> </div>"; echo $totaux_indiv[$eleve]['prenom']; ?> </td> <?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?> <td><?php echo $totaux_indiv[$eleve]['classe']; ?></td> <?php } ?> <td><?php echo $totaux_indiv[$eleve]['incidents']; ?></td><td><?php if(isset($totaux_indiv[$eleve]['mesures'])) echo $totaux_indiv[$eleve]['mesures'];else echo'0'; ?></td><td><?php if($totaux['L\'Etablissement']['mesures_prises'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2)); else echo'0';?></td> <td><?php if(isset($totaux_indiv[$eleve]['sanctions'])) echo $totaux_indiv[$eleve]['sanctions']; else echo '0';?></td><td><?php if($totaux['L\'Etablissement']['sanctions']) echo str_replace(",",".",round(100* ($totaux_indiv[$eleve]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2)); else echo'0';?></td> <td><?php if(isset($totaux_indiv[$eleve]['heures_retenues'])) echo $totaux_indiv[$eleve]['heures_retenues'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['heures_retenues'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2));else echo'0';?></td> <td><?php if(isset($totaux_indiv[$eleve]['jours_exclusions'])) echo $totaux_indiv[$eleve]['jours_exclusions'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['jours_exclusions'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2));else echo'0';?></td></tr> <?php }?> </tbody> <?php if (!isset($totaux_indiv[$titre])) { ?> <tfoot> <tr> <?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?> <td colspan="3"> <?php } else{ ?> <td colspan="2"> <?php } ?> Total</td> <td><?php if(isset($totaux_par_classe[$titre]['incidents']))echo $totaux_par_classe[$titre]['incidents']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises'])) echo $totaux_par_classe[$titre]['mesures']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises']) && $totaux['L\'Etablissement']['mesures_prises']>0) echo round(100*($totaux_par_classe[$titre]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2); else echo'0';?></td> <td><?php if(isset($totaux_par_classe[$titre]['sanctions'])) echo $totaux_par_classe[$titre]['sanctions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['sanctions']) && $totaux['L\'Etablissement']['sanctions']>0) echo round(100*($totaux_par_classe[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2); else echo'0';?></td> <td><?php if(isset($totaux_par_classe[$titre]['heures_retenues'])) echo $totaux_par_classe[$titre]['heures_retenues']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['heures_retenues']) && $totaux['L\'Etablissement']['heures_retenues']>0) echo round(100*($totaux_par_classe[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2); else echo'0';?></td> <td><?php if(isset($totaux_par_classe[$titre]['jours_exclusions'])) echo $totaux_par_classe[$titre]['jours_exclusions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['jours_exclusions']) && $totaux['L\'Etablissement']['jours_exclusions']>0) echo round(100*($totaux_par_classe[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2);else echo'0';?></td> </tr> </tfoot> <?php }?> </table> </div> <?php $i=$i+2; else : $i=$i+1; endif; } } }?> </div> </div> </div>
tbelliard/gepi
mod_discipline/stats2/apps/vues/bilans.php
PHP
gpl-2.0
21,097
/* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */ /* * Copyright 2010 by Eric House ([email protected]). All rights * reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.oliversride.wordryo; import junit.framework.Assert; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; public class XWActivity extends Activity implements DlgDelegate.DlgClickNotify, MultiService.MultiEventListener { private final static String TAG = "XWActivity"; private DlgDelegate m_delegate; @Override protected void onCreate( Bundle savedInstanceState ) { DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this ); super.onCreate( savedInstanceState ); m_delegate = new DlgDelegate( this, this, savedInstanceState ); } @Override protected void onStart() { DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this ); super.onStart(); } @Override protected void onResume() { DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this ); BTService.setListener( this ); SMSService.setListener( this ); super.onResume(); } @Override protected void onPause() { DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this ); BTService.setListener( null ); SMSService.setListener( null ); super.onPause(); } @Override protected void onStop() { DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this ); super.onStop(); } @Override protected void onDestroy() { DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b", getClass().getName(), this, isFinishing() ); super.onDestroy(); } @Override protected void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); m_delegate.onSaveInstanceState( outState ); } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = super.onCreateDialog( id ); if ( null == dialog ) { DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() ); dialog = m_delegate.onCreateDialog( id ); } return dialog; } // these are duplicated in XWListActivity -- sometimes multiple // inheritance would be nice to have... protected void showAboutDialog() { m_delegate.showAboutDialog(); } protected void showNotAgainDlgThen( int msgID, int prefsKey, int action ) { m_delegate.showNotAgainDlgThen( msgID, prefsKey, action ); } protected void showNotAgainDlgThen( int msgID, int prefsKey ) { m_delegate.showNotAgainDlgThen( msgID, prefsKey ); } protected void showOKOnlyDialog( int msgID ) { m_delegate.showOKOnlyDialog( msgID ); } protected void showOKOnlyDialog( String msg ) { m_delegate.showOKOnlyDialog( msg ); } protected void showDictGoneFinish() { m_delegate.showDictGoneFinish(); } protected void showConfirmThen( int msgID, int action ) { m_delegate.showConfirmThen( getString(msgID), action ); } protected void showConfirmThen( String msg, int action ) { m_delegate.showConfirmThen( msg, action ); } protected void showConfirmThen( int msg, int posButton, int action ) { m_delegate.showConfirmThen( getString(msg), posButton, action ); } public void showEmailOrSMSThen( int action ) { m_delegate.showEmailOrSMSThen( action ); } protected void doSyncMenuitem() { m_delegate.doSyncMenuitem(); } protected void launchLookup( String[] words, int lang ) { m_delegate.launchLookup( words, lang, false ); } protected void startProgress( int id ) { m_delegate.startProgress( id ); } protected void stopProgress() { m_delegate.stopProgress(); } protected boolean post( Runnable runnable ) { return m_delegate.post( runnable ); } // DlgDelegate.DlgClickNotify interface public void dlgButtonClicked( int id, int which ) { Assert.fail(); } // BTService.MultiEventListener interface public void eventOccurred( MultiService.MultiEvent event, final Object ... args ) { m_delegate.eventOccurred( event, args ); } }
oliversride/Wordryo
src/main/java/com/oliversride/wordryo/XWActivity.java
Java
gpl-2.0
5,258
<?php /** * Twenty Fifteen Customizer functionality * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ /** * Add postMessage support for site title and description for the Customizer. * * @since Twenty Fifteen 1.0 * * @param WP_Customize_Manager $wp_customize * Customizer object. */ function twentyfifteen_customize_register($wp_customize) { $color_scheme = twentyfifteen_get_color_scheme (); $wp_customize->get_setting ( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting ( 'blogdescription' )->transport = 'postMessage'; // Add color scheme setting and control. $wp_customize->add_setting ( 'color_scheme', array ( 'default' => 'default', 'sanitize_callback' => 'twentyfifteen_sanitize_color_scheme', 'transport' => 'postMessage' ) ); $wp_customize->add_control ( 'color_scheme', array ( 'label' => __ ( 'Base Color Scheme', 'twentyfifteen' ), 'section' => 'colors', 'type' => 'select', 'choices' => twentyfifteen_get_color_scheme_choices (), 'priority' => 1 ) ); // Add custom header and sidebar text color setting and control. $wp_customize->add_setting ( 'sidebar_textcolor', array ( 'default' => $color_scheme [4], 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage' ) ); $wp_customize->add_control ( new WP_Customize_Color_Control ( $wp_customize, 'sidebar_textcolor', array ( 'label' => __ ( 'Header and Sidebar Text Color', 'twentyfifteen' ), 'description' => __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' ), 'section' => 'colors' ) ) ); // Remove the core header textcolor control, as it shares the sidebar text color. $wp_customize->remove_control ( 'header_textcolor' ); // Add custom header and sidebar background color setting and control. $wp_customize->add_setting ( 'header_background_color', array ( 'default' => $color_scheme [1], 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage' ) ); $wp_customize->add_control ( new WP_Customize_Color_Control ( $wp_customize, 'header_background_color', array ( 'label' => __ ( 'Header and Sidebar Background Color', 'twentyfifteen' ), 'description' => __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' ), 'section' => 'colors' ) ) ); // Add an additional description to the header image section. $wp_customize->get_section ( 'header_image' )->description = __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' ); } add_action ( 'customize_register', 'twentyfifteen_customize_register', 11 ); /** * Register color schemes for Twenty Fifteen. * * Can be filtered with {@see 'twentyfifteen_color_schemes'}. * * The order of colors in a colors array: * 1. Main Background Color. * 2. Sidebar Background Color. * 3. Box Background Color. * 4. Main Text and Link Color. * 5. Sidebar Text and Link Color. * 6. Meta Box Background Color. * * @since Twenty Fifteen 1.0 * * @return array An associative array of color scheme options. */ function twentyfifteen_get_color_schemes() { return apply_filters ( 'twentyfifteen_color_schemes', array ( 'default' => array ( 'label' => __ ( 'Default', 'twentyfifteen' ), 'colors' => array ( '#f1f1f1', '#ffffff', '#ffffff', '#333333', '#333333', '#f7f7f7' ) ), 'dark' => array ( 'label' => __ ( 'Dark', 'twentyfifteen' ), 'colors' => array ( '#111111', '#202020', '#202020', '#bebebe', '#bebebe', '#1b1b1b' ) ), 'yellow' => array ( 'label' => __ ( 'Yellow', 'twentyfifteen' ), 'colors' => array ( '#f4ca16', '#ffdf00', '#ffffff', '#111111', '#111111', '#f1f1f1' ) ), 'pink' => array ( 'label' => __ ( 'Pink', 'twentyfifteen' ), 'colors' => array ( '#ffe5d1', '#e53b51', '#ffffff', '#352712', '#ffffff', '#f1f1f1' ) ), 'purple' => array ( 'label' => __ ( 'Purple', 'twentyfifteen' ), 'colors' => array ( '#674970', '#2e2256', '#ffffff', '#2e2256', '#ffffff', '#f1f1f1' ) ), 'blue' => array ( 'label' => __ ( 'Blue', 'twentyfifteen' ), 'colors' => array ( '#e9f2f9', '#55c3dc', '#ffffff', '#22313f', '#ffffff', '#f1f1f1' ) ) ) ); } if (! function_exists ( 'twentyfifteen_get_color_scheme' )) : /** * Get the current Twenty Fifteen color scheme. * * @since Twenty Fifteen 1.0 * * @return array An associative array of either the current or default color scheme hex values. */ function twentyfifteen_get_color_scheme() { $color_scheme_option = get_theme_mod ( 'color_scheme', 'default' ); $color_schemes = twentyfifteen_get_color_schemes (); if (array_key_exists ( $color_scheme_option, $color_schemes )) { return $color_schemes [$color_scheme_option] ['colors']; } return $color_schemes ['default'] ['colors']; } endif; // twentyfifteen_get_color_scheme if (! function_exists ( 'twentyfifteen_get_color_scheme_choices' )) : /** * Returns an array of color scheme choices registered for Twenty Fifteen. * * @since Twenty Fifteen 1.0 * * @return array Array of color schemes. */ function twentyfifteen_get_color_scheme_choices() { $color_schemes = twentyfifteen_get_color_schemes (); $color_scheme_control_options = array (); foreach ( $color_schemes as $color_scheme => $value ) { $color_scheme_control_options [$color_scheme] = $value ['label']; } return $color_scheme_control_options; } endif; // twentyfifteen_get_color_scheme_choices if (! function_exists ( 'twentyfifteen_sanitize_color_scheme' )) : /** * Sanitization callback for color schemes. * * @since Twenty Fifteen 1.0 * * @param string $value * Color scheme name value. * @return string Color scheme name. */ function twentyfifteen_sanitize_color_scheme($value) { $color_schemes = twentyfifteen_get_color_scheme_choices (); if (! array_key_exists ( $value, $color_schemes )) { $value = 'default'; } return $value; } endif; // twentyfifteen_sanitize_color_scheme /** * Enqueues front-end CSS for color scheme. * * @since Twenty Fifteen 1.0 * * @see wp_add_inline_style() */ function twentyfifteen_color_scheme_css() { $color_scheme_option = get_theme_mod ( 'color_scheme', 'default' ); // Don't do anything if the default color scheme is selected. if ('default' === $color_scheme_option) { return; } $color_scheme = twentyfifteen_get_color_scheme (); // Convert main and sidebar text hex color to rgba. $color_textcolor_rgb = twentyfifteen_hex2rgb ( $color_scheme [3] ); $color_sidebar_textcolor_rgb = twentyfifteen_hex2rgb ( $color_scheme [4] ); $colors = array ( 'background_color' => $color_scheme [0], 'header_background_color' => $color_scheme [1], 'box_background_color' => $color_scheme [2], 'textcolor' => $color_scheme [3], 'secondary_textcolor' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.7)', $color_textcolor_rgb ), 'border_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.1)', $color_textcolor_rgb ), 'border_focus_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.3)', $color_textcolor_rgb ), 'sidebar_textcolor' => $color_scheme [4], 'sidebar_border_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.1)', $color_sidebar_textcolor_rgb ), 'sidebar_border_focus_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.3)', $color_sidebar_textcolor_rgb ), 'secondary_sidebar_textcolor' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.7)', $color_sidebar_textcolor_rgb ), 'meta_box_background_color' => $color_scheme [5] ); $color_scheme_css = twentyfifteen_get_color_scheme_css ( $colors ); wp_add_inline_style ( 'twentyfifteen-style', $color_scheme_css ); } add_action ( 'wp_enqueue_scripts', 'twentyfifteen_color_scheme_css' ); /** * Binds JS listener to make Customizer color_scheme control. * * Passes color scheme data as colorScheme global. * * @since Twenty Fifteen 1.0 */ function twentyfifteen_customize_control_js() { wp_enqueue_script ( 'color-scheme-control', get_template_directory_uri () . '/js/color-scheme-control.js', array ( 'customize-controls', 'iris', 'underscore', 'wp-util' ), '20141216', true ); wp_localize_script ( 'color-scheme-control', 'colorScheme', twentyfifteen_get_color_schemes () ); } add_action ( 'customize_controls_enqueue_scripts', 'twentyfifteen_customize_control_js' ); /** * Binds JS handlers to make the Customizer preview reload changes asynchronously. * * @since Twenty Fifteen 1.0 */ function twentyfifteen_customize_preview_js() { wp_enqueue_script ( 'twentyfifteen-customize-preview', get_template_directory_uri () . '/js/customize-preview.js', array ( 'customize-preview' ), '20141216', true ); } add_action ( 'customize_preview_init', 'twentyfifteen_customize_preview_js' ); /** * Returns CSS for the color schemes. * * @since Twenty Fifteen 1.0 * * @param array $colors * Color scheme colors. * @return string Color scheme CSS. */ function twentyfifteen_get_color_scheme_css($colors) { $colors = wp_parse_args ( $colors, array ( 'background_color' => '', 'header_background_color' => '', 'box_background_color' => '', 'textcolor' => '', 'secondary_textcolor' => '', 'border_color' => '', 'border_focus_color' => '', 'sidebar_textcolor' => '', 'sidebar_border_color' => '', 'sidebar_border_focus_color' => '', 'secondary_sidebar_textcolor' => '', 'meta_box_background_color' => '' ) ); $css = <<<CSS /* Color Scheme */ /* Background Color */ body { background-color: {$colors['background_color']}; } /* Sidebar Background Color */ body:before, .site-header { background-color: {$colors['header_background_color']}; } /* Box Background Color */ .post-navigation, .pagination, .secondary, .site-footer, .hentry, .page-header, .page-content, .comments-area, .widecolumn { background-color: {$colors['box_background_color']}; } /* Box Background Color */ button, input[type="button"], input[type="reset"], input[type="submit"], .pagination .prev, .pagination .next, .widget_calendar tbody a, .widget_calendar tbody a:hover, .widget_calendar tbody a:focus, .page-links a, .page-links a:hover, .page-links a:focus, .sticky-post { color: {$colors['box_background_color']}; } /* Main Text Color */ button, input[type="button"], input[type="reset"], input[type="submit"], .pagination .prev, .pagination .next, .widget_calendar tbody a, .page-links a, .sticky-post { background-color: {$colors['textcolor']}; } /* Main Text Color */ body, blockquote cite, blockquote small, a, .dropdown-toggle:after, .image-navigation a:hover, .image-navigation a:focus, .comment-navigation a:hover, .comment-navigation a:focus, .widget-title, .entry-footer a:hover, .entry-footer a:focus, .comment-metadata a:hover, .comment-metadata a:focus, .pingback .edit-link a:hover, .pingback .edit-link a:focus, .comment-list .reply a:hover, .comment-list .reply a:focus, .site-info a:hover, .site-info a:focus { color: {$colors['textcolor']}; } /* Main Text Color */ .entry-content a, .entry-summary a, .page-content a, .comment-content a, .pingback .comment-body > a, .author-description a, .taxonomy-description a, .textwidget a, .entry-footer a:hover, .comment-metadata a:hover, .pingback .edit-link a:hover, .comment-list .reply a:hover, .site-info a:hover { border-color: {$colors['textcolor']}; } /* Secondary Text Color */ button:hover, button:focus, input[type="button"]:hover, input[type="button"]:focus, input[type="reset"]:hover, input[type="reset"]:focus, input[type="submit"]:hover, input[type="submit"]:focus, .pagination .prev:hover, .pagination .prev:focus, .pagination .next:hover, .pagination .next:focus, .widget_calendar tbody a:hover, .widget_calendar tbody a:focus, .page-links a:hover, .page-links a:focus { background-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ background-color: {$colors['secondary_textcolor']}; } /* Secondary Text Color */ blockquote, a:hover, a:focus, .main-navigation .menu-item-description, .post-navigation .meta-nav, .post-navigation a:hover .post-title, .post-navigation a:focus .post-title, .image-navigation, .image-navigation a, .comment-navigation, .comment-navigation a, .widget, .author-heading, .entry-footer, .entry-footer a, .taxonomy-description, .page-links > .page-links-title, .entry-caption, .comment-author, .comment-metadata, .comment-metadata a, .pingback .edit-link, .pingback .edit-link a, .post-password-form label, .comment-form label, .comment-notes, .comment-awaiting-moderation, .logged-in-as, .form-allowed-tags, .no-comments, .site-info, .site-info a, .wp-caption-text, .gallery-caption, .comment-list .reply a, .widecolumn label, .widecolumn .mu_register label { color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ color: {$colors['secondary_textcolor']}; } /* Secondary Text Color */ blockquote, .logged-in-as a:hover, .comment-author a:hover { border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ border-color: {$colors['secondary_textcolor']}; } /* Border Color */ hr, .dropdown-toggle:hover, .dropdown-toggle:focus { background-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ background-color: {$colors['border_color']}; } /* Border Color */ pre, abbr[title], table, th, td, input, textarea, .main-navigation ul, .main-navigation li, .post-navigation, .post-navigation div + div, .pagination, .comment-navigation, .widget li, .widget_categories .children, .widget_nav_menu .sub-menu, .widget_pages .children, .site-header, .site-footer, .hentry + .hentry, .author-info, .entry-content .page-links a, .page-links > span, .page-header, .comments-area, .comment-list + .comment-respond, .comment-list article, .comment-list .pingback, .comment-list .trackback, .comment-list .reply a, .no-comments { border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ border-color: {$colors['border_color']}; } /* Border Focus Color */ a:focus, button:focus, input:focus { outline-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ outline-color: {$colors['border_focus_color']}; } input:focus, textarea:focus { border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */ border-color: {$colors['border_focus_color']}; } /* Sidebar Link Color */ .secondary-toggle:before { color: {$colors['sidebar_textcolor']}; } .site-title a, .site-description { color: {$colors['sidebar_textcolor']}; } /* Sidebar Text Color */ .site-title a:hover, .site-title a:focus { color: {$colors['secondary_sidebar_textcolor']}; } /* Sidebar Border Color */ .secondary-toggle { border-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */ border-color: {$colors['sidebar_border_color']}; } /* Sidebar Border Focus Color */ .secondary-toggle:hover, .secondary-toggle:focus { border-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */ border-color: {$colors['sidebar_border_focus_color']}; } .site-title a { outline-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */ outline-color: {$colors['sidebar_border_focus_color']}; } /* Meta Background Color */ .entry-footer { background-color: {$colors['meta_box_background_color']}; } @media screen and (min-width: 38.75em) { /* Main Text Color */ .page-header { border-color: {$colors['textcolor']}; } } @media screen and (min-width: 59.6875em) { /* Make sure its transparent on desktop */ .site-header, .secondary { background-color: transparent; } /* Sidebar Background Color */ .widget button, .widget input[type="button"], .widget input[type="reset"], .widget input[type="submit"], .widget_calendar tbody a, .widget_calendar tbody a:hover, .widget_calendar tbody a:focus { color: {$colors['header_background_color']}; } /* Sidebar Link Color */ .secondary a, .dropdown-toggle:after, .widget-title, .widget blockquote cite, .widget blockquote small { color: {$colors['sidebar_textcolor']}; } .widget button, .widget input[type="button"], .widget input[type="reset"], .widget input[type="submit"], .widget_calendar tbody a { background-color: {$colors['sidebar_textcolor']}; } .textwidget a { border-color: {$colors['sidebar_textcolor']}; } /* Sidebar Text Color */ .secondary a:hover, .secondary a:focus, .main-navigation .menu-item-description, .widget, .widget blockquote, .widget .wp-caption-text, .widget .gallery-caption { color: {$colors['secondary_sidebar_textcolor']}; } .widget button:hover, .widget button:focus, .widget input[type="button"]:hover, .widget input[type="button"]:focus, .widget input[type="reset"]:hover, .widget input[type="reset"]:focus, .widget input[type="submit"]:hover, .widget input[type="submit"]:focus, .widget_calendar tbody a:hover, .widget_calendar tbody a:focus { background-color: {$colors['secondary_sidebar_textcolor']}; } .widget blockquote { border-color: {$colors['secondary_sidebar_textcolor']}; } /* Sidebar Border Color */ .main-navigation ul, .main-navigation li, .widget input, .widget textarea, .widget table, .widget th, .widget td, .widget pre, .widget li, .widget_categories .children, .widget_nav_menu .sub-menu, .widget_pages .children, .widget abbr[title] { border-color: {$colors['sidebar_border_color']}; } .dropdown-toggle:hover, .dropdown-toggle:focus, .widget hr { background-color: {$colors['sidebar_border_color']}; } .widget input:focus, .widget textarea:focus { border-color: {$colors['sidebar_border_focus_color']}; } .sidebar a:focus, .dropdown-toggle:focus { outline-color: {$colors['sidebar_border_focus_color']}; } } CSS; return $css; } /** * Output an Underscore template for generating CSS for the color scheme. * * The template generates the css dynamically for instant display in the Customizer * preview. * * @since Twenty Fifteen 1.0 */ function twentyfifteen_color_scheme_css_template() { $colors = array ( 'background_color' => '{{ data.background_color }}', 'header_background_color' => '{{ data.header_background_color }}', 'box_background_color' => '{{ data.box_background_color }}', 'textcolor' => '{{ data.textcolor }}', 'secondary_textcolor' => '{{ data.secondary_textcolor }}', 'border_color' => '{{ data.border_color }}', 'border_focus_color' => '{{ data.border_focus_color }}', 'sidebar_textcolor' => '{{ data.sidebar_textcolor }}', 'sidebar_border_color' => '{{ data.sidebar_border_color }}', 'sidebar_border_focus_color' => '{{ data.sidebar_border_focus_color }}', 'secondary_sidebar_textcolor' => '{{ data.secondary_sidebar_textcolor }}', 'meta_box_background_color' => '{{ data.meta_box_background_color }}' ); ?> <script type="text/html" id="tmpl-twentyfifteen-color-scheme"> <?php echo twentyfifteen_get_color_scheme_css( $colors ); ?> </script> <?php } add_action ( 'customize_controls_print_footer_scripts', 'twentyfifteen_color_scheme_css_template' );
AgnaldoJaws/On-The-Bass.
wp-content/themes/twentyfifteen/inc/customizer.php
PHP
gpl-2.0
19,694
<?php //$Id: mod_form.php,v 1.2.2.3 2009/03/19 12:23:11 mudrd8mz Exp $ /** * This file defines the main deva configuration form * It uses the standard core Moodle (>1.8) formslib. For * more info about them, please visit: * * http://docs.moodle.org/en/Development:lib/formslib.php * * The form must provide support for, at least these fields: * - name: text element of 64cc max * * Also, it's usual to use these fields: * - intro: one htmlarea element to describe the activity * (will be showed in the list of activities of * deva type (index.php) and in the header * of the deva main page (view.php). * - introformat: The format used to write the contents * of the intro field. It automatically defaults * to HTML when the htmleditor is used and can be * manually selected if the htmleditor is not used * (standard formats are: MOODLE, HTML, PLAIN, MARKDOWN) * See lib/weblib.php Constants and the format_text() * function for more info */ require_once($CFG->dirroot.'/course/moodleform_mod.php'); class mod_deva_mod_form extends moodleform_mod { function definition() { global $COURSE; $mform =& $this->_form; //------------------------------------------------------------------------------- /// Adding the "general" fieldset, where all the common settings are showed $mform->addElement('header', 'general', get_string('general', 'form')); /// Adding the standard "name" field $mform->addElement('text', 'name', get_string('devaname', 'deva'), array('size'=>'64')); $mform->setType('name', PARAM_TEXT); $mform->addRule('name', null, 'required', null, 'client'); $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); /// Adding the required "intro" field to hold the description of the instance $mform->addElement('htmleditor', 'intro', get_string('devaintro', 'deva')); $mform->setType('intro', PARAM_RAW); $mform->addRule('intro', get_string('required'), 'required', null, 'client'); $mform->setHelpButton('intro', array('writing', 'richtext'), false, 'editorhelpbutton'); /// Adding "introformat" field $mform->addElement('format', 'introformat', get_string('format')); //------------------------------------------------------------------------------- /// Adding the rest of deva settings, spreeading all them into this fieldset /// or adding more fieldsets ('header' elements) if needed for better logic $mform->addElement('static', 'label1', 'devasetting1', 'Your deva fields go here. Replace me!'); $mform->addElement('header', 'devafieldset', get_string('devafieldset', 'deva')); $mform->addElement('static', 'label2', 'devasetting2', 'Your deva fields go here. Replace me!'); //------------------------------------------------------------------------------- // add standard elements, common to all modules $this->standard_coursemodule_elements(); //------------------------------------------------------------------------------- // add standard buttons, common to all modules $this->add_action_buttons(); } } ?>
IT-Scholars/Moodle-ITScholars-LMS
mod/deva/mod_form.php
PHP
gpl-2.0
3,290
/* arch/arm/mach-rk29/vpu.c * * Copyright (C) 2010 ROCKCHIP, Inc. * author: chenhengming [email protected] * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/ioport.h> #include <linux/miscdevice.h> #include <linux/mm.h> #include <linux/poll.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/wakelock.h> #include <linux/cdev.h> #include <linux/of.h> #include <linux/rockchip/cpu.h> #include <linux/rockchip/cru.h> #include <asm/cacheflush.h> #include <asm/uaccess.h> #if defined(CONFIG_ION_ROCKCHIP) #include <linux/rockchip_ion.h> #endif //#define CONFIG_VCODEC_MMU #ifdef CONFIG_VCODEC_MMU #include <linux/rockchip/iovmm.h> #include <linux/rockchip/sysmmu.h> #include <linux/dma-buf.h> #endif #ifdef CONFIG_DEBUG_FS #include <linux/debugfs.h> #endif #if defined(CONFIG_ARCH_RK319X) #include <mach/grf.h> #endif #include "vcodec_service.h" #define HEVC_TEST_ENABLE 0 #define HEVC_SIM_ENABLE 0 #define VCODEC_CLOCK_ENABLE 1 typedef enum { VPU_DEC_ID_9190 = 0x6731, VPU_ID_8270 = 0x8270, VPU_ID_4831 = 0x4831, HEVC_ID = 0x6867, } VPU_HW_ID; typedef enum { VPU_DEC_TYPE_9190 = 0, VPU_ENC_TYPE_8270 = 0x100, VPU_ENC_TYPE_4831 , } VPU_HW_TYPE_E; typedef enum VPU_FREQ { VPU_FREQ_200M, VPU_FREQ_266M, VPU_FREQ_300M, VPU_FREQ_400M, VPU_FREQ_500M, VPU_FREQ_600M, VPU_FREQ_DEFAULT, VPU_FREQ_BUT, } VPU_FREQ; typedef struct { VPU_HW_ID hw_id; unsigned long hw_addr; unsigned long enc_offset; unsigned long enc_reg_num; unsigned long enc_io_size; unsigned long dec_offset; unsigned long dec_reg_num; unsigned long dec_io_size; } VPU_HW_INFO_E; #define VPU_SERVICE_SHOW_TIME 0 #if VPU_SERVICE_SHOW_TIME static struct timeval enc_start, enc_end; static struct timeval dec_start, dec_end; static struct timeval pp_start, pp_end; #endif #define MHZ (1000*1000) #define REG_NUM_9190_DEC (60) #define REG_NUM_9190_PP (41) #define REG_NUM_9190_DEC_PP (REG_NUM_9190_DEC+REG_NUM_9190_PP) #define REG_NUM_DEC_PP (REG_NUM_9190_DEC+REG_NUM_9190_PP) #define REG_NUM_ENC_8270 (96) #define REG_SIZE_ENC_8270 (0x200) #define REG_NUM_ENC_4831 (164) #define REG_SIZE_ENC_4831 (0x400) #define REG_NUM_HEVC_DEC (68) #define SIZE_REG(reg) ((reg)*4) static VPU_HW_INFO_E vpu_hw_set[] = { [0] = { .hw_id = VPU_ID_8270, .hw_addr = 0, .enc_offset = 0x0, .enc_reg_num = REG_NUM_ENC_8270, .enc_io_size = REG_NUM_ENC_8270 * 4, .dec_offset = REG_SIZE_ENC_8270, .dec_reg_num = REG_NUM_9190_DEC_PP, .dec_io_size = REG_NUM_9190_DEC_PP * 4, }, [1] = { .hw_id = VPU_ID_4831, .hw_addr = 0, .enc_offset = 0x0, .enc_reg_num = REG_NUM_ENC_4831, .enc_io_size = REG_NUM_ENC_4831 * 4, .dec_offset = REG_SIZE_ENC_4831, .dec_reg_num = REG_NUM_9190_DEC_PP, .dec_io_size = REG_NUM_9190_DEC_PP * 4, }, [2] = { .hw_id = HEVC_ID, .hw_addr = 0, .dec_offset = 0x0, .dec_reg_num = REG_NUM_HEVC_DEC, .dec_io_size = REG_NUM_HEVC_DEC * 4, }, }; #define DEC_INTERRUPT_REGISTER 1 #define PP_INTERRUPT_REGISTER 60 #define ENC_INTERRUPT_REGISTER 1 #define DEC_INTERRUPT_BIT 0x100 #define DEC_BUFFER_EMPTY_BIT 0x4000 #define PP_INTERRUPT_BIT 0x100 #define ENC_INTERRUPT_BIT 0x1 #define HEVC_DEC_INT_RAW_BIT 0x200 #define HEVC_DEC_STR_ERROR_BIT 0x4000 #define HEVC_DEC_BUS_ERROR_BIT 0x2000 #define HEVC_DEC_BUFFER_EMPTY_BIT 0x10000 #define VPU_REG_EN_ENC 14 #define VPU_REG_ENC_GATE 2 #define VPU_REG_ENC_GATE_BIT (1<<4) #define VPU_REG_EN_DEC 1 #define VPU_REG_DEC_GATE 2 #define VPU_REG_DEC_GATE_BIT (1<<10) #define VPU_REG_EN_PP 0 #define VPU_REG_PP_GATE 1 #define VPU_REG_PP_GATE_BIT (1<<8) #define VPU_REG_EN_DEC_PP 1 #define VPU_REG_DEC_PP_GATE 61 #define VPU_REG_DEC_PP_GATE_BIT (1<<8) static u8 addr_tbl_vpu_dec[] = { 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 40, 41 }; static u8 addr_tbl_vpu_enc[] = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 51 }; static u8 addr_tbl_hevc_dec[] = { 4, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 42, 43 }; /** * struct for process session which connect to vpu * * @author ChenHengming (2011-5-3) */ typedef struct vpu_session { VPU_CLIENT_TYPE type; /* a linked list of data so we can access them for debugging */ struct list_head list_session; /* a linked list of register data waiting for process */ struct list_head waiting; /* a linked list of register data in processing */ struct list_head running; /* a linked list of register data processed */ struct list_head done; wait_queue_head_t wait; pid_t pid; atomic_t task_running; } vpu_session; /** * struct for process register set * * @author ChenHengming (2011-5-4) */ typedef struct vpu_reg { VPU_CLIENT_TYPE type; VPU_FREQ freq; vpu_session *session; struct list_head session_link; /* link to vpu service session */ struct list_head status_link; /* link to register set list */ unsigned long size; #if defined(CONFIG_VCODEC_MMU) struct list_head mem_region_list; #endif unsigned long *reg; } vpu_reg; typedef struct vpu_device { atomic_t irq_count_codec; atomic_t irq_count_pp; unsigned long iobaseaddr; unsigned int iosize; volatile u32 *hwregs; } vpu_device; enum vcodec_device_id { VCODEC_DEVICE_ID_VPU, VCODEC_DEVICE_ID_HEVC }; struct vcodec_mem_region { struct list_head srv_lnk; struct list_head reg_lnk; struct list_head session_lnk; dma_addr_t iova; /* virtual address for iommu */ struct dma_buf *buf; struct dma_buf_attachment *attachment; struct sg_table *sg_table; struct ion_handle *hdl; }; typedef struct vpu_service_info { struct wake_lock wake_lock; struct delayed_work power_off_work; struct mutex lock; struct list_head waiting; /* link to link_reg in struct vpu_reg */ struct list_head running; /* link to link_reg in struct vpu_reg */ struct list_head done; /* link to link_reg in struct vpu_reg */ struct list_head session; /* link to list_session in struct vpu_session */ atomic_t total_running; bool enabled; vpu_reg *reg_codec; vpu_reg *reg_pproc; vpu_reg *reg_resev; VPUHwDecConfig_t dec_config; VPUHwEncConfig_t enc_config; VPU_HW_INFO_E *hw_info; unsigned long reg_size; bool auto_freq; bool bug_dec_addr; atomic_t freq_status; struct clk *aclk_vcodec; struct clk *hclk_vcodec; struct clk *clk_core; struct clk *clk_cabac; int irq_dec; int irq_enc; vpu_device enc_dev; vpu_device dec_dev; struct device *dev; struct cdev cdev; dev_t dev_t; struct class *cls; struct device *child_dev; struct dentry *debugfs_dir; struct dentry *debugfs_file_regs; u32 irq_status; #if defined(CONFIG_ION_ROCKCHIP) struct ion_client * ion_client; #endif #if defined(CONFIG_VCODEC_MMU) struct list_head mem_region_list; #endif enum vcodec_device_id dev_id; struct delayed_work simulate_work; } vpu_service_info; typedef struct vpu_request { unsigned long *req; unsigned long size; } vpu_request; /// global variable //static struct clk *pd_video; static struct dentry *parent; // debugfs root directory for all device (vpu, hevc). #ifdef CONFIG_DEBUG_FS static int vcodec_debugfs_init(void); static void vcodec_debugfs_exit(void); static struct dentry* vcodec_debugfs_create_device_dir(char *dirname, struct dentry *parent); static int debug_vcodec_open(struct inode *inode, struct file *file); static const struct file_operations debug_vcodec_fops = { .open = debug_vcodec_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif #define VPU_POWER_OFF_DELAY 4*HZ /* 4s */ #define VPU_TIMEOUT_DELAY 2*HZ /* 2s */ #define VPU_SIMULATE_DELAY msecs_to_jiffies(15) static void vpu_get_clk(struct vpu_service_info *pservice) { #if VCODEC_CLOCK_ENABLE /*pd_video = clk_get(NULL, "pd_video"); if (IS_ERR(pd_video)) { pr_err("failed on clk_get pd_video\n"); }*/ pservice->aclk_vcodec = devm_clk_get(pservice->dev, "aclk_vcodec"); if (IS_ERR(pservice->aclk_vcodec)) { dev_err(pservice->dev, "failed on clk_get aclk_vcodec\n"); } pservice->hclk_vcodec = devm_clk_get(pservice->dev, "hclk_vcodec"); if (IS_ERR(pservice->hclk_vcodec)) { dev_err(pservice->dev, "failed on clk_get hclk_vcodec\n"); } if (pservice->dev_id == VCODEC_DEVICE_ID_HEVC) { pservice->clk_core = devm_clk_get(pservice->dev, "clk_core"); if (IS_ERR(pservice->clk_core)) { dev_err(pservice->dev, "failed on clk_get clk_core\n"); } pservice->clk_cabac = devm_clk_get(pservice->dev, "clk_cabac"); if (IS_ERR(pservice->clk_cabac)) { dev_err(pservice->dev, "failed on clk_get clk_cabac\n"); } } #endif } static void vpu_put_clk(struct vpu_service_info *pservice) { #if VCODEC_CLOCK_ENABLE //clk_put(pd_video); if (pservice->aclk_vcodec) { devm_clk_put(pservice->dev, pservice->aclk_vcodec); } if (pservice->hclk_vcodec) { devm_clk_put(pservice->dev, pservice->hclk_vcodec); } if (pservice->dev_id == VCODEC_DEVICE_ID_HEVC) { if (pservice->clk_core) { devm_clk_put(pservice->dev, pservice->clk_core); } if (pservice->clk_cabac) { devm_clk_put(pservice->dev, pservice->clk_cabac); } } #endif } static void vpu_reset(struct vpu_service_info *pservice) { #if defined(CONFIG_ARCH_RK29) clk_disable(aclk_ddr_vepu); cru_set_soft_reset(SOFT_RST_CPU_VODEC_A2A_AHB, true); cru_set_soft_reset(SOFT_RST_DDR_VCODEC_PORT, true); cru_set_soft_reset(SOFT_RST_VCODEC_AHB_BUS, true); cru_set_soft_reset(SOFT_RST_VCODEC_AXI_BUS, true); mdelay(10); cru_set_soft_reset(SOFT_RST_VCODEC_AXI_BUS, false); cru_set_soft_reset(SOFT_RST_VCODEC_AHB_BUS, false); cru_set_soft_reset(SOFT_RST_DDR_VCODEC_PORT, false); cru_set_soft_reset(SOFT_RST_CPU_VODEC_A2A_AHB, false); clk_enable(aclk_ddr_vepu); #elif defined(CONFIG_ARCH_RK30) pmu_set_idle_request(IDLE_REQ_VIDEO, true); cru_set_soft_reset(SOFT_RST_CPU_VCODEC, true); cru_set_soft_reset(SOFT_RST_VCODEC_NIU_AXI, true); cru_set_soft_reset(SOFT_RST_VCODEC_AHB, true); cru_set_soft_reset(SOFT_RST_VCODEC_AXI, true); mdelay(1); cru_set_soft_reset(SOFT_RST_VCODEC_AXI, false); cru_set_soft_reset(SOFT_RST_VCODEC_AHB, false); cru_set_soft_reset(SOFT_RST_VCODEC_NIU_AXI, false); cru_set_soft_reset(SOFT_RST_CPU_VCODEC, false); pmu_set_idle_request(IDLE_REQ_VIDEO, false); #endif pservice->reg_codec = NULL; pservice->reg_pproc = NULL; pservice->reg_resev = NULL; } static void reg_deinit(struct vpu_service_info *pservice, vpu_reg *reg); static void vpu_service_session_clear(struct vpu_service_info *pservice, vpu_session *session) { vpu_reg *reg, *n; list_for_each_entry_safe(reg, n, &session->waiting, session_link) { reg_deinit(pservice, reg); } list_for_each_entry_safe(reg, n, &session->running, session_link) { reg_deinit(pservice, reg); } list_for_each_entry_safe(reg, n, &session->done, session_link) { reg_deinit(pservice, reg); } } static void vpu_service_dump(struct vpu_service_info *pservice) { int running; vpu_reg *reg, *reg_tmp; vpu_session *session, *session_tmp; running = atomic_read(&pservice->total_running); printk("total_running %d\n", running); printk("reg_codec 0x%.8x\n", (unsigned int)pservice->reg_codec); printk("reg_pproc 0x%.8x\n", (unsigned int)pservice->reg_pproc); printk("reg_resev 0x%.8x\n", (unsigned int)pservice->reg_resev); list_for_each_entry_safe(session, session_tmp, &pservice->session, list_session) { printk("session pid %d type %d:\n", session->pid, session->type); running = atomic_read(&session->task_running); printk("task_running %d\n", running); list_for_each_entry_safe(reg, reg_tmp, &session->waiting, session_link) { printk("waiting register set 0x%.8x\n", (unsigned int)reg); } list_for_each_entry_safe(reg, reg_tmp, &session->running, session_link) { printk("running register set 0x%.8x\n", (unsigned int)reg); } list_for_each_entry_safe(reg, reg_tmp, &session->done, session_link) { printk("done register set 0x%.8x\n", (unsigned int)reg); } } } static void vpu_service_power_off(struct vpu_service_info *pservice) { int total_running; if (!pservice->enabled) { return; } pservice->enabled = false; total_running = atomic_read(&pservice->total_running); if (total_running) { pr_alert("alert: power off when %d task running!!\n", total_running); mdelay(50); pr_alert("alert: delay 50 ms for running task\n"); vpu_service_dump(pservice); } printk("%s: power off...", dev_name(pservice->dev)); #ifdef CONFIG_ARCH_RK29 pmu_set_power_domain(PD_VCODEC, false); #else //clk_disable(pd_video); #endif udelay(10); #if VCODEC_CLOCK_ENABLE clk_disable_unprepare(pservice->hclk_vcodec); clk_disable_unprepare(pservice->aclk_vcodec); if (pservice->dev_id == VCODEC_DEVICE_ID_HEVC) { clk_disable_unprepare(pservice->clk_core); clk_disable_unprepare(pservice->clk_cabac); } #endif wake_unlock(&pservice->wake_lock); printk("done\n"); } static inline void vpu_queue_power_off_work(struct vpu_service_info *pservice) { queue_delayed_work(system_nrt_wq, &pservice->power_off_work, VPU_POWER_OFF_DELAY); } static void vpu_power_off_work(struct work_struct *work_s) { struct delayed_work *dlwork = container_of(work_s, struct delayed_work, work); struct vpu_service_info *pservice = container_of(dlwork, struct vpu_service_info, power_off_work); if (mutex_trylock(&pservice->lock)) { vpu_service_power_off(pservice); mutex_unlock(&pservice->lock); } else { /* Come back later if the device is busy... */ vpu_queue_power_off_work(pservice); } } static void vpu_service_power_on(struct vpu_service_info *pservice) { static ktime_t last; ktime_t now = ktime_get(); if (ktime_to_ns(ktime_sub(now, last)) > NSEC_PER_SEC) { cancel_delayed_work_sync(&pservice->power_off_work); vpu_queue_power_off_work(pservice); last = now; } if (pservice->enabled) return ; pservice->enabled = true; printk("%s: power on\n", dev_name(pservice->dev)); #if VCODEC_CLOCK_ENABLE clk_prepare_enable(pservice->aclk_vcodec); clk_prepare_enable(pservice->hclk_vcodec); if (pservice->dev_id == VCODEC_DEVICE_ID_HEVC) { clk_prepare_enable(pservice->clk_core); clk_prepare_enable(pservice->clk_cabac); } #endif #if defined(CONFIG_ARCH_RK319X) /// select aclk_vepu as vcodec clock source. #define BIT_VCODEC_SEL (1<<7) writel_relaxed(readl_relaxed(RK319X_GRF_BASE + GRF_SOC_CON1) | (BIT_VCODEC_SEL) | (BIT_VCODEC_SEL << 16), RK319X_GRF_BASE + GRF_SOC_CON1); #endif udelay(10); #ifdef CONFIG_ARCH_RK29 pmu_set_power_domain(PD_VCODEC, true); #else //clk_enable(pd_video); #endif udelay(10); wake_lock(&pservice->wake_lock); } static inline bool reg_check_rmvb_wmv(vpu_reg *reg) { unsigned long type = (reg->reg[3] & 0xF0000000) >> 28; return ((type == 8) || (type == 4)); } static inline bool reg_check_interlace(vpu_reg *reg) { unsigned long type = (reg->reg[3] & (1 << 23)); return (type > 0); } static inline bool reg_check_avc(vpu_reg *reg) { unsigned long type = (reg->reg[3] & 0xF0000000) >> 28; return (type == 0); } static inline int reg_probe_width(vpu_reg *reg) { int width_in_mb = reg->reg[4] >> 23; return width_in_mb * 16; } #if defined(CONFIG_VCODEC_MMU) static unsigned int vcodec_map_ion_handle(vpu_service_info *pservice, vpu_reg *reg, struct ion_handle *ion_handle, struct dma_buf *buf, int offset) { struct vcodec_mem_region *mem_region = kzalloc(sizeof(struct vcodec_mem_region), GFP_KERNEL); if (mem_region == NULL) { dev_err(pservice->dev, "allocate memory for iommu memory region failed\n"); return -1; } mem_region->buf = buf; mem_region->hdl = ion_handle; mem_region->attachment = dma_buf_attach(buf, pservice->dev); if (IS_ERR_OR_NULL(mem_region->attachment)) { dev_err(pservice->dev, "dma_buf_attach() failed: %ld\n", PTR_ERR(mem_region->attachment)); goto err_buf_map_attach; } mem_region->sg_table = dma_buf_map_attachment(mem_region->attachment, DMA_BIDIRECTIONAL); if (IS_ERR_OR_NULL(mem_region->sg_table)) { dev_err(pservice->dev, "dma_buf_map_attachment() failed: %ld\n", PTR_ERR(mem_region->sg_table)); goto err_buf_map_attachment; } mem_region->iova = iovmm_map(pservice->dev, mem_region->sg_table->sgl, offset, buf->size); if (mem_region->iova == 0 || IS_ERR_VALUE(mem_region->iova)) { dev_err(pservice->dev, "iovmm_map() failed: %d\n", mem_region->iova); goto err_iovmm_map; } INIT_LIST_HEAD(&mem_region->reg_lnk); list_add_tail(&mem_region->reg_lnk, &reg->mem_region_list); return mem_region->iova; err_iovmm_map: dma_buf_unmap_attachment(mem_region->attachment, mem_region->sg_table, DMA_BIDIRECTIONAL); err_buf_map_attachment: dma_buf_detach(buf, mem_region->attachment); err_buf_map_attach: kfree(mem_region); return 0; } static int vcodec_reg_address_translate(struct vpu_service_info *pservice, vpu_reg *reg) { VPU_HW_ID hw_id; int i; hw_id = pservice->hw_info->hw_id; if (hw_id == HEVC_ID) { } else { if (reg->type == VPU_DEC) { for (i=0; i<sizeof(addr_tbl_vpu_dec); i++) { int usr_fd; struct ion_handle *hdl; //ion_phys_addr_t phy_addr; struct dma_buf *buf; //size_t len; int offset; #if 0 if (copy_from_user(&usr_fd, &reg->reg[addr_tbl_vpu_dec[i]], sizeof(usr_fd))) return -EFAULT; #else usr_fd = reg->reg[addr_tbl_vpu_dec[i]] & 0xFF; offset = reg->reg[addr_tbl_vpu_dec[i]] >> 8; #endif if (usr_fd != 0) { hdl = ion_import_dma_buf(pservice->ion_client, usr_fd); if (IS_ERR(hdl)) { pr_err("import dma-buf from fd %d failed\n", usr_fd); return PTR_ERR(hdl); } #if 0 ion_phys(pservice->ion_client, hdl, &phy_addr, &len); reg->reg[addr_tbl_vpu_dec[i]] = phy_addr + offset; ion_free(pservice->ion_client, hdl); #else buf = ion_share_dma_buf(pservice->ion_client, hdl); if (IS_ERR_OR_NULL(buf)) { dev_err(pservice->dev, "ion_share_dma_buf() failed\n"); ion_free(pservice->ion_client, hdl); return PTR_ERR(buf); } reg->reg[addr_tbl_vpu_dec[i]] = vcodec_map_ion_handle(pservice, reg, hdl, buf, offset); #endif } } } else if (reg->type == VPU_ENC) { } } return 0; } #endif static vpu_reg *reg_init(struct vpu_service_info *pservice, vpu_session *session, void __user *src, unsigned long size) { vpu_reg *reg = kmalloc(sizeof(vpu_reg)+pservice->reg_size, GFP_KERNEL); if (NULL == reg) { pr_err("error: kmalloc fail in reg_init\n"); return NULL; } if (size > pservice->reg_size) { printk("warning: vpu reg size %lu is larger than hw reg size %lu\n", size, pservice->reg_size); size = pservice->reg_size; } reg->session = session; reg->type = session->type; reg->size = size; reg->freq = VPU_FREQ_DEFAULT; reg->reg = (unsigned long *)&reg[1]; INIT_LIST_HEAD(&reg->session_link); INIT_LIST_HEAD(&reg->status_link); #if defined(CONFIG_VCODEC_MMU) INIT_LIST_HEAD(&reg->mem_region_list); #endif if (copy_from_user(&reg->reg[0], (void __user *)src, size)) { pr_err("error: copy_from_user failed in reg_init\n"); kfree(reg); return NULL; } #if defined(CONFIG_VCODEC_MMU) if (0 > vcodec_reg_address_translate(pservice, reg)) { pr_err("error: translate reg address failed\n"); kfree(reg); return NULL; } #endif mutex_lock(&pservice->lock); list_add_tail(&reg->status_link, &pservice->waiting); list_add_tail(&reg->session_link, &session->waiting); mutex_unlock(&pservice->lock); if (pservice->auto_freq) { if (!soc_is_rk2928g()) { if (reg->type == VPU_DEC || reg->type == VPU_DEC_PP) { if (reg_check_rmvb_wmv(reg)) { reg->freq = VPU_FREQ_200M; } else if (reg_check_avc(reg)) { if (reg_probe_width(reg) > 3200) { // raise frequency for 4k avc. reg->freq = VPU_FREQ_500M; } } else { if (reg_check_interlace(reg)) { reg->freq = VPU_FREQ_400M; } } } if (reg->type == VPU_PP) { reg->freq = VPU_FREQ_400M; } } } return reg; } static void reg_deinit(struct vpu_service_info *pservice, vpu_reg *reg) { #if defined(CONFIG_VCODEC_MMU) struct vcodec_mem_region *mem_region = NULL, *n; #endif list_del_init(&reg->session_link); list_del_init(&reg->status_link); if (reg == pservice->reg_codec) pservice->reg_codec = NULL; if (reg == pservice->reg_pproc) pservice->reg_pproc = NULL; #if defined(CONFIG_VCODEC_MMU) // release memory region attach to this registers table. list_for_each_entry_safe(mem_region, n, &reg->mem_region_list, reg_lnk) { iovmm_unmap(pservice->dev, mem_region->iova); dma_buf_unmap_attachment(mem_region->attachment, mem_region->sg_table, DMA_BIDIRECTIONAL); dma_buf_detach(mem_region->buf, mem_region->attachment); dma_buf_put(mem_region->buf); ion_free(pservice->ion_client, mem_region->hdl); list_del_init(&mem_region->reg_lnk); kfree(mem_region); } #endif kfree(reg); } static void reg_from_wait_to_run(struct vpu_service_info *pservice, vpu_reg *reg) { list_del_init(&reg->status_link); list_add_tail(&reg->status_link, &pservice->running); list_del_init(&reg->session_link); list_add_tail(&reg->session_link, &reg->session->running); } static void reg_copy_from_hw(vpu_reg *reg, volatile u32 *src, u32 count) { int i; u32 *dst = (u32 *)&reg->reg[0]; for (i = 0; i < count; i++) *dst++ = *src++; } static void reg_from_run_to_done(struct vpu_service_info *pservice, vpu_reg *reg) { int irq_reg = -1; list_del_init(&reg->status_link); list_add_tail(&reg->status_link, &pservice->done); list_del_init(&reg->session_link); list_add_tail(&reg->session_link, &reg->session->done); switch (reg->type) { case VPU_ENC : { pservice->reg_codec = NULL; reg_copy_from_hw(reg, pservice->enc_dev.hwregs, pservice->hw_info->enc_reg_num); irq_reg = ENC_INTERRUPT_REGISTER; break; } case VPU_DEC : { int reg_len = pservice->hw_info->hw_id == HEVC_ID ? REG_NUM_HEVC_DEC : REG_NUM_9190_DEC; pservice->reg_codec = NULL; reg_copy_from_hw(reg, pservice->dec_dev.hwregs, reg_len); irq_reg = DEC_INTERRUPT_REGISTER; break; } case VPU_PP : { pservice->reg_pproc = NULL; reg_copy_from_hw(reg, pservice->dec_dev.hwregs + PP_INTERRUPT_REGISTER, REG_NUM_9190_PP); pservice->dec_dev.hwregs[PP_INTERRUPT_REGISTER] = 0; break; } case VPU_DEC_PP : { pservice->reg_codec = NULL; pservice->reg_pproc = NULL; reg_copy_from_hw(reg, pservice->dec_dev.hwregs, REG_NUM_9190_DEC_PP); pservice->dec_dev.hwregs[PP_INTERRUPT_REGISTER] = 0; break; } default : { pr_err("error: copy reg from hw with unknown type %d\n", reg->type); break; } } if (irq_reg != -1) { reg->reg[irq_reg] = pservice->irq_status; } atomic_sub(1, &reg->session->task_running); atomic_sub(1, &pservice->total_running); wake_up(&reg->session->wait); } static void vpu_service_set_freq(struct vpu_service_info *pservice, vpu_reg *reg) { VPU_FREQ curr = atomic_read(&pservice->freq_status); if (curr == reg->freq) { return ; } atomic_set(&pservice->freq_status, reg->freq); switch (reg->freq) { case VPU_FREQ_200M : { clk_set_rate(pservice->aclk_vcodec, 200*MHZ); //printk("default: 200M\n"); } break; case VPU_FREQ_266M : { clk_set_rate(pservice->aclk_vcodec, 266*MHZ); //printk("default: 266M\n"); } break; case VPU_FREQ_300M : { clk_set_rate(pservice->aclk_vcodec, 300*MHZ); //printk("default: 300M\n"); } break; case VPU_FREQ_400M : { clk_set_rate(pservice->aclk_vcodec, 400*MHZ); //printk("default: 400M\n"); } break; case VPU_FREQ_500M : { clk_set_rate(pservice->aclk_vcodec, 500*MHZ); } break; case VPU_FREQ_600M : { clk_set_rate(pservice->aclk_vcodec, 600*MHZ); } break; default : { if (soc_is_rk2928g()) { clk_set_rate(pservice->aclk_vcodec, 400*MHZ); } else { clk_set_rate(pservice->aclk_vcodec, 300*MHZ); } //printk("default: 300M\n"); } break; } } #if HEVC_SIM_ENABLE static void simulate_start(struct vpu_service_info *pservice); #endif static void reg_copy_to_hw(struct vpu_service_info *pservice, vpu_reg *reg) { int i; u32 *src = (u32 *)&reg->reg[0]; atomic_add(1, &pservice->total_running); atomic_add(1, &reg->session->task_running); if (pservice->auto_freq) { vpu_service_set_freq(pservice, reg); } switch (reg->type) { case VPU_ENC : { int enc_count = pservice->hw_info->enc_reg_num; u32 *dst = (u32 *)pservice->enc_dev.hwregs; #if 0 if (pservice->bug_dec_addr) { #if !defined(CONFIG_ARCH_RK319X) cru_set_soft_reset(SOFT_RST_CPU_VCODEC, true); #endif cru_set_soft_reset(SOFT_RST_VCODEC_AHB, true); cru_set_soft_reset(SOFT_RST_VCODEC_AHB, false); #if !defined(CONFIG_ARCH_RK319X) cru_set_soft_reset(SOFT_RST_CPU_VCODEC, false); #endif } #endif pservice->reg_codec = reg; dst[VPU_REG_EN_ENC] = src[VPU_REG_EN_ENC] & 0x6; for (i = 0; i < VPU_REG_EN_ENC; i++) dst[i] = src[i]; for (i = VPU_REG_EN_ENC + 1; i < enc_count; i++) dst[i] = src[i]; dsb(); dst[VPU_REG_ENC_GATE] = src[VPU_REG_ENC_GATE] | VPU_REG_ENC_GATE_BIT; dst[VPU_REG_EN_ENC] = src[VPU_REG_EN_ENC]; #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&enc_start); #endif } break; case VPU_DEC : { u32 *dst = (u32 *)pservice->dec_dev.hwregs; pservice->reg_codec = reg; if (pservice->hw_info->hw_id != HEVC_ID) { for (i = REG_NUM_9190_DEC - 1; i > VPU_REG_DEC_GATE; i--) dst[i] = src[i]; } else { for (i = REG_NUM_HEVC_DEC - 1; i > VPU_REG_EN_DEC; i--) { dst[i] = src[i]; } } dsb(); if (pservice->hw_info->hw_id != HEVC_ID) { dst[VPU_REG_DEC_GATE] = src[VPU_REG_DEC_GATE] | VPU_REG_DEC_GATE_BIT; dst[VPU_REG_EN_DEC] = src[VPU_REG_EN_DEC]; } else { dst[VPU_REG_EN_DEC] = src[VPU_REG_EN_DEC]; } dsb(); dmb(); #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&dec_start); #endif } break; case VPU_PP : { u32 *dst = (u32 *)pservice->dec_dev.hwregs + PP_INTERRUPT_REGISTER; pservice->reg_pproc = reg; dst[VPU_REG_PP_GATE] = src[VPU_REG_PP_GATE] | VPU_REG_PP_GATE_BIT; for (i = VPU_REG_PP_GATE + 1; i < REG_NUM_9190_PP; i++) dst[i] = src[i]; dsb(); dst[VPU_REG_EN_PP] = src[VPU_REG_EN_PP]; #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&pp_start); #endif } break; case VPU_DEC_PP : { u32 *dst = (u32 *)pservice->dec_dev.hwregs; pservice->reg_codec = reg; pservice->reg_pproc = reg; for (i = VPU_REG_EN_DEC_PP + 1; i < REG_NUM_9190_DEC_PP; i++) dst[i] = src[i]; dst[VPU_REG_EN_DEC_PP] = src[VPU_REG_EN_DEC_PP] | 0x2; dsb(); dst[VPU_REG_DEC_PP_GATE] = src[VPU_REG_DEC_PP_GATE] | VPU_REG_PP_GATE_BIT; dst[VPU_REG_DEC_GATE] = src[VPU_REG_DEC_GATE] | VPU_REG_DEC_GATE_BIT; dst[VPU_REG_EN_DEC] = src[VPU_REG_EN_DEC]; #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&dec_start); #endif } break; default : { pr_err("error: unsupport session type %d", reg->type); atomic_sub(1, &pservice->total_running); atomic_sub(1, &reg->session->task_running); break; } } #if HEVC_SIM_ENABLE if (pservice->hw_info->hw_id == HEVC_ID) { simulate_start(pservice); } #endif } static void try_set_reg(struct vpu_service_info *pservice) { // first get reg from reg list if (!list_empty(&pservice->waiting)) { int can_set = 0; vpu_reg *reg = list_entry(pservice->waiting.next, vpu_reg, status_link); vpu_service_power_on(pservice); switch (reg->type) { case VPU_ENC : { if ((NULL == pservice->reg_codec) && (NULL == pservice->reg_pproc)) can_set = 1; } break; case VPU_DEC : { if (NULL == pservice->reg_codec) can_set = 1; if (pservice->auto_freq && (NULL != pservice->reg_pproc)) { can_set = 0; } } break; case VPU_PP : { if (NULL == pservice->reg_codec) { if (NULL == pservice->reg_pproc) can_set = 1; } else { if ((VPU_DEC == pservice->reg_codec->type) && (NULL == pservice->reg_pproc)) can_set = 1; // can not charge frequency when vpu is working if (pservice->auto_freq) { can_set = 0; } } } break; case VPU_DEC_PP : { if ((NULL == pservice->reg_codec) && (NULL == pservice->reg_pproc)) can_set = 1; } break; default : { printk("undefined reg type %d\n", reg->type); } break; } if (can_set) { reg_from_wait_to_run(pservice, reg); reg_copy_to_hw(pservice, reg); } } } static int return_reg(struct vpu_service_info *pservice, vpu_reg *reg, u32 __user *dst) { int ret = 0; switch (reg->type) { case VPU_ENC : { if (copy_to_user(dst, &reg->reg[0], pservice->hw_info->enc_io_size)) ret = -EFAULT; break; } case VPU_DEC : { int reg_len = pservice->hw_info->hw_id == HEVC_ID ? REG_NUM_HEVC_DEC : REG_NUM_9190_DEC; if (copy_to_user(dst, &reg->reg[0], SIZE_REG(reg_len))) ret = -EFAULT; break; } case VPU_PP : { if (copy_to_user(dst, &reg->reg[0], SIZE_REG(REG_NUM_9190_PP))) ret = -EFAULT; break; } case VPU_DEC_PP : { if (copy_to_user(dst, &reg->reg[0], SIZE_REG(REG_NUM_9190_DEC_PP))) ret = -EFAULT; break; } default : { ret = -EFAULT; pr_err("error: copy reg to user with unknown type %d\n", reg->type); break; } } reg_deinit(pservice, reg); return ret; } static long vpu_service_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct vpu_service_info *pservice = container_of(filp->f_dentry->d_inode->i_cdev, struct vpu_service_info, cdev); vpu_session *session = (vpu_session *)filp->private_data; if (NULL == session) { return -EINVAL; } switch (cmd) { case VPU_IOC_SET_CLIENT_TYPE : { session->type = (VPU_CLIENT_TYPE)arg; break; } case VPU_IOC_GET_HW_FUSE_STATUS : { vpu_request req; if (copy_from_user(&req, (void __user *)arg, sizeof(vpu_request))) { pr_err("error: VPU_IOC_GET_HW_FUSE_STATUS copy_from_user failed\n"); return -EFAULT; } else { if (VPU_ENC != session->type) { if (copy_to_user((void __user *)req.req, &pservice->dec_config, sizeof(VPUHwDecConfig_t))) { pr_err("error: VPU_IOC_GET_HW_FUSE_STATUS copy_to_user failed type %d\n", session->type); return -EFAULT; } } else { if (copy_to_user((void __user *)req.req, &pservice->enc_config, sizeof(VPUHwEncConfig_t))) { pr_err("error: VPU_IOC_GET_HW_FUSE_STATUS copy_to_user failed type %d\n", session->type); return -EFAULT; } } } break; } case VPU_IOC_SET_REG : { vpu_request req; vpu_reg *reg; if (copy_from_user(&req, (void __user *)arg, sizeof(vpu_request))) { pr_err("error: VPU_IOC_SET_REG copy_from_user failed\n"); return -EFAULT; } reg = reg_init(pservice, session, (void __user *)req.req, req.size); if (NULL == reg) { return -EFAULT; } else { mutex_lock(&pservice->lock); try_set_reg(pservice); mutex_unlock(&pservice->lock); } break; } case VPU_IOC_GET_REG : { vpu_request req; vpu_reg *reg; if (copy_from_user(&req, (void __user *)arg, sizeof(vpu_request))) { pr_err("error: VPU_IOC_GET_REG copy_from_user failed\n"); return -EFAULT; } else { int ret = wait_event_timeout(session->wait, !list_empty(&session->done), VPU_TIMEOUT_DELAY); if (!list_empty(&session->done)) { if (ret < 0) { pr_err("warning: pid %d wait task sucess but wait_evernt ret %d\n", session->pid, ret); } ret = 0; } else { if (unlikely(ret < 0)) { pr_err("error: pid %d wait task ret %d\n", session->pid, ret); } else if (0 == ret) { pr_err("error: pid %d wait %d task done timeout\n", session->pid, atomic_read(&session->task_running)); ret = -ETIMEDOUT; } } if (ret < 0) { int task_running = atomic_read(&session->task_running); mutex_lock(&pservice->lock); vpu_service_dump(pservice); if (task_running) { atomic_set(&session->task_running, 0); atomic_sub(task_running, &pservice->total_running); printk("%d task is running but not return, reset hardware...", task_running); vpu_reset(pservice); printk("done\n"); } vpu_service_session_clear(pservice, session); mutex_unlock(&pservice->lock); return ret; } } mutex_lock(&pservice->lock); reg = list_entry(session->done.next, vpu_reg, session_link); return_reg(pservice, reg, (u32 __user *)req.req); mutex_unlock(&pservice->lock); break; } default : { pr_err("error: unknow vpu service ioctl cmd %x\n", cmd); break; } } return 0; } static int vpu_service_check_hw(vpu_service_info *p, unsigned long hw_addr) { int ret = -EINVAL, i = 0; volatile u32 *tmp = (volatile u32 *)ioremap_nocache(hw_addr, 0x4); u32 enc_id = *tmp; #if HEVC_SIM_ENABLE /// temporary, hevc driver test. if (strncmp(dev_name(p->dev), "hevc_service", strlen("hevc_service")) == 0) { p->hw_info = &vpu_hw_set[2]; return 0; } #endif enc_id = (enc_id >> 16) & 0xFFFF; pr_info("checking hw id %x\n", enc_id); p->hw_info = NULL; for (i = 0; i < ARRAY_SIZE(vpu_hw_set); i++) { if (enc_id == vpu_hw_set[i].hw_id) { p->hw_info = &vpu_hw_set[i]; ret = 0; break; } } iounmap((void *)tmp); return ret; } static int vpu_service_open(struct inode *inode, struct file *filp) { struct vpu_service_info *pservice = container_of(inode->i_cdev, struct vpu_service_info, cdev); vpu_session *session = (vpu_session *)kmalloc(sizeof(vpu_session), GFP_KERNEL); if (NULL == session) { pr_err("error: unable to allocate memory for vpu_session."); return -ENOMEM; } session->type = VPU_TYPE_BUTT; session->pid = current->pid; INIT_LIST_HEAD(&session->waiting); INIT_LIST_HEAD(&session->running); INIT_LIST_HEAD(&session->done); INIT_LIST_HEAD(&session->list_session); init_waitqueue_head(&session->wait); atomic_set(&session->task_running, 0); mutex_lock(&pservice->lock); list_add_tail(&session->list_session, &pservice->session); filp->private_data = (void *)session; mutex_unlock(&pservice->lock); pr_debug("dev opened\n"); return nonseekable_open(inode, filp); } static int vpu_service_release(struct inode *inode, struct file *filp) { struct vpu_service_info *pservice = container_of(inode->i_cdev, struct vpu_service_info, cdev); int task_running; vpu_session *session = (vpu_session *)filp->private_data; if (NULL == session) return -EINVAL; task_running = atomic_read(&session->task_running); if (task_running) { pr_err("error: vpu_service session %d still has %d task running when closing\n", session->pid, task_running); msleep(50); } wake_up(&session->wait); mutex_lock(&pservice->lock); /* remove this filp from the asynchronusly notified filp's */ list_del_init(&session->list_session); vpu_service_session_clear(pservice, session); kfree(session); filp->private_data = NULL; mutex_unlock(&pservice->lock); pr_debug("dev closed\n"); return 0; } static const struct file_operations vpu_service_fops = { .unlocked_ioctl = vpu_service_ioctl, .open = vpu_service_open, .release = vpu_service_release, //.fasync = vpu_service_fasync, }; static irqreturn_t vdpu_irq(int irq, void *dev_id); static irqreturn_t vdpu_isr(int irq, void *dev_id); static irqreturn_t vepu_irq(int irq, void *dev_id); static irqreturn_t vepu_isr(int irq, void *dev_id); static void get_hw_info(struct vpu_service_info *pservice); #if HEVC_SIM_ENABLE static void simulate_work(struct work_struct *work_s) { struct delayed_work *dlwork = container_of(work_s, struct delayed_work, work); struct vpu_service_info *pservice = container_of(dlwork, struct vpu_service_info, simulate_work); vpu_device *dev = &pservice->dec_dev; if (!list_empty(&pservice->running)) { atomic_add(1, &dev->irq_count_codec); vdpu_isr(0, (void*)pservice); } else { //simulate_start(pservice); pr_err("empty running queue\n"); } } static void simulate_init(struct vpu_service_info *pservice) { INIT_DELAYED_WORK(&pservice->simulate_work, simulate_work); } static void simulate_start(struct vpu_service_info *pservice) { cancel_delayed_work_sync(&pservice->power_off_work); queue_delayed_work(system_nrt_wq, &pservice->simulate_work, VPU_SIMULATE_DELAY); } #endif #if HEVC_TEST_ENABLE static int hevc_test_case0(vpu_service_info *pservice); #endif #if defined(CONFIG_VCODEC_MMU) & defined(CONFIG_ION_ROCKCHIP) extern struct ion_client *rockchip_ion_client_create(const char * name); #endif static int vcodec_probe(struct platform_device *pdev) { int ret = 0; struct resource *res = NULL; struct device *dev = &pdev->dev; void __iomem *regs = NULL; struct device_node *np = pdev->dev.of_node; struct vpu_service_info *pservice = devm_kzalloc(dev, sizeof(struct vpu_service_info), GFP_KERNEL); char *prop = (char*)dev_name(dev); #if defined(CONFIG_VCODEC_MMU) struct device *mmu_dev = NULL; char mmu_dev_dts_name[40]; #endif pr_info("probe device %s\n", dev_name(dev)); of_property_read_string(np, "name", (const char**)&prop); dev_set_name(dev, prop); if (strcmp(dev_name(dev), "hevc_service") == 0) { pservice->dev_id = VCODEC_DEVICE_ID_HEVC; } else if (strcmp(dev_name(dev), "vpu_service") == 0) { pservice->dev_id = VCODEC_DEVICE_ID_VPU; } else { dev_err(dev, "Unknown device %s to probe\n", dev_name(dev)); return -1; } wake_lock_init(&pservice->wake_lock, WAKE_LOCK_SUSPEND, "vpu"); INIT_LIST_HEAD(&pservice->waiting); INIT_LIST_HEAD(&pservice->running); INIT_LIST_HEAD(&pservice->done); INIT_LIST_HEAD(&pservice->session); mutex_init(&pservice->lock); pservice->reg_codec = NULL; pservice->reg_pproc = NULL; atomic_set(&pservice->total_running, 0); pservice->enabled = false; pservice->dev = dev; vpu_get_clk(pservice); INIT_DELAYED_WORK(&pservice->power_off_work, vpu_power_off_work); vpu_service_power_on(pservice); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); regs = devm_ioremap_resource(pservice->dev, res); if (IS_ERR(regs)) { ret = PTR_ERR(regs); goto err; } ret = vpu_service_check_hw(pservice, res->start); if (ret < 0) { pr_err("error: hw info check faild\n"); goto err; } /// define regs address. pservice->dec_dev.iobaseaddr = res->start + pservice->hw_info->dec_offset; pservice->dec_dev.iosize = pservice->hw_info->dec_io_size; pservice->dec_dev.hwregs = (volatile u32 *)((u8 *)regs + pservice->hw_info->dec_offset); pservice->reg_size = pservice->dec_dev.iosize; if (pservice->hw_info->hw_id != HEVC_ID) { pservice->enc_dev.iobaseaddr = res->start + pservice->hw_info->enc_offset; pservice->enc_dev.iosize = pservice->hw_info->enc_io_size; pservice->reg_size = pservice->reg_size > pservice->enc_dev.iosize ? pservice->reg_size : pservice->enc_dev.iosize; pservice->enc_dev.hwregs = (volatile u32 *)((u8 *)regs + pservice->hw_info->enc_offset); pservice->irq_enc = platform_get_irq_byname(pdev, "irq_enc"); if (pservice->irq_enc < 0) { dev_err(pservice->dev, "cannot find IRQ encoder\n"); ret = -ENXIO; goto err; } ret = devm_request_threaded_irq(pservice->dev, pservice->irq_enc, vepu_irq, vepu_isr, 0, dev_name(pservice->dev), (void *)pservice); if (ret) { dev_err(pservice->dev, "error: can't request vepu irq %d\n", pservice->irq_enc); goto err; } } pservice->irq_dec = platform_get_irq_byname(pdev, "irq_dec"); if (pservice->irq_dec < 0) { dev_err(pservice->dev, "cannot find IRQ decoder\n"); ret = -ENXIO; goto err; } /* get the IRQ line */ ret = devm_request_threaded_irq(pservice->dev, pservice->irq_dec, vdpu_irq, vdpu_isr, 0, dev_name(pservice->dev), (void *)pservice); if (ret) { dev_err(pservice->dev, "error: can't request vdpu irq %d\n", pservice->irq_dec); goto err; } atomic_set(&pservice->dec_dev.irq_count_codec, 0); atomic_set(&pservice->dec_dev.irq_count_pp, 0); atomic_set(&pservice->enc_dev.irq_count_codec, 0); atomic_set(&pservice->enc_dev.irq_count_pp, 0); /// create device ret = alloc_chrdev_region(&pservice->dev_t, 0, 1, dev_name(dev)); if (ret) { dev_err(dev, "alloc dev_t failed\n"); goto err; } cdev_init(&pservice->cdev, &vpu_service_fops); pservice->cdev.owner = THIS_MODULE; pservice->cdev.ops = &vpu_service_fops; ret = cdev_add(&pservice->cdev, pservice->dev_t, 1); if (ret) { dev_err(dev, "add dev_t failed\n"); goto err; } pservice->cls = class_create(THIS_MODULE, dev_name(dev)); if (IS_ERR(pservice->cls)) { ret = PTR_ERR(pservice->cls); dev_err(dev, "class_create err:%d\n", ret); goto err; } pservice->child_dev = device_create(pservice->cls, dev, pservice->dev_t, NULL, dev_name(dev)); platform_set_drvdata(pdev, pservice); get_hw_info(pservice); #ifdef CONFIG_DEBUG_FS pservice->debugfs_dir = vcodec_debugfs_create_device_dir((char*)dev_name(dev), parent); if (pservice->debugfs_dir == NULL) { pr_err("create debugfs dir %s failed\n", dev_name(dev)); } pservice->debugfs_file_regs = debugfs_create_file("regs", 0664, pservice->debugfs_dir, pservice, &debug_vcodec_fops); #endif vpu_service_power_off(pservice); pr_info("init success\n"); #if defined(CONFIG_VCODEC_MMU) & defined(CONFIG_ION_ROCKCHIP) pservice->ion_client = rockchip_ion_client_create("vpu"); if (IS_ERR(pservice->ion_client)) { dev_err(&pdev->dev, "failed to create ion client for vcodec"); return PTR_ERR(pservice->ion_client); } else { dev_info(&pdev->dev, "vcodec ion client create success!\n"); } sprintf(mmu_dev_dts_name, "iommu,%s", dev_name(dev)); mmu_dev = rockchip_get_sysmmu_device_by_compatible(mmu_dev_dts_name); platform_set_sysmmu(mmu_dev, pservice->dev); iovmm_activate(pservice->dev); #endif #if HEVC_SIM_ENABLE if (pservice->hw_info->hw_id == HEVC_ID) { simulate_init(pservice); } #endif #if HEVC_TEST_ENABLE hevc_test_case0(pservice); #endif return 0; err: pr_info("init failed\n"); vpu_service_power_off(pservice); vpu_put_clk(pservice); wake_lock_destroy(&pservice->wake_lock); if (res) { if (regs) { devm_ioremap_release(&pdev->dev, res); } devm_release_mem_region(&pdev->dev, res->start, resource_size(res)); } if (pservice->irq_enc > 0) { free_irq(pservice->irq_enc, (void *)pservice); } if (pservice->irq_dec > 0) { free_irq(pservice->irq_dec, (void *)pservice); } if (pservice->child_dev) { device_destroy(pservice->cls, pservice->dev_t); cdev_del(&pservice->cdev); unregister_chrdev_region(pservice->dev_t, 1); } if (pservice->cls) { class_destroy(pservice->cls); } return ret; } static int vcodec_remove(struct platform_device *pdev) { struct vpu_service_info *pservice = platform_get_drvdata(pdev); struct resource *res; device_destroy(pservice->cls, pservice->dev_t); class_destroy(pservice->cls); cdev_del(&pservice->cdev); unregister_chrdev_region(pservice->dev_t, 1); free_irq(pservice->irq_enc, (void *)&pservice->enc_dev); free_irq(pservice->irq_dec, (void *)&pservice->dec_dev); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); devm_ioremap_release(&pdev->dev, res); devm_release_mem_region(&pdev->dev, res->start, resource_size(res)); vpu_put_clk(pservice); wake_lock_destroy(&pservice->wake_lock); #ifdef CONFIG_DEBUG_FS if (pservice->debugfs_file_regs) { debugfs_remove(pservice->debugfs_file_regs); } if (pservice->debugfs_dir) { debugfs_remove(pservice->debugfs_dir); } #endif return 0; } #if defined(CONFIG_OF) static const struct of_device_id vcodec_service_dt_ids[] = { {.compatible = "vpu_service",}, {.compatible = "rockchip,hevc_service",}, {}, }; #endif static struct platform_driver vcodec_driver = { .probe = vcodec_probe, .remove = vcodec_remove, .driver = { .name = "vcodec", .owner = THIS_MODULE, #if defined(CONFIG_OF) .of_match_table = of_match_ptr(vcodec_service_dt_ids), #endif }, }; static void get_hw_info(struct vpu_service_info *pservice) { VPUHwDecConfig_t *dec = &pservice->dec_config; VPUHwEncConfig_t *enc = &pservice->enc_config; if (pservice->dev_id == VCODEC_DEVICE_ID_VPU) { u32 configReg = pservice->dec_dev.hwregs[VPU_DEC_HWCFG0]; u32 asicID = pservice->dec_dev.hwregs[0]; dec->h264Support = (configReg >> DWL_H264_E) & 0x3U; dec->jpegSupport = (configReg >> DWL_JPEG_E) & 0x01U; if (dec->jpegSupport && ((configReg >> DWL_PJPEG_E) & 0x01U)) dec->jpegSupport = JPEG_PROGRESSIVE; dec->mpeg4Support = (configReg >> DWL_MPEG4_E) & 0x3U; dec->vc1Support = (configReg >> DWL_VC1_E) & 0x3U; dec->mpeg2Support = (configReg >> DWL_MPEG2_E) & 0x01U; dec->sorensonSparkSupport = (configReg >> DWL_SORENSONSPARK_E) & 0x01U; dec->refBufSupport = (configReg >> DWL_REF_BUFF_E) & 0x01U; dec->vp6Support = (configReg >> DWL_VP6_E) & 0x01U; if (!soc_is_rk3190() && !soc_is_rk3288()) { dec->maxDecPicWidth = configReg & 0x07FFU; } else { dec->maxDecPicWidth = 4096; } /* 2nd Config register */ configReg = pservice->dec_dev.hwregs[VPU_DEC_HWCFG1]; if (dec->refBufSupport) { if ((configReg >> DWL_REF_BUFF_ILACE_E) & 0x01U) dec->refBufSupport |= 2; if ((configReg >> DWL_REF_BUFF_DOUBLE_E) & 0x01U) dec->refBufSupport |= 4; } dec->customMpeg4Support = (configReg >> DWL_MPEG4_CUSTOM_E) & 0x01U; dec->vp7Support = (configReg >> DWL_VP7_E) & 0x01U; dec->vp8Support = (configReg >> DWL_VP8_E) & 0x01U; dec->avsSupport = (configReg >> DWL_AVS_E) & 0x01U; /* JPEG xtensions */ if (((asicID >> 16) >= 0x8190U) || ((asicID >> 16) == 0x6731U)) { dec->jpegESupport = (configReg >> DWL_JPEG_EXT_E) & 0x01U; } else { dec->jpegESupport = JPEG_EXT_NOT_SUPPORTED; } if (((asicID >> 16) >= 0x9170U) || ((asicID >> 16) == 0x6731U) ) { dec->rvSupport = (configReg >> DWL_RV_E) & 0x03U; } else { dec->rvSupport = RV_NOT_SUPPORTED; } dec->mvcSupport = (configReg >> DWL_MVC_E) & 0x03U; if (dec->refBufSupport && (asicID >> 16) == 0x6731U ) { dec->refBufSupport |= 8; /* enable HW support for offset */ } /// invalidate fuse register value in rk319x vpu and following. if (!soc_is_rk3190() && !soc_is_rk3288()) { VPUHwFuseStatus_t hwFuseSts; /* Decoder fuse configuration */ u32 fuseReg = pservice->dec_dev.hwregs[VPU_DEC_HW_FUSE_CFG]; hwFuseSts.h264SupportFuse = (fuseReg >> DWL_H264_FUSE_E) & 0x01U; hwFuseSts.mpeg4SupportFuse = (fuseReg >> DWL_MPEG4_FUSE_E) & 0x01U; hwFuseSts.mpeg2SupportFuse = (fuseReg >> DWL_MPEG2_FUSE_E) & 0x01U; hwFuseSts.sorensonSparkSupportFuse = (fuseReg >> DWL_SORENSONSPARK_FUSE_E) & 0x01U; hwFuseSts.jpegSupportFuse = (fuseReg >> DWL_JPEG_FUSE_E) & 0x01U; hwFuseSts.vp6SupportFuse = (fuseReg >> DWL_VP6_FUSE_E) & 0x01U; hwFuseSts.vc1SupportFuse = (fuseReg >> DWL_VC1_FUSE_E) & 0x01U; hwFuseSts.jpegProgSupportFuse = (fuseReg >> DWL_PJPEG_FUSE_E) & 0x01U; hwFuseSts.rvSupportFuse = (fuseReg >> DWL_RV_FUSE_E) & 0x01U; hwFuseSts.avsSupportFuse = (fuseReg >> DWL_AVS_FUSE_E) & 0x01U; hwFuseSts.vp7SupportFuse = (fuseReg >> DWL_VP7_FUSE_E) & 0x01U; hwFuseSts.vp8SupportFuse = (fuseReg >> DWL_VP8_FUSE_E) & 0x01U; hwFuseSts.customMpeg4SupportFuse = (fuseReg >> DWL_CUSTOM_MPEG4_FUSE_E) & 0x01U; hwFuseSts.mvcSupportFuse = (fuseReg >> DWL_MVC_FUSE_E) & 0x01U; /* check max. decoder output width */ if (fuseReg & 0x8000U) hwFuseSts.maxDecPicWidthFuse = 1920; else if (fuseReg & 0x4000U) hwFuseSts.maxDecPicWidthFuse = 1280; else if (fuseReg & 0x2000U) hwFuseSts.maxDecPicWidthFuse = 720; else if (fuseReg & 0x1000U) hwFuseSts.maxDecPicWidthFuse = 352; else /* remove warning */ hwFuseSts.maxDecPicWidthFuse = 352; hwFuseSts.refBufSupportFuse = (fuseReg >> DWL_REF_BUFF_FUSE_E) & 0x01U; /* Pp configuration */ configReg = pservice->dec_dev.hwregs[VPU_PP_HW_SYNTH_CFG]; if ((configReg >> DWL_PP_E) & 0x01U) { dec->ppSupport = 1; dec->maxPpOutPicWidth = configReg & 0x07FFU; /*pHwCfg->ppConfig = (configReg >> DWL_CFG_E) & 0x0FU; */ dec->ppConfig = configReg; } else { dec->ppSupport = 0; dec->maxPpOutPicWidth = 0; dec->ppConfig = 0; } /* check the HW versio */ if (((asicID >> 16) >= 0x8190U) || ((asicID >> 16) == 0x6731U)) { /* Pp configuration */ configReg = pservice->dec_dev.hwregs[VPU_DEC_HW_FUSE_CFG]; if ((configReg >> DWL_PP_E) & 0x01U) { /* Pp fuse configuration */ u32 fuseRegPp = pservice->dec_dev.hwregs[VPU_PP_HW_FUSE_CFG]; if ((fuseRegPp >> DWL_PP_FUSE_E) & 0x01U) { hwFuseSts.ppSupportFuse = 1; /* check max. pp output width */ if (fuseRegPp & 0x8000U) hwFuseSts.maxPpOutPicWidthFuse = 1920; else if (fuseRegPp & 0x4000U) hwFuseSts.maxPpOutPicWidthFuse = 1280; else if (fuseRegPp & 0x2000U) hwFuseSts.maxPpOutPicWidthFuse = 720; else if (fuseRegPp & 0x1000U) hwFuseSts.maxPpOutPicWidthFuse = 352; else hwFuseSts.maxPpOutPicWidthFuse = 352; hwFuseSts.ppConfigFuse = fuseRegPp; } else { hwFuseSts.ppSupportFuse = 0; hwFuseSts.maxPpOutPicWidthFuse = 0; hwFuseSts.ppConfigFuse = 0; } } else { hwFuseSts.ppSupportFuse = 0; hwFuseSts.maxPpOutPicWidthFuse = 0; hwFuseSts.ppConfigFuse = 0; } if (dec->maxDecPicWidth > hwFuseSts.maxDecPicWidthFuse) dec->maxDecPicWidth = hwFuseSts.maxDecPicWidthFuse; if (dec->maxPpOutPicWidth > hwFuseSts.maxPpOutPicWidthFuse) dec->maxPpOutPicWidth = hwFuseSts.maxPpOutPicWidthFuse; if (!hwFuseSts.h264SupportFuse) dec->h264Support = H264_NOT_SUPPORTED; if (!hwFuseSts.mpeg4SupportFuse) dec->mpeg4Support = MPEG4_NOT_SUPPORTED; if (!hwFuseSts.customMpeg4SupportFuse) dec->customMpeg4Support = MPEG4_CUSTOM_NOT_SUPPORTED; if (!hwFuseSts.jpegSupportFuse) dec->jpegSupport = JPEG_NOT_SUPPORTED; if ((dec->jpegSupport == JPEG_PROGRESSIVE) && !hwFuseSts.jpegProgSupportFuse) dec->jpegSupport = JPEG_BASELINE; if (!hwFuseSts.mpeg2SupportFuse) dec->mpeg2Support = MPEG2_NOT_SUPPORTED; if (!hwFuseSts.vc1SupportFuse) dec->vc1Support = VC1_NOT_SUPPORTED; if (!hwFuseSts.vp6SupportFuse) dec->vp6Support = VP6_NOT_SUPPORTED; if (!hwFuseSts.vp7SupportFuse) dec->vp7Support = VP7_NOT_SUPPORTED; if (!hwFuseSts.vp8SupportFuse) dec->vp8Support = VP8_NOT_SUPPORTED; if (!hwFuseSts.ppSupportFuse) dec->ppSupport = PP_NOT_SUPPORTED; /* check the pp config vs fuse status */ if ((dec->ppConfig & 0xFC000000) && ((hwFuseSts.ppConfigFuse & 0xF0000000) >> 5)) { u32 deInterlace = ((dec->ppConfig & PP_DEINTERLACING) >> 25); u32 alphaBlend = ((dec->ppConfig & PP_ALPHA_BLENDING) >> 24); u32 deInterlaceFuse = (((hwFuseSts.ppConfigFuse >> 5) & PP_DEINTERLACING) >> 25); u32 alphaBlendFuse = (((hwFuseSts.ppConfigFuse >> 5) & PP_ALPHA_BLENDING) >> 24); if (deInterlace && !deInterlaceFuse) dec->ppConfig &= 0xFD000000; if (alphaBlend && !alphaBlendFuse) dec->ppConfig &= 0xFE000000; } if (!hwFuseSts.sorensonSparkSupportFuse) dec->sorensonSparkSupport = SORENSON_SPARK_NOT_SUPPORTED; if (!hwFuseSts.refBufSupportFuse) dec->refBufSupport = REF_BUF_NOT_SUPPORTED; if (!hwFuseSts.rvSupportFuse) dec->rvSupport = RV_NOT_SUPPORTED; if (!hwFuseSts.avsSupportFuse) dec->avsSupport = AVS_NOT_SUPPORTED; if (!hwFuseSts.mvcSupportFuse) dec->mvcSupport = MVC_NOT_SUPPORTED; } } configReg = pservice->enc_dev.hwregs[63]; enc->maxEncodedWidth = configReg & ((1 << 11) - 1); enc->h264Enabled = (configReg >> 27) & 1; enc->mpeg4Enabled = (configReg >> 26) & 1; enc->jpegEnabled = (configReg >> 25) & 1; enc->vsEnabled = (configReg >> 24) & 1; enc->rgbEnabled = (configReg >> 28) & 1; //enc->busType = (configReg >> 20) & 15; //enc->synthesisLanguage = (configReg >> 16) & 15; //enc->busWidth = (configReg >> 12) & 15; enc->reg_size = pservice->reg_size; enc->reserv[0] = enc->reserv[1] = 0; pservice->auto_freq = soc_is_rk2928g() || soc_is_rk2928l() || soc_is_rk2926() || soc_is_rk3288(); if (pservice->auto_freq) { pr_info("vpu_service set to auto frequency mode\n"); atomic_set(&pservice->freq_status, VPU_FREQ_BUT); } pservice->bug_dec_addr = cpu_is_rk30xx(); //printk("cpu 3066b bug %d\n", service.bug_dec_addr); } else { // disable frequency switch in hevc. pservice->auto_freq = false; } } static irqreturn_t vdpu_irq(int irq, void *dev_id) { struct vpu_service_info *pservice = (struct vpu_service_info*)dev_id; vpu_device *dev = &pservice->dec_dev; u32 raw_status; u32 irq_status = raw_status = readl(dev->hwregs + DEC_INTERRUPT_REGISTER); pr_debug("dec_irq\n"); if (irq_status & DEC_INTERRUPT_BIT) { pr_debug("dec_isr dec %x\n", irq_status); if ((irq_status & 0x40001) == 0x40001) { do { irq_status = readl(dev->hwregs + DEC_INTERRUPT_REGISTER); } while ((irq_status & 0x40001) == 0x40001); } /* clear dec IRQ */ if (pservice->hw_info->hw_id != HEVC_ID) { writel(irq_status & (~DEC_INTERRUPT_BIT|DEC_BUFFER_EMPTY_BIT), dev->hwregs + DEC_INTERRUPT_REGISTER); } else { /*writel(irq_status & (~(DEC_INTERRUPT_BIT|HEVC_DEC_INT_RAW_BIT|HEVC_DEC_STR_ERROR_BIT|HEVC_DEC_BUS_ERROR_BIT|HEVC_DEC_BUFFER_EMPTY_BIT)), dev->hwregs + DEC_INTERRUPT_REGISTER);*/ writel(0, dev->hwregs + DEC_INTERRUPT_REGISTER); } atomic_add(1, &dev->irq_count_codec); } if (pservice->hw_info->hw_id != HEVC_ID) { irq_status = readl(dev->hwregs + PP_INTERRUPT_REGISTER); if (irq_status & PP_INTERRUPT_BIT) { pr_debug("vdpu_isr pp %x\n", irq_status); /* clear pp IRQ */ writel(irq_status & (~DEC_INTERRUPT_BIT), dev->hwregs + PP_INTERRUPT_REGISTER); atomic_add(1, &dev->irq_count_pp); } } pservice->irq_status = raw_status; return IRQ_WAKE_THREAD; } static irqreturn_t vdpu_isr(int irq, void *dev_id) { struct vpu_service_info *pservice = (struct vpu_service_info*)dev_id; vpu_device *dev = &pservice->dec_dev; mutex_lock(&pservice->lock); if (atomic_read(&dev->irq_count_codec)) { #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&dec_end); pr_info("dec task: %ld ms\n", (dec_end.tv_sec - dec_start.tv_sec) * 1000 + (dec_end.tv_usec - dec_start.tv_usec) / 1000); #endif atomic_sub(1, &dev->irq_count_codec); if (NULL == pservice->reg_codec) { pr_err("error: dec isr with no task waiting\n"); } else { reg_from_run_to_done(pservice, pservice->reg_codec); } } if (atomic_read(&dev->irq_count_pp)) { #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&pp_end); printk("pp task: %ld ms\n", (pp_end.tv_sec - pp_start.tv_sec) * 1000 + (pp_end.tv_usec - pp_start.tv_usec) / 1000); #endif atomic_sub(1, &dev->irq_count_pp); if (NULL == pservice->reg_pproc) { pr_err("error: pp isr with no task waiting\n"); } else { reg_from_run_to_done(pservice, pservice->reg_pproc); } } try_set_reg(pservice); mutex_unlock(&pservice->lock); return IRQ_HANDLED; } static irqreturn_t vepu_irq(int irq, void *dev_id) { //struct vpu_device *dev = (struct vpu_device *) dev_id; struct vpu_service_info *pservice = (struct vpu_service_info*)dev_id; vpu_device *dev = &pservice->enc_dev; u32 irq_status = readl(dev->hwregs + ENC_INTERRUPT_REGISTER); pr_debug("vepu_irq irq status %x\n", irq_status); #if VPU_SERVICE_SHOW_TIME do_gettimeofday(&enc_end); pr_info("enc task: %ld ms\n", (enc_end.tv_sec - enc_start.tv_sec) * 1000 + (enc_end.tv_usec - enc_start.tv_usec) / 1000); #endif if (likely(irq_status & ENC_INTERRUPT_BIT)) { /* clear enc IRQ */ writel(irq_status & (~ENC_INTERRUPT_BIT), dev->hwregs + ENC_INTERRUPT_REGISTER); atomic_add(1, &dev->irq_count_codec); } pservice->irq_status = irq_status; return IRQ_WAKE_THREAD; } static irqreturn_t vepu_isr(int irq, void *dev_id) { //struct vpu_device *dev = (struct vpu_device *) dev_id; struct vpu_service_info *pservice = (struct vpu_service_info*)dev_id; vpu_device *dev = &pservice->enc_dev; mutex_lock(&pservice->lock); if (atomic_read(&dev->irq_count_codec)) { atomic_sub(1, &dev->irq_count_codec); if (NULL == pservice->reg_codec) { pr_err("error: enc isr with no task waiting\n"); } else { reg_from_run_to_done(pservice, pservice->reg_codec); } } try_set_reg(pservice); mutex_unlock(&pservice->lock); return IRQ_HANDLED; } static int __init vcodec_service_init(void) { int ret; if ((ret = platform_driver_register(&vcodec_driver)) != 0) { pr_err("Platform device register failed (%d).\n", ret); return ret; } #ifdef CONFIG_DEBUG_FS vcodec_debugfs_init(); #endif return ret; } static void __exit vcodec_service_exit(void) { #ifdef CONFIG_DEBUG_FS vcodec_debugfs_exit(); #endif platform_driver_unregister(&vcodec_driver); } module_init(vcodec_service_init); module_exit(vcodec_service_exit); #ifdef CONFIG_DEBUG_FS #include <linux/seq_file.h> static int vcodec_debugfs_init() { parent = debugfs_create_dir("vcodec", NULL); if (!parent) return -1; return 0; } static void vcodec_debugfs_exit() { debugfs_remove(parent); } static struct dentry* vcodec_debugfs_create_device_dir(char *dirname, struct dentry *parent) { return debugfs_create_dir(dirname, parent); } static int debug_vcodec_show(struct seq_file *s, void *unused) { struct vpu_service_info *pservice = s->private; unsigned int i, n; vpu_reg *reg, *reg_tmp; vpu_session *session, *session_tmp; mutex_lock(&pservice->lock); vpu_service_power_on(pservice); if (pservice->hw_info->hw_id != HEVC_ID) { seq_printf(s, "\nENC Registers:\n"); n = pservice->enc_dev.iosize >> 2; for (i = 0; i < n; i++) { seq_printf(s, "\tswreg%d = %08X\n", i, readl(pservice->enc_dev.hwregs + i)); } } seq_printf(s, "\nDEC Registers:\n"); n = pservice->dec_dev.iosize >> 2; for (i = 0; i < n; i++) { seq_printf(s, "\tswreg%d = %08X\n", i, readl(pservice->dec_dev.hwregs + i)); } seq_printf(s, "\nvpu service status:\n"); list_for_each_entry_safe(session, session_tmp, &pservice->session, list_session) { seq_printf(s, "session pid %d type %d:\n", session->pid, session->type); //seq_printf(s, "waiting reg set %d\n"); list_for_each_entry_safe(reg, reg_tmp, &session->waiting, session_link) { seq_printf(s, "waiting register set\n"); } list_for_each_entry_safe(reg, reg_tmp, &session->running, session_link) { seq_printf(s, "running register set\n"); } list_for_each_entry_safe(reg, reg_tmp, &session->done, session_link) { seq_printf(s, "done register set\n"); } } mutex_unlock(&pservice->lock); return 0; } static int debug_vcodec_open(struct inode *inode, struct file *file) { return single_open(file, debug_vcodec_show, inode->i_private); } #endif #if HEVC_TEST_ENABLE & defined(CONFIG_ION_ROCKCHIP) #include "hevc_test_inc/pps_00.h" #include "hevc_test_inc/register_00.h" #include "hevc_test_inc/rps_00.h" #include "hevc_test_inc/scaling_list_00.h" #include "hevc_test_inc/stream_00.h" #include "hevc_test_inc/pps_01.h" #include "hevc_test_inc/register_01.h" #include "hevc_test_inc/rps_01.h" #include "hevc_test_inc/scaling_list_01.h" #include "hevc_test_inc/stream_01.h" #include "hevc_test_inc/cabac.h" extern struct ion_client *rockchip_ion_client_create(const char * name); static struct ion_client *ion_client = NULL; u8* get_align_ptr(u8* tbl, int len, u32 *phy) { int size = (len+15) & (~15); struct ion_handle *handle; u8 *ptr;// = (u8*)kzalloc(size, GFP_KERNEL); if (ion_client == NULL) { ion_client = rockchip_ion_client_create("vcodec"); } handle = ion_alloc(ion_client, (size_t)len, 16, ION_HEAP(ION_CMA_HEAP_ID), 0); ptr = ion_map_kernel(ion_client, handle); ion_phys(ion_client, handle, phy, &size); memcpy(ptr, tbl, len); return ptr; } u8* get_align_ptr_no_copy(int len, u32 *phy) { int size = (len+15) & (~15); struct ion_handle *handle; u8 *ptr;// = (u8*)kzalloc(size, GFP_KERNEL); if (ion_client == NULL) { ion_client = rockchip_ion_client_create("vcodec"); } handle = ion_alloc(ion_client, (size_t)len, 16, ION_HEAP(ION_CMA_HEAP_ID), 0); ptr = ion_map_kernel(ion_client, handle); ion_phys(ion_client, handle, phy, &size); return ptr; } #define TEST_CNT 2 static int hevc_test_case0(vpu_service_info *pservice) { vpu_session session; vpu_reg *reg; unsigned long size = 272;//sizeof(register_00); // registers array length int testidx = 0; int ret = 0; u8 *pps_tbl[TEST_CNT]; u8 *register_tbl[TEST_CNT]; u8 *rps_tbl[TEST_CNT]; u8 *scaling_list_tbl[TEST_CNT]; u8 *stream_tbl[TEST_CNT]; int stream_size[2]; int pps_size[2]; int rps_size[2]; int scl_size[2]; int cabac_size[2]; u32 phy_pps; u32 phy_rps; u32 phy_scl; u32 phy_str; u32 phy_yuv; u32 phy_ref; u32 phy_cabac; volatile u8 *stream_buf; volatile u8 *pps_buf; volatile u8 *rps_buf; volatile u8 *scl_buf; volatile u8 *yuv_buf; volatile u8 *cabac_buf; volatile u8 *ref_buf; u8 *pps; u8 *yuv[2]; int i; pps_tbl[0] = pps_00; pps_tbl[1] = pps_01; register_tbl[0] = register_00; register_tbl[1] = register_01; rps_tbl[0] = rps_00; rps_tbl[1] = rps_01; scaling_list_tbl[0] = scaling_list_00; scaling_list_tbl[1] = scaling_list_01; stream_tbl[0] = stream_00; stream_tbl[1] = stream_01; stream_size[0] = sizeof(stream_00); stream_size[1] = sizeof(stream_01); pps_size[0] = sizeof(pps_00); pps_size[1] = sizeof(pps_01); rps_size[0] = sizeof(rps_00); rps_size[1] = sizeof(rps_01); scl_size[0] = sizeof(scaling_list_00); scl_size[1] = sizeof(scaling_list_01); cabac_size[0] = sizeof(Cabac_table); cabac_size[1] = sizeof(Cabac_table); // create session session.pid = current->pid; session.type = VPU_DEC; INIT_LIST_HEAD(&session.waiting); INIT_LIST_HEAD(&session.running); INIT_LIST_HEAD(&session.done); INIT_LIST_HEAD(&session.list_session); init_waitqueue_head(&session.wait); atomic_set(&session.task_running, 0); list_add_tail(&session.list_session, &pservice->session); yuv[0] = get_align_ptr_no_copy(256*256*2, &phy_yuv); yuv[1] = get_align_ptr_no_copy(256*256*2, &phy_ref); while (testidx < TEST_CNT) { // create registers reg = kmalloc(sizeof(vpu_reg)+pservice->reg_size, GFP_KERNEL); if (NULL == reg) { pr_err("error: kmalloc fail in reg_init\n"); return -1; } if (size > pservice->reg_size) { printk("warning: vpu reg size %lu is larger than hw reg size %lu\n", size, pservice->reg_size); size = pservice->reg_size; } reg->session = &session; reg->type = session.type; reg->size = size; reg->freq = VPU_FREQ_DEFAULT; reg->reg = (unsigned long *)&reg[1]; INIT_LIST_HEAD(&reg->session_link); INIT_LIST_HEAD(&reg->status_link); // TODO: stuff registers memcpy(&reg->reg[0], register_tbl[testidx], /*sizeof(register_00)*/ 176); stream_buf = get_align_ptr(stream_tbl[testidx], stream_size[testidx], &phy_str); pps_buf = get_align_ptr(pps_tbl[0], pps_size[0], &phy_pps); rps_buf = get_align_ptr(rps_tbl[testidx], rps_size[testidx], &phy_rps); scl_buf = get_align_ptr(scaling_list_tbl[testidx], scl_size[testidx], &phy_scl); cabac_buf = get_align_ptr(Cabac_table, cabac_size[testidx], &phy_cabac); pps = pps_buf; // TODO: replace reigster address for (i=0; i<64; i++) { u32 scaling_offset; u32 tmp; scaling_offset = (u32)pps[i*80+74]; scaling_offset += (u32)pps[i*80+75] << 8; scaling_offset += (u32)pps[i*80+76] << 16; scaling_offset += (u32)pps[i*80+77] << 24; tmp = phy_scl + scaling_offset; pps[i*80+74] = tmp & 0xff; pps[i*80+75] = (tmp >> 8) & 0xff; pps[i*80+76] = (tmp >> 16) & 0xff; pps[i*80+77] = (tmp >> 24) & 0xff; } printk("%s %d, phy stream %08x, phy pps %08x, phy rps %08x\n", __func__, __LINE__, phy_str, phy_pps, phy_rps); reg->reg[1] = 0x21; reg->reg[4] = phy_str; reg->reg[5] = ((stream_size[testidx]+15)&(~15))+64; reg->reg[6] = phy_cabac; reg->reg[7] = testidx?phy_ref:phy_yuv; reg->reg[42] = phy_pps; reg->reg[43] = phy_rps; for (i = 10; i <= 24; i++) { reg->reg[i] = phy_yuv; } mutex_lock(&pservice->lock); list_add_tail(&reg->status_link, &pservice->waiting); list_add_tail(&reg->session_link, &session.waiting); mutex_unlock(&pservice->lock); printk("%s %d %p\n", __func__, __LINE__, pservice); // stuff hardware try_set_reg(pservice); // wait for result ret = wait_event_timeout(session.wait, !list_empty(&session.done), VPU_TIMEOUT_DELAY); if (!list_empty(&session.done)) { if (ret < 0) { pr_err("warning: pid %d wait task sucess but wait_evernt ret %d\n", session.pid, ret); } ret = 0; } else { if (unlikely(ret < 0)) { pr_err("error: pid %d wait task ret %d\n", session.pid, ret); } else if (0 == ret) { pr_err("error: pid %d wait %d task done timeout\n", session.pid, atomic_read(&session.task_running)); ret = -ETIMEDOUT; } } if (ret < 0) { int task_running = atomic_read(&session.task_running); int n; mutex_lock(&pservice->lock); vpu_service_dump(pservice); if (task_running) { atomic_set(&session.task_running, 0); atomic_sub(task_running, &pservice->total_running); printk("%d task is running but not return, reset hardware...", task_running); vpu_reset(pservice); printk("done\n"); } vpu_service_session_clear(pservice, &session); mutex_unlock(&pservice->lock); printk("\nDEC Registers:\n"); n = pservice->dec_dev.iosize >> 2; for (i=0; i<n; i++) { printk("\tswreg%d = %08X\n", i, readl(pservice->dec_dev.hwregs + i)); } pr_err("test index %d failed\n", testidx); break; } else { pr_info("test index %d success\n", testidx); vpu_reg *reg = list_entry(session.done.next, vpu_reg, session_link); for (i=0; i<68; i++) { if (i % 4 == 0) { printk("%02d: ", i); } printk("%08x ", reg->reg[i]); if ((i+1) % 4 == 0) { printk("\n"); } } testidx++; } reg_deinit(pservice, reg); } return 0; } #endif
crewrktablets/rk3x_kernel_3.10
arch/arm/mach-rockchip/vcodec_service.c
C
gpl-2.0
73,376
<?php /** * Order tracking form * * @author WooThemes * @package WooCommerce/Templates * @version 2.0.0 * * Edited by WebMan */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce, $post; ?> <form action="<?php echo esc_url( get_permalink($post->ID) ); ?>" method="post" class="track_order"> <p><?php _e( 'To track your order please enter your Order ID in the box below and press return. This was given to you on your receipt and in the confirmation email you should have received.', 'woocommerce' ); ?></p> <div class="clear mt20"></div> <p class="form-row column col-12"><label for="orderid"><?php _e('Order ID', 'woocommerce'); ?></label> <input class="input-text" type="text" name="orderid" id="orderid" placeholder="<?php _e('Found in your order confirmation email.', 'woocommerce'); ?>" /></p> <p class="form-row column col-12 last"><label for="order_email"><?php _e('Billing Email', 'woocommerce'); ?></label> <input class="input-text" type="text" name="order_email" id="order_email" placeholder="<?php _e('Email you used during checkout.', 'woocommerce'); ?>" /></p> <div class="clear"></div> <p class="form-row"><input type="submit" class="button" name="track" value="<?php _e( 'Track', 'woocommerce' ); ?>" /></p> <?php $woocommerce->nonce_field('order_tracking') ?> </form>
samuelmolinski/miniature-octo-archer
wp-content/themes/atlantes/woocommerce/order/form-tracking.php
PHP
gpl-2.0
1,333
<?php // no direct access defined('_JEXEC') or die('Restricted access'); ?> <script language="javascript" type="text/javascript"> function tableOrdering( order, dir, task ) { var form = document.adminForm; form.filter_order.value = order; form.filter_order_Dir.value = dir; document.adminForm.submit( task ); } </script> <form action="<?php echo $this->action; ?>" method="post" name="adminForm"> <?php if ($this->params->get('filter') || $this->params->get('show_pagination_limit')) : ?> <?php if ($this->params->get('show_pagination_limit')) : ?> <div class="jsn-infofilter"> <?php if ($this->params->get('filter')) : ?> <span class="jsn-titlefilter"> <?php echo JText::_($this->params->get('filter_type') . ' Filter').'&nbsp;'; ?> <input type="text" name="filter" value="<?php echo $this->escape($this->lists['filter']);?>" class="inputbox" onchange="document.adminForm.submit();" /> </span> <?php endif; ?> <?php echo '&nbsp;&nbsp;&nbsp;'.JText::_('Display Num').'&nbsp;'; echo $this->pagination->getLimitBox(); ?> </div> <?php endif; ?> <?php endif; ?> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="jsn-infotable"> <?php if ($this->params->get('show_headings')) : ?> <tr class="jsn-tableheader"> <td class="sectiontableheader" align="right" width="5%"> <?php echo JText::_('Num'); ?> </td> <?php if ($this->params->get('show_title')) : ?> <td class="sectiontableheader" width="45%"> <?php echo JHTML::_('grid.sort', 'Item Title', 'a.title', $this->lists['order_Dir'], $this->lists['order'] ); ?> </td> <?php endif; ?> <?php if ($this->params->get('show_date')) : ?> <td class="sectiontableheader" width="25%"> <?php echo JHTML::_('grid.sort', 'Date', 'a.created', $this->lists['order_Dir'], $this->lists['order'] ); ?> </td> <?php endif; ?> <?php if ($this->params->get('show_author')) : ?> <td class="sectiontableheader" width="20%"> <?php echo JHTML::_('grid.sort', 'Author', 'author', $this->lists['order_Dir'], $this->lists['order'] ); ?> </td> <?php endif; ?> <?php if ($this->params->get('show_hits')) : ?> <td align="center" class="sectiontableheader" width="5%" nowrap="nowrap"> <?php echo JHTML::_('grid.sort', 'Hits', 'a.hits', $this->lists['order_Dir'], $this->lists['order'] ); ?> </td> <?php endif; ?> </tr> <?php endif; ?> <?php foreach ($this->items as $item) : ?> <tr class="sectiontableentry<?php echo ($item->odd +1 ) ." ". $this->params->get( 'pageclass_sfx' ); ?>" > <td align="right"> <?php echo $this->pagination->getRowOffset( $item->count ); ?> </td> <?php if ($this->params->get('show_title')) : ?> <?php if ($item->access <= $this->user->get('aid', 0)) : ?> <td> <a href="<?php echo $item->link; ?>"> <?php echo $item->title; ?></a> <?php $this->item = $item; echo JHTML::_('icon.edit', $item, $this->params, $this->access) ?> </td> <?php else : ?> <td> <?php echo $this->escape($item->title).' : '; $link = JRoute::_('index.php?option=com_user&view=login'); $returnURL = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug, $item->sectionid), false); $fullURL = new JURI($link); $fullURL->setVar('return', base64_encode($returnURL)); $link = $fullURL->toString(); ?> <a href="<?php echo $link; ?>"> <?php echo JText::_( 'Register to read more...' ); ?></a> </td> <?php endif; ?> <?php endif; ?> <?php if ($this->params->get('show_date')) : ?> <td> <?php echo $item->created; ?> </td> <?php endif; ?> <?php if ($this->params->get('show_author')) : ?> <td > <?php echo $item->created_by_alias ? $item->created_by_alias : $item->author; ?> </td> <?php endif; ?> <?php if ($this->params->get('show_hits')) : ?> <td align="center"> <?php echo $item->hits ? $item->hits : '-'; ?> </td> <?php endif; ?> </tr> <?php endforeach; ?> </table> <?php if ($this->params->get('show_pagination', 2)) : ?> <div class="jsn-pagination"><?php echo $this->pagination->getPagesLinks(); ?></div> <?php endif; ?> <?php if ($this->params->get('show_pagination_results', 1)) : ?> <p class="jsn-pageinfo"><?php echo $this->pagination->getPagesCounter(); ?></p> <?php endif; ?> <input type="hidden" name="id" value="<?php echo $this->category->id; ?>" /> <input type="hidden" name="sectionid" value="<?php echo $this->category->sectionid; ?>" /> <input type="hidden" name="task" value="<?php echo $this->lists['task']; ?>" /> <input type="hidden" name="filter_order" value="" /> <input type="hidden" name="filter_order_Dir" value="" /> <input type="hidden" name="limitstart" value="0" /> </form>
w2/ctb
templates/jsn_dome_free/html/com_content2/category/default_items.php
PHP
gpl-2.0
4,614
package kc.spark.pixels.android.ui.assets; import static org.solemnsilence.util.Py.map; import java.util.Map; import android.content.Context; import android.graphics.Typeface; public class Typefaces { // NOTE: this is tightly coupled to the filenames in assets/fonts public static enum Style { BOLD("Arial.ttf"), BOLD_ITALIC("Arial.ttf"), BOOK("Arial.ttf"), BOOK_ITALIC("Arial.ttf"), LIGHT("Arial.ttf"), LIGHT_ITALIC("Arial.ttf"), MEDIUM("Arial.ttf"), MEDIUM_ITALIC("Arial.ttf"); // BOLD("gotham_bold.otf"), // BOLD_ITALIC("gotham_bold_ita.otf"), // BOOK("gotham_book.otf"), // BOOK_ITALIC("gotham_book_ita.otf"), // LIGHT("gotham_light.otf"), // LIGHT_ITALIC("gotham_light_ita.otf"), // MEDIUM("gotham_medium.otf"), // MEDIUM_ITALIC("gotham_medium_ita.otf"); public final String fileName; private Style(String name) { fileName = name; } } private static final Map<Style, Typeface> typefaces = map(); public static Typeface getTypeface(Context ctx, Style style) { Typeface face = typefaces.get(style); if (face == null) { face = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + style.fileName); typefaces.put(style, face); } return face; } }
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java
Java
gpl-2.0
1,212
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @bug 4922813 @summary Check the new impl of encodePath will not cause regression @key randomness */ import java.util.BitSet; import java.io.File; import java.util.Random; import sun.net.www.ParseUtil; public class ParseUtil_4922813 { public static void main(String[] argv) throws Exception { int num = 400; while (num-- >= 0) { String source = getTestSource(); String ec = sun.net.www.ParseUtil.encodePath(source); String v117 = ParseUtil_V117.encodePath(source); if (!ec.equals(v117)) { throw new RuntimeException("Test Failed for : \n" + " source =<" + getUnicodeString(source) + ">"); } } } static int maxCharCount = 200; static int maxCodePoint = 0x10ffff; static Random random; static String getTestSource() { if (random == null) { long seed = System.currentTimeMillis(); random = new Random(seed); } String source = ""; int i = 0; int count = random.nextInt(maxCharCount) + 1; while (i < count) { int codepoint = random.nextInt(127); source = source + String.valueOf((char)codepoint); codepoint = random.nextInt(0x7ff); source = source + String.valueOf((char)codepoint); codepoint = random.nextInt(maxCodePoint); source = source + new String(Character.toChars(codepoint)); i += 3; } return source; } static String getUnicodeString(String s){ String unicodeString = ""; for(int j=0; j< s.length(); j++){ unicodeString += "0x"+ Integer.toString(s.charAt(j), 16); } return unicodeString; } } class ParseUtil_V117 { static BitSet encodedInPath; static { encodedInPath = new BitSet(256); // Set the bits corresponding to characters that are encoded in the // path component of a URI. // These characters are reserved in the path segment as described in // RFC2396 section 3.3. encodedInPath.set('='); encodedInPath.set(';'); encodedInPath.set('?'); encodedInPath.set('/'); // These characters are defined as excluded in RFC2396 section 2.4.3 // and must be escaped if they occur in the data part of a URI. encodedInPath.set('#'); encodedInPath.set(' '); encodedInPath.set('<'); encodedInPath.set('>'); encodedInPath.set('%'); encodedInPath.set('"'); encodedInPath.set('{'); encodedInPath.set('}'); encodedInPath.set('|'); encodedInPath.set('\\'); encodedInPath.set('^'); encodedInPath.set('['); encodedInPath.set(']'); encodedInPath.set('`'); // US ASCII control characters 00-1F and 7F. for (int i=0; i<32; i++) encodedInPath.set(i); encodedInPath.set(127); } /** * Constructs an encoded version of the specified path string suitable * for use in the construction of a URL. * * A path separator is replaced by a forward slash. The string is UTF8 * encoded. The % escape sequence is used for characters that are above * 0x7F or those defined in RFC2396 as reserved or excluded in the path * component of a URL. */ public static String encodePath(String path) { StringBuffer sb = new StringBuffer(); int n = path.length(); for (int i=0; i<n; i++) { char c = path.charAt(i); if (c == File.separatorChar) sb.append('/'); else { if (c <= 0x007F) { if (encodedInPath.get(c)) escape(sb, c); else sb.append(c); } else if (c > 0x07FF) { escape(sb, (char)(0xE0 | ((c >> 12) & 0x0F))); escape(sb, (char)(0x80 | ((c >> 6) & 0x3F))); escape(sb, (char)(0x80 | ((c >> 0) & 0x3F))); } else { escape(sb, (char)(0xC0 | ((c >> 6) & 0x1F))); escape(sb, (char)(0x80 | ((c >> 0) & 0x3F))); } } } return sb.toString(); } /** * Appends the URL escape sequence for the specified char to the * specified StringBuffer. */ private static void escape(StringBuffer s, char c) { s.append('%'); s.append(Character.forDigit((c >> 4) & 0xF, 16)); s.append(Character.forDigit(c & 0xF, 16)); } }
openjdk/jdk8u
jdk/test/sun/net/www/ParseUtil_4922813.java
Java
gpl-2.0
5,843
#ifndef __ASM_MAPLE_H #define __ASM_MAPLE_H #define MAPLE_PORTS 4 #define MAPLE_PNP_INTERVAL HZ #define MAPLE_MAXPACKETS 8 #define MAPLE_DMA_ORDER 14 #define MAPLE_DMA_SIZE (1 << MAPLE_DMA_ORDER) #define MAPLE_DMA_PAGES ((MAPLE_DMA_ORDER > PAGE_SHIFT) ? \ MAPLE_DMA_ORDER - PAGE_SHIFT : 0) /* Maple Bus registers */ #define MAPLE_BASE 0xa05f6c00 #define MAPLE_DMAADDR (MAPLE_BASE+0x04) #define MAPLE_TRIGTYPE (MAPLE_BASE+0x10) #define MAPLE_ENABLE (MAPLE_BASE+0x14) #define MAPLE_STATE (MAPLE_BASE+0x18) #define MAPLE_SPEED (MAPLE_BASE+0x80) #define MAPLE_RESET (MAPLE_BASE+0x8c) #define MAPLE_MAGIC 0x6155404f #define MAPLE_2MBPS 0 #define MAPLE_TIMEOUT(n) ((n)<<15) /* Function codes */ #define MAPLE_FUNC_CONTROLLER 0x001 #define MAPLE_FUNC_MEMCARD 0x002 #define MAPLE_FUNC_LCD 0x004 #define MAPLE_FUNC_CLOCK 0x008 #define MAPLE_FUNC_MICROPHONE 0x010 #define MAPLE_FUNC_ARGUN 0x020 #define MAPLE_FUNC_KEYBOARD 0x040 #define MAPLE_FUNC_LIGHTGUN 0x080 #define MAPLE_FUNC_PURUPURU 0x100 #define MAPLE_FUNC_MOUSE 0x200 #endif /* __ASM_MAPLE_H */
Jackeagle/android_kernel_sony_c2305
arch/sh/include/mach-dreamcast/mach/maple.h
C
gpl-2.0
1,145
import random from collections import namedtuple import dateparser import pytest from cfme import test_requirements from cfme.containers.image import Image from cfme.containers.provider import ContainersProvider from cfme.containers.provider import ContainersTestItem from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.meta(server_roles='+smartproxy'), pytest.mark.usefixtures('setup_provider'), pytest.mark.tier(1), pytest.mark.provider([ContainersProvider], scope='function'), test_requirements.containers ] AttributeToVerify = namedtuple('AttributeToVerify', ['table', 'attr', 'verifier']) TESTED_ATTRIBUTES__openscap_off = ( AttributeToVerify('configuration', 'OpenSCAP Results', bool), AttributeToVerify('configuration', 'OpenSCAP HTML', lambda val: val == 'Available'), AttributeToVerify('configuration', 'Last scan', dateparser.parse) ) TESTED_ATTRIBUTES__openscap_on = TESTED_ATTRIBUTES__openscap_off + ( AttributeToVerify('compliance', 'Status', lambda val: val.lower() != 'never verified'), AttributeToVerify('compliance', 'History', lambda val: val == 'Available') ) TEST_ITEMS = ( ContainersTestItem(Image, 'openscap_off', is_openscap=False, tested_attr=TESTED_ATTRIBUTES__openscap_off), ContainersTestItem(Image, 'openscap_on', is_openscap=True, tested_attr=TESTED_ATTRIBUTES__openscap_on) ) NUM_SELECTED_IMAGES = 1 @pytest.fixture(scope='function') def delete_all_container_tasks(appliance): col = appliance.collections.tasks.filter({'tab': 'AllTasks'}) col.delete_all() @pytest.fixture(scope='function') def random_image_instance(appliance): collection = appliance.collections.container_images # add filter for select only active(not archived) images from redHat registry filter_image_collection = collection.filter({'active': True, 'redhat_registry': True}) return random.sample(filter_image_collection.all(), NUM_SELECTED_IMAGES).pop() @pytest.mark.polarion('10030') def test_manage_policies_navigation(random_image_instance): """ Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """ random_image_instance.assign_policy_profiles('OpenSCAP profile') @pytest.mark.polarion('10031') def test_check_compliance(random_image_instance): """ Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """ random_image_instance.assign_policy_profiles('OpenSCAP profile') random_image_instance.check_compliance() def get_table_attr(instance, table_name, attr): # Trying to read the table <table_name> attribute <attr> view = navigate_to(instance, 'Details', force=True) table = getattr(view.entities, table_name, None) if table: return table.read().get(attr) @pytest.mark.parametrize(('test_item'), TEST_ITEMS) def test_containers_smartstate_analysis(provider, test_item, soft_assert, delete_all_container_tasks, random_image_instance): """ Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """ if test_item.is_openscap: random_image_instance.assign_policy_profiles('OpenSCAP profile') else: random_image_instance.unassign_policy_profiles('OpenSCAP profile') random_image_instance.perform_smartstate_analysis(wait_for_finish=True) view = navigate_to(random_image_instance, 'Details') for tbl, attr, verifier in test_item.tested_attr: table = getattr(view.entities, tbl) table_data = {k.lower(): v for k, v in table.read().items()} if not soft_assert(attr.lower() in table_data, f'{tbl} table has missing attribute \'{attr}\''): continue provider.refresh_provider_relationships() wait_for_retval = wait_for(lambda: get_table_attr(random_image_instance, tbl, attr), message='Trying to get attribute "{}" of table "{}"'.format( attr, tbl), delay=5, num_sec=120, silent_failure=True) if not wait_for_retval: soft_assert(False, 'Could not get attribute "{}" for "{}" table.' .format(attr, tbl)) continue value = wait_for_retval.out soft_assert(verifier(value), f'{tbl}.{attr} attribute has unexpected value ({value})') @pytest.mark.parametrize(('test_item'), TEST_ITEMS) def test_containers_smartstate_analysis_api(provider, test_item, soft_assert, delete_all_container_tasks, random_image_instance): """ Test initiating a SmartState Analysis scan via the CFME API through the ManageIQ API Client entity class. RFE: BZ 1486362 Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """ if test_item.is_openscap: random_image_instance.assign_policy_profiles('OpenSCAP profile') else: random_image_instance.unassign_policy_profiles('OpenSCAP profile') original_scan = random_image_instance.last_scan_attempt_on random_image_instance.scan() task = provider.appliance.collections.tasks.instantiate( name=f"Container Image Analysis: '{random_image_instance.name}'", tab='AllTasks') task.wait_for_finished() soft_assert(original_scan != random_image_instance.last_scan_attempt_on, 'SmartState Anaysis scan has failed')
nachandr/cfme_tests
cfme/tests/containers/test_containers_smartstate_analysis.py
Python
gpl-2.0
5,838
/* * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool * Copyright(C) 2004-2006 Riad Djemili * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package jmemorize.core.test; import java.io.File; import java.io.IOException; import java.util.List; import jmemorize.core.Card; import jmemorize.core.Lesson; import jmemorize.core.LessonObserver; import jmemorize.core.LessonProvider; import jmemorize.core.Main; import junit.framework.TestCase; public class LessonProviderTest extends TestCase implements LessonObserver { private LessonProvider m_lessonProvider; private StringBuffer m_log; protected void setUp() throws Exception { m_lessonProvider = new Main(); m_lessonProvider.addLessonObserver(this); m_log = new StringBuffer(); } public void testLessonNewEvent() { m_lessonProvider.createNewLesson(); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedEvent() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedCardsAlwaysHaveExpiration() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/no_expiration.jml")); Lesson lesson = m_lessonProvider.getLesson(); List<Card> cards = lesson.getRootCategory().getCards(); for (Card card : cards) { if (card.getLevel() > 0) assertNotNull(card.getDateExpired()); else assertNull(card.getDateExpired()); } } public void testLessonLoadedClosedNewEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.createNewLesson(); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonLoadedClosedLoadEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.loadLesson(new File("test/fixtures/test.jml")); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonSavedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); m_lessonProvider.saveLesson(lesson, new File("./test.jml")); assertEquals("loaded saved ", m_log.toString()); } public void testLessonModifiedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); lesson.getRootCategory().addCard(new Card("front", "flip")); assertEquals("loaded modified ", m_log.toString()); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonLoaded(Lesson lesson) { m_log.append("loaded "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonModified(Lesson lesson) { m_log.append("modified "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonSaved(Lesson lesson) { m_log.append("saved "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonClosed(Lesson lesson) { m_log.append("closed "); } }
riadd/jMemorize
src/jmemorize/core/test/LessonProviderTest.java
Java
gpl-2.0
4,360
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. currentmodule:: __init__.py .. moduleauthor:: Pat Daburu <[email protected]> Provide a brief description of the module. """
patdaburu/mothergeo-py
mothergeo/db/postgis/__init__.py
Python
gpl-2.0
175
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.multithread; import junit.framework.TestCase; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.Configuration; import com.espertech.esper.support.bean.SupportTradeEvent; import com.espertech.esper.multithread.TwoPatternRunnable; /** * Test for multithread-safety for case of 2 patterns: * 1. Thread 1 starts pattern "every event1=SupportEvent(userID in ('100','101'), amount>=1000)" * 2. Thread 1 repeats sending 100 events and tests 5% received * 3. Main thread starts pattern: * ( every event1=SupportEvent(userID in ('100','101')) -> (SupportEvent(userID in ('100','101'), direction = event1.direction ) -> SupportEvent(userID in ('100','101'), direction = event1.direction ) ) where timer:within(8 hours) and not eventNC=SupportEvent(userID in ('100','101'), direction!= event1.direction ) ) -> eventFinal=SupportEvent(userID in ('100','101'), direction != event1.direction ) where timer:within(1 hour) * 4. Main thread waits for 2 seconds and stops all threads */ public class TestMTStmtTwoPatternsStartStop extends TestCase { private EPServiceProvider engine; public void setUp() { Configuration config = new Configuration(); config.addEventType("SupportEvent", SupportTradeEvent.class); engine = EPServiceProviderManager.getDefaultProvider(config); engine.initialize(); } public void tearDown() { engine.initialize(); } public void test2Patterns() throws Exception { String statementTwo = "( every event1=SupportEvent(userId in ('100','101')) ->\n" + " (SupportEvent(userId in ('100','101'), direction = event1.direction ) ->\n" + " SupportEvent(userId in ('100','101'), direction = event1.direction )\n" + " ) where timer:within(8 hours)\n" + " and not eventNC=SupportEvent(userId in ('100','101'), direction!= event1.direction )\n" + " ) -> eventFinal=SupportEvent(userId in ('100','101'), direction != event1.direction ) where timer:within(1 hour)"; TwoPatternRunnable runnable = new TwoPatternRunnable(engine); Thread t = new Thread(runnable); t.start(); Thread.sleep(200); // Create a second pattern, wait 200 msec, destroy second pattern in a loop for (int i = 0; i < 10; i++) { EPStatement statement = engine.getEPAdministrator().createPattern(statementTwo); Thread.sleep(200); statement.destroy(); } runnable.setShutdown(true); Thread.sleep(1000); assertFalse(t.isAlive()); } }
intelie/esper
esper/src/test/java/com/espertech/esper/multithread/TestMTStmtTwoPatternsStartStop.java
Java
gpl-2.0
3,675
/*****************************************************************************\ * $Id: genders_test_functionality.h,v 1.7 2010-02-02 00:04:34 chu11 Exp $ ***************************************************************************** * Copyright (C) 2007-2019 Lawrence Livermore National Security, LLC. * Copyright (C) 2001-2007 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Jim Garlick <[email protected]> and Albert Chu <[email protected]>. * UCRL-CODE-2003-004. * * This file is part of Genders, a cluster configuration database. * For details, see <http://www.llnl.gov/linux/genders/>. * * Genders is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * Genders is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with Genders. If not, see <http://www.gnu.org/licenses/>. \*****************************************************************************/ #ifndef _GENDERS_TEST_FUNCTIONALITY_H #define _GENDERS_TEST_FUNCTIONALITY_H 1 #include "genders.h" #include "genders_testlib.h" typedef int (*GendersFunctionalityFunc)(int); int genders_handle_create_functionality(int verbose); int genders_handle_destroy_functionality(int verbose); int genders_load_data_functionality(int verbose); int genders_errnum_functionality(int verbose); int genders_strerror_functionality(int verbose); int genders_errormsg_functionality(int verbose); int genders_perror_functionality(int verbose); int genders_get_flags_functionality(int verbose); int genders_set_flags_functionality(int verbose); int genders_getnumnodes_functionality(int verbose); int genders_getnumattrs_functionality(int verbose); int genders_getmaxattrs_functionality(int verbose); int genders_getmaxnodelen_functionality(int verbose); int genders_getmaxattrlen_functionality(int verbose); int genders_getmaxvallen_functionality(int verbose); int genders_nodelist_create_functionality(int verbose); int genders_nodelist_clear_functionality(int verbose); int genders_nodelist_destroy_functionality(int verbose); int genders_attrlist_create_functionality(int verbose); int genders_attrlist_clear_functionality(int verbose); int genders_attrlist_destroy_functionality(int verbose); int genders_vallist_create_functionality(int verbose); int genders_vallist_clear_functionality(int verbose); int genders_vallist_destroy_functionality(int verbose); int genders_getnodename_functionality(int verbose); int genders_getnodes_functionality(int verbose); int genders_getattr_functionality(int verbose); int genders_getattr_all_functionality(int verbose); int genders_testattr_functionality(int verbose); int genders_testattrval_functionality(int verbose); int genders_isnode_functionality(int verbose); int genders_isattr_functionality(int verbose); int genders_isattrval_functionality(int verbose); int genders_index_attrvals_functionality(int verbose); int genders_query_functionality(int verbose); int genders_testquery_functionality(int verbose); int genders_parse_functionality(int verbose); int genders_set_errnum_functionality(int verbose); int genders_copy_functionality(int verbose); #endif /* _GENDERS_TEST_FUNCTIONALITY_H */
BenCasses/genders
src/testsuite/libgenders/genders_test_functionality.h
C
gpl-2.0
3,639
VFS.Include("LuaRules/Utilities/numberfunctions.lua") -- math.triangulate local GRP = Spring.GetGameRulesParam local function GetRawBoxes() local ret = {} local boxCount = GRP("startbox_max_n") if not boxCount then return ret end for boxID = 0, boxCount do local polies = {} local polyCount = GRP("startbox_n_" .. boxID) if polyCount then for polyID = 1, polyCount do local poly = {} local vertexCount = GRP("startbox_polygon_" .. boxID .. "_" .. polyID) for vertexID = 1, vertexCount do local vertex = {} vertex[1] = GRP("startbox_polygon_x_" .. boxID .. "_" .. polyID .. "_" .. vertexID) vertex[2] = GRP("startbox_polygon_z_" .. boxID .. "_" .. polyID .. "_" .. vertexID) poly[vertexID] = vertex end polies[polyID] = poly end end local startpoints = {} local posCount = GRP("startpos_n_" .. boxID) if posCount then startpoints = {} for posID = 1, posCount do local pos = {} pos[1] = GRP("startpos_x_" .. boxID .. "_" .. posID) pos[2] = GRP("startpos_z_" .. boxID .. "_" .. posID) startpoints[posID] = pos end end if posCount or polyCount then ret[boxID] = { boxes = polies, startpoints = startpoints } end end return ret end local function GetTriangulatedBoxes() local boxes = GetRawBoxes() for boxID, box in pairs(boxes) do box.boxes = math.triangulate(box.boxes) end return boxes end return GetRawBoxes, GetTriangulatedBoxes
RyMarq/Zero-K
LuaUI/Headers/startbox_utilities.lua
Lua
gpl-2.0
1,457
<?php /** * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * * @author Jérôme Bogaerts, <[email protected]> * @license GPLv2 * @package */ namespace qtism\data\storage\xml\marshalling; use qtism\data\content\ModalFeedbackCollection; use qtism\data\content\StylesheetCollection; use qtism\data\state\OutcomeDeclarationCollection; use qtism\data\state\ResponseDeclarationCollection; use qtism\data\state\TemplateDeclarationCollection; use qtism\data\QtiComponent; use qtism\data\AssessmentItem; use \DOMElement; /** * Marshalling/Unmarshalling implementation for AssessmentItem. * * @author Jérôme Bogaerts <[email protected]> * */ class AssessmentItemMarshaller extends Marshaller { /** * Marshall an AssessmentItem object into a DOMElement object. * * @param QtiComponent $component An AssessmentItem object. * @return DOMElement The according DOMElement object. */ protected function marshall(QtiComponent $component) { $element = static::getDOMCradle()->createElement($component->getQtiClassName()); self::setDOMElementAttribute($element, 'identifier', $component->getIdentifier()); self::setDOMElementAttribute($element, 'title', $component->getTitle()); self::setDOMElementAttribute($element, 'timeDependent', $component->isTimeDependent()); self::setDOMElementAttribute($element, 'adaptive', $component->isAdaptive()); if ($component->hasLang() === true) { self::setDOMElementAttribute($element, 'lang', $component->getLang()); } if ($component->hasLabel() === true) { self::setDOMElementAttribute($element, 'label', $component->getLabel()); } if ($component->hasToolName() === true) { self::setDOMElementAttribute($element, 'toolName', $component->getToolName()); } if ($component->hasToolVersion() === true) { self::setDOMElementAttribute($element, 'toolVersion', $component->getToolVersion()); } foreach ($component->getResponseDeclarations() as $responseDeclaration) { $marshaller = $this->getMarshallerFactory()->createMarshaller($responseDeclaration); $element->appendChild($marshaller->marshall($responseDeclaration)); } foreach ($component->getOutcomeDeclarations() as $outcomeDeclaration) { $marshaller = $this->getMarshallerFactory()->createMarshaller($outcomeDeclaration); $element->appendChild($marshaller->marshall($outcomeDeclaration)); } foreach ($component->getTemplateDeclarations() as $templateDeclaration) { $marshaller = $this->getMarshallerFactory()->createMarshaller($templateDeclaration); $element->appendChild($marshaller->marshall($templateDeclaration)); } if ($component->hasTemplateProcessing() === true) { $marshaller = $this->getMarshallerFactory()->createMarshaller($component->getTemplateProcessing()); $element->appendChild($marshaller->marshall($component->getTemplateProcessing())); } foreach ($component->getStylesheets() as $stylesheet) { $marshaller = $this->getMarshallerFactory()->createMarshaller($stylesheet); $element->appendChild($marshaller->marshall($stylesheet)); } if ($component->hasItemBody() === true) { $itemBody = $component->getItemBody(); $marshaller = $this->getMarshallerFactory()->createMarshaller($itemBody); $element->appendChild($marshaller->marshall($itemBody)); } if ($component->hasResponseProcessing() === true) { $marshaller = $this->getMarshallerFactory()->createMarshaller($component->getResponseProcessing()); $element->appendChild($marshaller->marshall($component->getResponseProcessing())); } foreach ($component->getModalFeedbacks() as $modalFeedback) { $marshaller = $this->getMarshallerFactory()->createMarshaller($modalFeedback); $element->appendChild($marshaller->marshall($modalFeedback)); } return $element; } /** * Unmarshall a DOMElement object corresponding to a QTI assessmentItem element. * * If $assessmentItem is provided, it will be used as the unmarshalled component instead of creating * a new one. * * @param DOMElement $element A DOMElement object. * @param AssessmentItem $assessmentItem An optional AssessmentItem object to be decorated. * @return QtiComponent An AssessmentItem object. * @throws UnmarshallingException */ protected function unmarshall(DOMElement $element, AssessmentItem $assessmentItem = null) { if (($identifier = static::getDOMElementAttributeAs($element, 'identifier')) !== null) { if (($timeDependent = static::getDOMElementAttributeAs($element, 'timeDependent', 'boolean')) !== null) { if (($title= static::getDOMElementAttributeAs($element, 'title')) !== null) { if (empty($assessmentItem)) { $object = new AssessmentItem($identifier, $title, $timeDependent); } else { $object = $assessmentItem; $object->setIdentifier($identifier); $object->setTimeDependent($timeDependent); } if (($lang = static::getDOMElementAttributeAs($element, 'lang')) !== null) { $object->setLang($lang); } if (($label = static::getDOMElementAttributeAs($element, 'label')) !== null) { $object->setLabel($label); } if (($adaptive = static::getDOMElementAttributeAs($element, 'adaptive', 'boolean')) !== null) { $object->setAdaptive($adaptive); } if (($toolName = static::getDOMElementAttributeAs($element, 'toolName')) !== null) { $object->setToolName($toolName); } if (($toolVersion = static::getDOMElementAttributeAs($element, 'toolVersion')) !== null) { $object->setToolVersion($toolVersion); } $responseDeclarationElts = static::getChildElementsByTagName($element, 'responseDeclaration'); if (!empty($responseDeclarationElts)) { $responseDeclarations = new ResponseDeclarationCollection(); foreach ($responseDeclarationElts as $responseDeclarationElt) { $marshaller = $this->getMarshallerFactory()->createMarshaller($responseDeclarationElt); $responseDeclarations[] = $marshaller->unmarshall($responseDeclarationElt); } $object->setResponseDeclarations($responseDeclarations); } $outcomeDeclarationElts = static::getChildElementsByTagName($element, 'outcomeDeclaration'); if (!empty($outcomeDeclarationElts)) { $outcomeDeclarations = new OutcomeDeclarationCollection(); foreach ($outcomeDeclarationElts as $outcomeDeclarationElt) { $marshaller = $this->getMarshallerFactory()->createMarshaller($outcomeDeclarationElt); $outcomeDeclarations[] = $marshaller->unmarshall($outcomeDeclarationElt); } $object->setOutcomeDeclarations($outcomeDeclarations); } $templateDeclarationElts = static::getChildElementsByTagName($element, 'templateDeclaration'); if (!empty($templateDeclarationElts)) { $templateDeclarations = new TemplateDeclarationCollection(); foreach ($templateDeclarationElts as $templateDeclarationElt) { $marshaller = $this->getMarshallerFactory()->createMarshaller($templateDeclarationElt); $templateDeclarations[] = $marshaller->unmarshall($templateDeclarationElt); } $object->setTemplateDeclarations($templateDeclarations); } $templateProcessingElts = static::getChildElementsByTagName($element, 'templateProcessing'); if (!empty($templateProcessingElts)) { $marshaller = $this->getMarshallerFactory()->createMarshaller($templateProcessingElts[0]); $object->setTemplateProcessing($marshaller->unmarshall($templateProcessingElts[0])); } $stylesheetElts = static::getChildElementsByTagName($element, 'stylesheet'); if (!empty($stylesheetElts)) { $stylesheets = new StylesheetCollection(); foreach ($stylesheetElts as $stylesheetElt) { $marshaller = $this->getMarshallerFactory()->createMarshaller($stylesheetElt); $stylesheets[] = $marshaller->unmarshall($stylesheetElt); } $object->setStylesheets($stylesheets); } $itemBodyElts = static::getChildElementsByTagName($element, 'itemBody'); if (count($itemBodyElts) > 0) { $marshaller = $this->getMarshallerFactory()->createMarshaller($itemBodyElts[0]); $object->setItemBody($marshaller->unmarshall($itemBodyElts[0])); } $responseProcessingElts = static::getChildElementsByTagName($element, 'responseProcessing'); if (!empty($responseProcessingElts)) { $marshaller = $this->getMarshallerFactory()->createMarshaller($responseProcessingElts[0]); $object->setResponseProcessing($marshaller->unmarshall($responseProcessingElts[0])); } $modalFeedbackElts = static::getChildElementsByTagName($element, 'modalFeedback'); if (!empty($modalFeedbackElts)) { $modalFeedbacks = new ModalFeedbackCollection(); foreach ($modalFeedbackElts as $modalFeedbackElt) { $marshaller = $this->getMarshallerFactory()->createMarshaller($modalFeedbackElt); $modalFeedbacks[] = $marshaller->unmarshall($modalFeedbackElt); } $object->setModalFeedbacks($modalFeedbacks); } return $object; } else { $msg = "The mandatory attribute 'title' is missing from element '" . $element->localName . "'."; throw new UnmarshallingException($msg, $element); } } else { $msg = "The mandatory attribute 'timeDependent' is missing from element '" . $element->localName . "'."; throw new UnmarshallingException($msg, $element); } } else { $msg = "The mandatory attribute 'identifier' is missing from element '" . $element->localName . "'."; throw new UnmarshallingException($msg, $element); } } public function getExpectedQtiClassName() { return 'assessmentItem'; } }
dhx/tao-comp
vendor/qtism/qtism/qtism/data/storage/xml/marshalling/AssessmentItemMarshaller.php
PHP
gpl-2.0
11,567
<?php /* * @package Joomla.Framework * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * * @component Phoca Component * @copyright Copyright (C) Jan Pavelka www.phoca.cz * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later; */ defined('_JEXEC') or die(); jimport('joomla.application.component.modellist'); class PhocaGalleryCpModelPhocaGalleryRa extends JModelList { protected $option = 'com_phocagallery'; public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'title', 'a.title', 'username','ua.username', 'date', 'a.date', 'alias', 'a.alias', 'checked_out', 'a.checked_out', 'checked_out_time', 'a.checked_out_time', 'category_id', 'category_id', 'state', 'a.state', 'ordering', 'a.ordering', 'language', 'a.language', 'hits', 'a.hits', 'published','a.published', 'rating', 'a.rating', 'category_title', 'category_title' ); } parent::__construct($config); } protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication('administrator'); // Load the filter state. $search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); /* $accessId = $app->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', null, 'int'); $this->setState('filter.access', $accessId); $state = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string'); $this->setState('filter.state', $state); */ $categoryId = $app->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id', null); $this->setState('filter.category_id', $categoryId); /* $language = $app->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', ''); $this->setState('filter.language', $language); */ // Load the parameters. $params = JComponentHelper::getParams('com_phocagallery'); $this->setState('params', $params); // List state information. parent::populateState('ua.username', 'asc'); } protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); //$id .= ':'.$this->getState('filter.access'); //$id .= ':'.$this->getState('filter.state'); $id .= ':'.$this->getState('filter.category_id'); return parent::getStoreId($id); } protected function getListQuery() { /* $query = ' SELECT a.*, cc.title AS category, ua.name AS editor, u.id AS ratinguserid, u.username AS ratingusername ' . ' FROM #__phocagallery_votes AS a ' . ' LEFT JOIN #__phocagallery_categories AS cc ON cc.id = a.catid ' . ' LEFT JOIN #__users AS ua ON ua.id = a.checked_out ' . ' LEFT JOIN #__users AS u ON u.id = a.userid' . $where . ' GROUP by a.id' . $orderby ; */ // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.*' ) ); $query->from('`#__phocagallery_votes` AS a'); // Join over the language $query->select('l.title AS language_title'); $query->join('LEFT', '`#__languages` AS l ON l.lang_code = a.language'); // Join over the users for the checked out user. $query->select('ua.id AS ratinguserid, ua.username AS ratingusername, ua.name AS ratingname'); $query->join('LEFT', '#__users AS ua ON ua.id=a.userid'); $query->select('uc.name AS editor'); $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out'); /* // Join over the asset groups. $query->select('ag.title AS access_level'); $query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access'); */ // Join over the categories. $query->select('c.title AS category_title, c.id AS category_id'); $query->join('LEFT', '#__phocagallery_categories AS c ON c.id = a.catid'); // Filter by access level. /* if ($access = $this->getState('filter.access')) { $query->where('a.access = '.(int) $access); }*/ // Filter by published state. $published = $this->getState('filter.state'); if (is_numeric($published)) { $query->where('a.published = '.(int) $published); } else if ($published === '') { $query->where('(a.published IN (0, 1))'); } // Filter by category. $categoryId = $this->getState('filter.category_id'); if (is_numeric($categoryId)) { $query->where('a.catid = ' . (int) $categoryId); } // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); $query->where('( ua.name LIKE '.$search.' OR ua.username LIKE '.$search.')'); } } //$query->group('a.id'); // Add the list ordering clause. $orderCol = $this->state->get('list.ordering'); $orderDirn = $this->state->get('list.direction'); if ($orderCol == 'a.ordering' || $orderCol == 'category_title') { $orderCol = 'category_title '.$orderDirn.', a.ordering'; } $query->order($db->escape($orderCol.' '.$orderDirn)); //echo nl2br(str_replace('#__','jos_',$query)); return $query; } function delete($cid = array()) { if (count( $cid )) { \Joomla\Utilities\ArrayHelper::toInteger($cid); $cids = implode( ',', $cid ); //Select affected catids $query = 'SELECT v.catid AS catid' . ' FROM #__phocagallery_votes AS v' . ' WHERE v.id IN ( '.$cids.' )'; $catids = $this->_getList($query); //Delete it from DB $query = 'DELETE FROM #__phocagallery_votes' . ' WHERE id IN ( '.$cids.' )'; $this->_db->setQuery( $query ); if(!$this->_db->query()) { $this->setError($this->_db->getErrorMsg()); return false; } phocagalleryimport('phocagallery.rate.ratecategory'); foreach ($catids as $valueCatid) { $updated = PhocaGalleryRateCategory::updateVoteStatistics( $valueCatid->catid ); if(!$updated) { return false; } } } return true; } protected function prepareTable($table) { jimport('joomla.filter.output'); $date = JFactory::getDate(); $user = JFactory::getUser(); $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); $table->alias = \JApplicationHelper::stringURLSafe($table->alias); if (empty($table->alias)) { $table->alias = \JApplicationHelper::stringURLSafe($table->title); } if (empty($table->id)) { // Set the values //$table->created = $date->toSql(); // Set ordering to the last item if not set if (empty($table->ordering)) { $db = JFactory::getDbo(); $db->setQuery('SELECT MAX(ordering) FROM #__phocagallery_votes WHERE catid = '.(int) $table->catid); $max = $db->loadResult(); $table->ordering = $max+1; } } else { // Set the values //$table->modified = $date->toSql(); //$table->modified_by = $user->get('id'); } } } ?>
renebentes/joomla-3.x
administrator/components/com_phocagallery/models/phocagalleryra.php
PHP
gpl-2.0
7,227
/************************************************************************** Copyright (C) 2000 - 2010 Novell, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. **************************************************************************/ /*---------------------------------------------------------------------\ | | | __ __ ____ _____ ____ | | \ \ / /_ _/ ___|_ _|___ \ | | \ V / _` \___ \ | | __) | | | | | (_| |___) || | / __/ | | |_|\__,_|____/ |_| |_____| | | | | core system | | (c) SuSE Linux AG | \----------------------------------------------------------------------/ File: YQZyppSolverDialogPluginStub.cc Authors: Stefan Schubert <[email protected]> Textdomain "qt-pkg" /-*/ #include <qmessagebox.h> #include "YQZyppSolverDialogPluginStub.h" #define YUILogComponent "qt-ui" #include "YUILog.h" #include "YQi18n.h" #define PLUGIN_BASE_NAME "qt_zypp_solver_dialog" using std::endl; YQZyppSolverDialogPluginStub::YQZyppSolverDialogPluginStub() : YUIPlugin( PLUGIN_BASE_NAME ) { if ( success() ) { yuiMilestone() << "Loaded " << PLUGIN_BASE_NAME << " plugin successfully from " << pluginLibFullPath() << endl; } impl = (YQZyppSolverDialogPluginIf*) locateSymbol("ZYPPDIALOGP"); if ( ! impl ) { yuiError() << "Plugin " << PLUGIN_BASE_NAME << " does not provide ZYPPP symbol" << endl; } } YQZyppSolverDialogPluginStub::~YQZyppSolverDialogPluginStub() { // NOP } bool YQZyppSolverDialogPluginStub::createZyppSolverDialog( const zypp::PoolItem item ) { if ( ! impl ) { QMessageBox::information( 0, _("Missing package") , _("Package libqdialogsolver is required for this feature.")); return false; } return impl->createZyppSolverDialog( item ); }
gabi2/libyui-qt-pkg
src/YQZyppSolverDialogPluginStub.cc
C++
gpl-2.0
2,581
//===-- PPCISelLowering.h - PPC32 DAG Lowering Interface --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interfaces that PPC uses to lower LLVM code into a // selection DAG. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_POWERPC_PPCISELLOWERING_H #define LLVM_LIB_TARGET_POWERPC_PPCISELLOWERING_H #include "PPC.h" #include "PPCInstrInfo.h" #include "PPCRegisterInfo.h" #include "llvm/CodeGen/CallingConvLower.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/Target/TargetLowering.h" namespace llvm { namespace PPCISD { enum NodeType : unsigned { // Start the numbering where the builtin ops and target ops leave off. FIRST_NUMBER = ISD::BUILTIN_OP_END, /// FSEL - Traditional three-operand fsel node. /// FSEL, /// FCFID - The FCFID instruction, taking an f64 operand and producing /// and f64 value containing the FP representation of the integer that /// was temporarily in the f64 operand. FCFID, /// Newer FCFID[US] integer-to-floating-point conversion instructions for /// unsigned integers and single-precision outputs. FCFIDU, FCFIDS, FCFIDUS, /// FCTI[D,W]Z - The FCTIDZ and FCTIWZ instructions, taking an f32 or f64 /// operand, producing an f64 value containing the integer representation /// of that FP value. FCTIDZ, FCTIWZ, /// Newer FCTI[D,W]UZ floating-point-to-integer conversion instructions for /// unsigned integers. FCTIDUZ, FCTIWUZ, /// Reciprocal estimate instructions (unary FP ops). FRE, FRSQRTE, // VMADDFP, VNMSUBFP - The VMADDFP and VNMSUBFP instructions, taking // three v4f32 operands and producing a v4f32 result. VMADDFP, VNMSUBFP, /// VPERM - The PPC VPERM Instruction. /// VPERM, /// The CMPB instruction (takes two operands of i32 or i64). CMPB, /// Hi/Lo - These represent the high and low 16-bit parts of a global /// address respectively. These nodes have two operands, the first of /// which must be a TargetGlobalAddress, and the second of which must be a /// Constant. Selected naively, these turn into 'lis G+C' and 'li G+C', /// though these are usually folded into other nodes. Hi, Lo, /// The following two target-specific nodes are used for calls through /// function pointers in the 64-bit SVR4 ABI. /// OPRC, CHAIN = DYNALLOC(CHAIN, NEGSIZE, FRAME_INDEX) /// This instruction is lowered in PPCRegisterInfo::eliminateFrameIndex to /// compute an allocation on the stack. DYNALLOC, /// GlobalBaseReg - On Darwin, this node represents the result of the mflr /// at function entry, used for PIC code. GlobalBaseReg, /// These nodes represent the 32-bit PPC shifts that operate on 6-bit /// shift amounts. These nodes are generated by the multi-precision shift /// code. SRL, SRA, SHL, /// The combination of sra[wd]i and addze used to implemented signed /// integer division by a power of 2. The first operand is the dividend, /// and the second is the constant shift amount (representing the /// divisor). SRA_ADDZE, /// CALL - A direct function call. /// CALL_NOP is a call with the special NOP which follows 64-bit /// SVR4 calls. CALL, CALL_NOP, /// CHAIN,FLAG = MTCTR(VAL, CHAIN[, INFLAG]) - Directly corresponds to a /// MTCTR instruction. MTCTR, /// CHAIN,FLAG = BCTRL(CHAIN, INFLAG) - Directly corresponds to a /// BCTRL instruction. BCTRL, /// CHAIN,FLAG = BCTRL(CHAIN, ADDR, INFLAG) - The combination of a bctrl /// instruction and the TOC reload required on SVR4 PPC64. BCTRL_LOAD_TOC, /// Return with a flag operand, matched by 'blr' RET_FLAG, /// R32 = MFOCRF(CRREG, INFLAG) - Represents the MFOCRF instruction. /// This copies the bits corresponding to the specified CRREG into the /// resultant GPR. Bits corresponding to other CR regs are undefined. MFOCRF, /// Direct move from a VSX register to a GPR MFVSR, /// Direct move from a GPR to a VSX register (algebraic) MTVSRA, /// Direct move from a GPR to a VSX register (zero) MTVSRZ, // FIXME: Remove these once the ANDI glue bug is fixed: /// i1 = ANDIo_1_[EQ|GT]_BIT(i32 or i64 x) - Represents the result of the /// eq or gt bit of CR0 after executing andi. x, 1. This is used to /// implement truncation of i32 or i64 to i1. ANDIo_1_EQ_BIT, ANDIo_1_GT_BIT, // READ_TIME_BASE - A read of the 64-bit time-base register on a 32-bit // target (returns (Lo, Hi)). It takes a chain operand. READ_TIME_BASE, // EH_SJLJ_SETJMP - SjLj exception handling setjmp. EH_SJLJ_SETJMP, // EH_SJLJ_LONGJMP - SjLj exception handling longjmp. EH_SJLJ_LONGJMP, /// RESVEC = VCMP(LHS, RHS, OPC) - Represents one of the altivec VCMP* /// instructions. For lack of better number, we use the opcode number /// encoding for the OPC field to identify the compare. For example, 838 /// is VCMPGTSH. VCMP, /// RESVEC, OUTFLAG = VCMPo(LHS, RHS, OPC) - Represents one of the /// altivec VCMP*o instructions. For lack of better number, we use the /// opcode number encoding for the OPC field to identify the compare. For /// example, 838 is VCMPGTSH. VCMPo, /// CHAIN = COND_BRANCH CHAIN, CRRC, OPC, DESTBB [, INFLAG] - This /// corresponds to the COND_BRANCH pseudo instruction. CRRC is the /// condition register to branch on, OPC is the branch opcode to use (e.g. /// PPC::BLE), DESTBB is the destination block to branch to, and INFLAG is /// an optional input flag argument. COND_BRANCH, /// CHAIN = BDNZ CHAIN, DESTBB - These are used to create counter-based /// loops. BDNZ, BDZ, /// F8RC = FADDRTZ F8RC, F8RC - This is an FADD done with rounding /// towards zero. Used only as part of the long double-to-int /// conversion sequence. FADDRTZ, /// F8RC = MFFS - This moves the FPSCR (not modeled) into the register. MFFS, /// TC_RETURN - A tail call return. /// operand #0 chain /// operand #1 callee (register or absolute) /// operand #2 stack adjustment /// operand #3 optional in flag TC_RETURN, /// ch, gl = CR6[UN]SET ch, inglue - Toggle CR bit 6 for SVR4 vararg calls CR6SET, CR6UNSET, /// GPRC = address of _GLOBAL_OFFSET_TABLE_. Used by initial-exec TLS /// on PPC32. PPC32_GOT, /// GPRC = address of _GLOBAL_OFFSET_TABLE_. Used by general dynamic and /// local dynamic TLS on PPC32. PPC32_PICGOT, /// G8RC = ADDIS_GOT_TPREL_HA %X2, Symbol - Used by the initial-exec /// TLS model, produces an ADDIS8 instruction that adds the GOT /// base to sym\@got\@tprel\@ha. ADDIS_GOT_TPREL_HA, /// G8RC = LD_GOT_TPREL_L Symbol, G8RReg - Used by the initial-exec /// TLS model, produces a LD instruction with base register G8RReg /// and offset sym\@got\@tprel\@l. This completes the addition that /// finds the offset of "sym" relative to the thread pointer. LD_GOT_TPREL_L, /// G8RC = ADD_TLS G8RReg, Symbol - Used by the initial-exec TLS /// model, produces an ADD instruction that adds the contents of /// G8RReg to the thread pointer. Symbol contains a relocation /// sym\@tls which is to be replaced by the thread pointer and /// identifies to the linker that the instruction is part of a /// TLS sequence. ADD_TLS, /// G8RC = ADDIS_TLSGD_HA %X2, Symbol - For the general-dynamic TLS /// model, produces an ADDIS8 instruction that adds the GOT base /// register to sym\@got\@tlsgd\@ha. ADDIS_TLSGD_HA, /// %X3 = ADDI_TLSGD_L G8RReg, Symbol - For the general-dynamic TLS /// model, produces an ADDI8 instruction that adds G8RReg to /// sym\@got\@tlsgd\@l and stores the result in X3. Hidden by /// ADDIS_TLSGD_L_ADDR until after register assignment. ADDI_TLSGD_L, /// %X3 = GET_TLS_ADDR %X3, Symbol - For the general-dynamic TLS /// model, produces a call to __tls_get_addr(sym\@tlsgd). Hidden by /// ADDIS_TLSGD_L_ADDR until after register assignment. GET_TLS_ADDR, /// G8RC = ADDI_TLSGD_L_ADDR G8RReg, Symbol, Symbol - Op that /// combines ADDI_TLSGD_L and GET_TLS_ADDR until expansion following /// register assignment. ADDI_TLSGD_L_ADDR, /// G8RC = ADDIS_TLSLD_HA %X2, Symbol - For the local-dynamic TLS /// model, produces an ADDIS8 instruction that adds the GOT base /// register to sym\@got\@tlsld\@ha. ADDIS_TLSLD_HA, /// %X3 = ADDI_TLSLD_L G8RReg, Symbol - For the local-dynamic TLS /// model, produces an ADDI8 instruction that adds G8RReg to /// sym\@got\@tlsld\@l and stores the result in X3. Hidden by /// ADDIS_TLSLD_L_ADDR until after register assignment. ADDI_TLSLD_L, /// %X3 = GET_TLSLD_ADDR %X3, Symbol - For the local-dynamic TLS /// model, produces a call to __tls_get_addr(sym\@tlsld). Hidden by /// ADDIS_TLSLD_L_ADDR until after register assignment. GET_TLSLD_ADDR, /// G8RC = ADDI_TLSLD_L_ADDR G8RReg, Symbol, Symbol - Op that /// combines ADDI_TLSLD_L and GET_TLSLD_ADDR until expansion /// following register assignment. ADDI_TLSLD_L_ADDR, /// G8RC = ADDIS_DTPREL_HA %X3, Symbol - For the local-dynamic TLS /// model, produces an ADDIS8 instruction that adds X3 to /// sym\@dtprel\@ha. ADDIS_DTPREL_HA, /// G8RC = ADDI_DTPREL_L G8RReg, Symbol - For the local-dynamic TLS /// model, produces an ADDI8 instruction that adds G8RReg to /// sym\@got\@dtprel\@l. ADDI_DTPREL_L, /// VRRC = VADD_SPLAT Elt, EltSize - Temporary node to be expanded /// during instruction selection to optimize a BUILD_VECTOR into /// operations on splats. This is necessary to avoid losing these /// optimizations due to constant folding. VADD_SPLAT, /// CHAIN = SC CHAIN, Imm128 - System call. The 7-bit unsigned /// operand identifies the operating system entry point. SC, /// CHAIN = CLRBHRB CHAIN - Clear branch history rolling buffer. CLRBHRB, /// GPRC, CHAIN = MFBHRBE CHAIN, Entry, Dummy - Move from branch /// history rolling buffer entry. MFBHRBE, /// CHAIN = RFEBB CHAIN, State - Return from event-based branch. RFEBB, /// VSRC, CHAIN = XXSWAPD CHAIN, VSRC - Occurs only for little /// endian. Maps to an xxswapd instruction that corrects an lxvd2x /// or stxvd2x instruction. The chain is necessary because the /// sequence replaces a load and needs to provide the same number /// of outputs. XXSWAPD, /// QVFPERM = This corresponds to the QPX qvfperm instruction. QVFPERM, /// QVGPCI = This corresponds to the QPX qvgpci instruction. QVGPCI, /// QVALIGNI = This corresponds to the QPX qvaligni instruction. QVALIGNI, /// QVESPLATI = This corresponds to the QPX qvesplati instruction. QVESPLATI, /// QBFLT = Access the underlying QPX floating-point boolean /// representation. QBFLT, /// CHAIN = STBRX CHAIN, GPRC, Ptr, Type - This is a /// byte-swapping store instruction. It byte-swaps the low "Type" bits of /// the GPRC input, then stores it through Ptr. Type can be either i16 or /// i32. STBRX = ISD::FIRST_TARGET_MEMORY_OPCODE, /// GPRC, CHAIN = LBRX CHAIN, Ptr, Type - This is a /// byte-swapping load instruction. It loads "Type" bits, byte swaps it, /// then puts it in the bottom bits of the GPRC. TYPE can be either i16 /// or i32. LBRX, /// STFIWX - The STFIWX instruction. The first operand is an input token /// chain, then an f64 value to store, then an address to store it to. STFIWX, /// GPRC, CHAIN = LFIWAX CHAIN, Ptr - This is a floating-point /// load which sign-extends from a 32-bit integer value into the /// destination 64-bit register. LFIWAX, /// GPRC, CHAIN = LFIWZX CHAIN, Ptr - This is a floating-point /// load which zero-extends from a 32-bit integer value into the /// destination 64-bit register. LFIWZX, /// VSRC, CHAIN = LXVD2X_LE CHAIN, Ptr - Occurs only for little endian. /// Maps directly to an lxvd2x instruction that will be followed by /// an xxswapd. LXVD2X, /// CHAIN = STXVD2X CHAIN, VSRC, Ptr - Occurs only for little endian. /// Maps directly to an stxvd2x instruction that will be preceded by /// an xxswapd. STXVD2X, /// QBRC, CHAIN = QVLFSb CHAIN, Ptr /// The 4xf32 load used for v4i1 constants. QVLFSb, /// GPRC = TOC_ENTRY GA, TOC /// Loads the entry for GA from the TOC, where the TOC base is given by /// the last operand. TOC_ENTRY }; } /// Define some predicates that are used for node matching. namespace PPC { /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUHUM instruction. bool isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG); /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUWUM instruction. bool isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG); /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUDUM instruction. bool isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG); /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes). bool isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG); /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes). bool isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG); /// isVMRGEOShuffleMask - Return true if this is a shuffle mask suitable for /// a VMRGEW or VMRGOW instruction bool isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, unsigned ShuffleKind, SelectionDAG &DAG); /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the /// shift amount, otherwise return -1. int isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, SelectionDAG &DAG); /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand /// specifies a splat of a single element that is suitable for input to /// VSPLTB/VSPLTH/VSPLTW. bool isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize); /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. unsigned getVSPLTImmediate(SDNode *N, unsigned EltSize, SelectionDAG &DAG); /// get_VSPLTI_elt - If this is a build_vector of constants which can be /// formed by using a vspltis[bhw] instruction of the specified element /// size, return the constant being splatted. The ByteSize field indicates /// the number of bytes of each element [124] -> [bhw]. SDValue get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG); /// If this is a qvaligni shuffle mask, return the shift /// amount, otherwise return -1. int isQVALIGNIShuffleMask(SDNode *N); } class PPCTargetLowering : public TargetLowering { const PPCSubtarget &Subtarget; public: explicit PPCTargetLowering(const PPCTargetMachine &TM, const PPCSubtarget &STI); /// getTargetNodeName() - This method returns the name of a target specific /// DAG node. const char *getTargetNodeName(unsigned Opcode) const override; MVT getScalarShiftAmountTy(const DataLayout &, EVT) const override { return MVT::i32; } bool isCheapToSpeculateCttz() const override { return true; } bool isCheapToSpeculateCtlz() const override { return true; } /// getSetCCResultType - Return the ISD::SETCC ValueType EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override; /// Return true if target always beneficiates from combining into FMA for a /// given value type. This must typically return false on targets where FMA /// takes more cycles to execute than FADD. bool enableAggressiveFMAFusion(EVT VT) const override; /// getPreIndexedAddressParts - returns true by value, base pointer and /// offset pointer and addressing mode by reference if the node's address /// can be legally represented as pre-indexed load / store address. bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override; /// SelectAddressRegReg - Given the specified addressed, check to see if it /// can be represented as an indexed [r+r] operation. Returns false if it /// can be more efficiently represented with [r+imm]. bool SelectAddressRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const; /// SelectAddressRegImm - Returns true if the address N can be represented /// by a base register plus a signed 16-bit displacement [r+imm], and if it /// is not better represented as reg+reg. If Aligned is true, only accept /// displacements suitable for STD and friends, i.e. multiples of 4. bool SelectAddressRegImm(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, bool Aligned) const; /// SelectAddressRegRegOnly - Given the specified addressed, force it to be /// represented as an indexed [r+r] operation. bool SelectAddressRegRegOnly(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const; Sched::Preference getSchedulingPreference(SDNode *N) const override; /// LowerOperation - Provide custom lowering hooks for some operations. /// SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override; /// ReplaceNodeResults - Replace the results of node with an illegal result /// type with new values built out of custom code. /// void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue>&Results, SelectionDAG &DAG) const override; SDValue expandVSXLoadForLE(SDNode *N, DAGCombinerInfo &DCI) const; SDValue expandVSXStoreForLE(SDNode *N, DAGCombinerInfo &DCI) const; SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override; SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, std::vector<SDNode *> *Created) const override; unsigned getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const override; void computeKnownBitsForTargetNode(const SDValue Op, APInt &KnownZero, APInt &KnownOne, const SelectionDAG &DAG, unsigned Depth = 0) const override; unsigned getPrefLoopAlignment(MachineLoop *ML) const override; Instruction* emitLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord, bool IsStore, bool IsLoad) const override; Instruction* emitTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord, bool IsStore, bool IsLoad) const override; MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const override; MachineBasicBlock *EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *MBB, unsigned AtomicSize, unsigned BinOpcode) const; MachineBasicBlock *EmitPartwordAtomicBinary(MachineInstr *MI, MachineBasicBlock *MBB, bool is8bit, unsigned Opcode) const; MachineBasicBlock *emitEHSjLjSetJmp(MachineInstr *MI, MachineBasicBlock *MBB) const; MachineBasicBlock *emitEHSjLjLongJmp(MachineInstr *MI, MachineBasicBlock *MBB) const; ConstraintType getConstraintType(StringRef Constraint) const override; /// Examine constraint string and operand type and determine a weight value. /// The operand object must already have been set up with the operand type. ConstraintWeight getSingleConstraintMatchWeight( AsmOperandInfo &info, const char *constraint) const override; std::pair<unsigned, const TargetRegisterClass *> getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override; /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate /// function arguments in the caller parameter area. This is the actual /// alignment, not its logarithm. unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const override; /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops /// vector. If it is invalid, don't add anything to Ops. void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, SelectionDAG &DAG) const override; unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override { if (ConstraintCode == "es") return InlineAsm::Constraint_es; else if (ConstraintCode == "o") return InlineAsm::Constraint_o; else if (ConstraintCode == "Q") return InlineAsm::Constraint_Q; else if (ConstraintCode == "Z") return InlineAsm::Constraint_Z; else if (ConstraintCode == "Zy") return InlineAsm::Constraint_Zy; return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); } /// isLegalAddressingMode - Return true if the addressing mode represented /// by AM is legal for this target, for a load/store of the specified type. bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const override; /// isLegalICmpImmediate - Return true if the specified immediate is legal /// icmp immediate, that is the target has icmp instructions which can /// compare a register against the immediate without having to materialize /// the immediate into a register. bool isLegalICmpImmediate(int64_t Imm) const override; /// isLegalAddImmediate - Return true if the specified immediate is legal /// add immediate, that is the target has add instructions which can /// add a register and the immediate without having to materialize /// the immediate into a register. bool isLegalAddImmediate(int64_t Imm) const override; /// isTruncateFree - Return true if it's free to truncate a value of /// type Ty1 to type Ty2. e.g. On PPC it's free to truncate a i64 value in /// register X1 to i32 by referencing its sub-register R1. bool isTruncateFree(Type *Ty1, Type *Ty2) const override; bool isTruncateFree(EVT VT1, EVT VT2) const override; bool isZExtFree(SDValue Val, EVT VT2) const override; bool isFPExtFree(EVT VT) const override; /// \brief Returns true if it is beneficial to convert a load of a constant /// to just the constant itself. bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override; bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override; bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I, unsigned Intrinsic) const override; /// getOptimalMemOpType - Returns the target specific optimal type for load /// and store operations as a result of memset, memcpy, and memmove /// lowering. If DstAlign is zero that means it's safe to destination /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it /// means there isn't a need to check it against alignment requirement, /// probably because the source does not need to be loaded. If 'IsMemset' is /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy /// source is constant so it does not need to be loaded. /// It returns EVT::Other if the type should be determined using generic /// target-independent logic. EVT getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset, bool MemcpyStrSrc, MachineFunction &MF) const override; /// Is unaligned memory access allowed for the given type, and is it fast /// relative to software emulation. bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, unsigned Align = 1, bool *Fast = nullptr) const override; /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be /// expanded to FMAs when this method returns true, otherwise fmuladd is /// expanded to fmul + fadd. bool isFMAFasterThanFMulAndFAdd(EVT VT) const override; const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const override; // Should we expand the build vector with shuffles? bool shouldExpandBuildVectorWithShuffles(EVT VT, unsigned DefinedValues) const override; /// createFastISel - This method returns a target-specific FastISel object, /// or null if the target does not support "fast" instruction selection. FastISel *createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const override; /// \brief Returns true if an argument of type Ty needs to be passed in a /// contiguous block of registers in calling convention CallConv. bool functionArgumentNeedsConsecutiveRegisters( Type *Ty, CallingConv::ID CallConv, bool isVarArg) const override { // We support any array type as "consecutive" block in the parameter // save area. The element type defines the alignment requirement and // whether the argument should go in GPRs, FPRs, or VRs if available. // // Note that clang uses this capability both to implement the ELFv2 // homogeneous float/vector aggregate ABI, and to avoid having to use // "byval" when passing aggregates that might fully fit in registers. return Ty->isArrayTy(); } private: struct ReuseLoadInfo { SDValue Ptr; SDValue Chain; SDValue ResChain; MachinePointerInfo MPI; bool IsInvariant; unsigned Alignment; AAMDNodes AAInfo; const MDNode *Ranges; ReuseLoadInfo() : IsInvariant(false), Alignment(0), Ranges(nullptr) {} }; bool canReuseLoadAddress(SDValue Op, EVT MemVT, ReuseLoadInfo &RLI, SelectionDAG &DAG, ISD::LoadExtType ET = ISD::NON_EXTLOAD) const; void spliceIntoChain(SDValue ResChain, SDValue NewResChain, SelectionDAG &DAG) const; void LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, SelectionDAG &DAG, SDLoc dl) const; SDValue LowerFP_TO_INTDirectMove(SDValue Op, SelectionDAG &DAG, SDLoc dl) const; SDValue LowerINT_TO_FPDirectMove(SDValue Op, SelectionDAG &DAG, SDLoc dl) const; SDValue getFramePointerFrameIndex(SelectionDAG & DAG) const; SDValue getReturnAddrFrameIndex(SelectionDAG & DAG) const; bool IsEligibleForTailCallOptimization(SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG& DAG) const; SDValue EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, SDValue &FPOpOut, bool isDarwinABI, SDLoc dl) const; SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) const; SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSETCC(SDValue Op, SelectionDAG &DAG) const; SDValue LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const; SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const; SDValue LowerVACOPY(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const; SDValue LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const; SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const; SDValue LowerLOAD(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const; SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, SDLoc dl) const; SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const; SDValue LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const; SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const; SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const; SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVectorLoad(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVectorStore(SDValue Op, SelectionDAG &DAG) const; SDValue LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue FinishCall(CallingConv::ID CallConv, SDLoc dl, bool isTailCall, bool isVarArg, bool IsPatchPoint, bool hasNest, SelectionDAG &DAG, SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const; SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const override; SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl<SDValue> &InVals) const override; bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const override; SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, SDLoc dl, SelectionDAG &DAG) const override; SDValue extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT, SelectionDAG &DAG, SDValue ArgVal, SDLoc dl) const; SDValue LowerFormalArguments_Darwin(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue LowerFormalArguments_64SVR4(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue LowerFormalArguments_32SVR4(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, SDLoc dl) const; SDValue LowerCall_Darwin(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const; SDValue LowerCall_64SVR4(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const; SDValue LowerCall_32SVR4(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const; SDValue lowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const; SDValue lowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const; SDValue DAGCombineExtBoolTrunc(SDNode *N, DAGCombinerInfo &DCI) const; SDValue DAGCombineTruncBoolExt(SDNode *N, DAGCombinerInfo &DCI) const; SDValue combineFPToIntToFP(SDNode *N, DAGCombinerInfo &DCI) const; SDValue getRsqrtEstimate(SDValue Operand, DAGCombinerInfo &DCI, unsigned &RefinementSteps, bool &UseOneConstNR) const override; SDValue getRecipEstimate(SDValue Operand, DAGCombinerInfo &DCI, unsigned &RefinementSteps) const override; bool combineRepeatedFPDivisors(unsigned NumUsers) const override; CCAssignFn *useFastISelCCs(unsigned Flag) const; }; namespace PPC { FastISel *createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo); } bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State); bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State); bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State); } #endif // LLVM_TARGET_POWERPC_PPC32ISELLOWERING_H
rutgers-apl/Atomicity-Violation-Detector
tdebug-llvm/llvm/lib/Target/PowerPC/PPCISelLowering.h
C
gpl-2.0
39,773
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>C-Layman: /home/detlev/src/c-layman/src/message.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.8 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&nbsp;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> </div> <div class="contents"> <h1>/home/detlev/src/c-layman/src/message.h File Reference</h1><code>#include &lt;stdio.h&gt;</code><br> <code>#include &quot;<a class="el" href="stringlist_8h-source.html">stringlist.h</a>&quot;</code><br> <p> <a href="message_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Typedefs</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">typedef struct <a class="el" href="struct_message.html">Message</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="message_8h.html#82fffef6ac8d8a796ab35b7d6a7a0dcb">Message</a></td></tr> <tr><td colspan="2"><br><h2>Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="struct_message.html">Message</a> *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__message.html#g71549e9f908d468258f2e257655df858">messageCreate</a> (const char *module, FILE *out, FILE *err, FILE *dbg)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__message.html#g5faf9665b84f817233ca8dad4dbe9004">messageFree</a> (<a class="el" href="struct_message.html">Message</a> *m)</td></tr> </table> <hr><h2>Typedef Documentation</h2> <a class="anchor" name="82fffef6ac8d8a796ab35b7d6a7a0dcb"></a><!-- doxytag: member="message.h::Message" ref="82fffef6ac8d8a796ab35b7d6a7a0dcb" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct <a class="el" href="struct_message.html">Message</a> <a class="el" href="struct_message.html">Message</a> </td> </tr> </table> </div> <div class="memdoc"> <p> </div> </div><p> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Fri Aug 6 20:00:53 2010 for C-Layman by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.8 </small></address> </body> </html>
jmesmon/layman
c-layman/doc/html/message_8h.html
HTML
gpl-2.0
3,111
<div class="container" id="mainContent"> <div id="topOfPage"> </div> <h1> Feedback Results - Student </h1> <br> <div class="well well-plain"> <div class="panel-body"> <div class="form-horizontal"> <div class="panel-heading"> <div class="form-group"> <label class="col-sm-2 control-label"> Course ID: </label> <div class="col-sm-10"> <p class="form-control-static"> AHPUiT____.instr1_.gma-demo </p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Session: </label> <div class="col-sm-10"> <p class="form-control-static"> First team feedback session </p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Opening time: </label> <div class="col-sm-10"> <p class="form-control-static"> Sun, 01 Apr 2012, 11:59 PM </p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label"> Closing time: </label> <div class="col-sm-10"> <p class="form-control-static"> Mon, 02 Apr 2012, 11:59 PM </p> </div> </div> </div> </div> </div> </div> <br> <div id="statusMessagesToUser"> <div class="overflow-auto alert alert-info statusMessage"> You have received feedback from others. Please see below. </div> </div> <script defer="" src="/js/statusMessage.js" type="text/javascript"> </script> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4> Question 1: <span class="text-preserve-space"> Please rate the estimated contribution of your team members and yourself.  <span style=" white-space: normal;"> <a class="color_gray" data-less="[less]" data-more="[more]" href="javascript:;" id="questionAdditionalInfoButton-1-" onclick="toggleAdditionalQuestionInfo('1-')"> [more] </a> <br> <span id="questionAdditionalInfo-1-" style="display:none;"> Team contribution question </span> </span> </span> </h4> <div class="panel panel-primary"> <div class="panel-heading"> Comparison of work distribution   <span style=" white-space: normal;"> <a class="small link-in-dark-bg" data-less="[less]" data-more="[how to interpret, etc..]" href="javascript:;" id="questionAdditionalInfoButton-1-contributionInfo" onclick="toggleAdditionalQuestionInfo('1-contributionInfo')"> [how to interpret, etc..] </a> <br> <span id="questionAdditionalInfo-1-contributionInfo" style="display:none;"> <h4 id="interpret"> How do I interpret these results? </h4> <ul class="bulletedList"> <li> Compare values given under 'My view' to those under 'Team's view'. This tells you whether your perception matches with what the team thinks, particularly regarding your own contribution. You may ignore minor differences. </li> <li> Team's view of your contribution is the average value of the contribution your team members attributed to you, excluding the contribution you attributed to yourself. That means you cannot boost your perceived contribution by claiming a high contribution for yourself or attributing a low contribution to team members. </li> <li> Also note that the team’s view has been scaled up/down so that the sum of values in your view matches the sum of values in team’s view. That way, you can make a direct comparison between your view and the team’s view. As a result, the values you see in team’s view may not match the values your team members see in their results. </li> </ul> <br> <h4> How are these results used in grading? </h4> TEAMMATES does not calculate grades. It is up to the instructors to use contribution question results in any way they want. However, TEAMMATES recommend that contribution question results are used only as flags to identify teams with contribution imbalances. Once identified, the instructor is recommended to investigate further before taking action. <br> <br> <h4> How are the contribution numbers calculated? </h4> Here are the important things to note: <ul class="bulletedList"> <li> The contribution you attributed to yourself is not used when calculating the perceived contribution of you or team members. </li> <li> From the estimates you submit, we try to deduce the answer to this question: In your opinion, if your teammates are doing the project by themselves without you, how do they compare against each other in terms of contribution? This is because we want to deduce your unbiased opinion about your team members’ contributions. Then, we use those values to calculate the average perceived contribution of each team member. </li> <li> When deducing the above, we first adjust the estimates you submitted to remove artificial inflations/deflations. For example, giving everyone [Equal share + 20%] is as same as giving everyone [Equal share] because in both cases all members have done a similar share of work. </li> </ul> The actual calculation is a bit complex and the finer details can be found <a href="https://docs.google.com/document/d/1hjQQHYM3YId0EUSrGnJWG5AeFpDD_G7xg_d--7jg3vU/pub?embedded=true#h.n5u2xs6z9y0g"> here </a> . </span> </span> </div> <table class="table table-striped"> <tbody> <tr> <td> <strong> My view: </strong> </td> <td> <span class="text-muted"> <strong> of me: </strong> </span> <span class="color-positive"> E +10% </span> </td> <td> <span class="text-muted"> <strong> of others: </strong> </span> <span class="color-positive"> E +10% </span> , <span class="color-positive"> E +10% </span> , <span class="color-negative"> E -20% </span> </td> </tr> <tr> <td> <strong> Team's view: </strong> </td> <td> <span class="text-muted"> <strong> of me: </strong> </span> <span class="color-positive"> E +9% </span> </td> <td> <span class="text-muted"> <strong> of others: </strong> </span> <span class="color-positive"> E +9% </span> , <span class="color-positive"> E +9% </span> , <span class="color-negative"> E -18% </span> </td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4> Question 2: <span class="text-preserve-space"> Comments about my contribution (shown to other teammates) </span> </h4> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> You </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> I was the project lead. I designed the application architecture and managed the project to ensure we deliver the product on time. </td> </tr> </tbody> </table> </div> <div class="panel panel-primary"> <div class="panel-heading"> <b> To: </b> Charlie Davis </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Charlie Davis </td> </tr> <tr> <td class="text-preserve-space"> I am a bit slow compared to my team mates, but the members helped me to catch up. </td> </tr> <tr> <td> <ul class="list-group comment-list"> <li class="list-group-item list-group-item-warning" id="responseCommentRow-${comment.id}"> <div id="commentBar-${comment.id}"> <span class="text-muted"> From: [email protected] [Mon, 30 Apr 2012, 09:36 PM UTC] </span> </div> <div id="plainCommentText-${comment.id}" style="margin-left: 15px;"> <p> Well, Being your first team project always takes some time. I hope you had nice experience working with the team. </p> </div> </li> </ul> </td> </tr> </tbody> </table> </div> <div class="panel panel-primary"> <div class="panel-heading"> <b> To: </b> Francis Gabriel </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Francis Gabriel </td> </tr> <tr> <td class="text-preserve-space"> I was the designer. I did all the UI work. </td> </tr> <tr> <td> <ul class="list-group comment-list"> <li class="list-group-item list-group-item-warning" id="responseCommentRow-${comment.id}"> <div id="commentBar-${comment.id}"> <span class="text-muted"> From: [email protected] [Mon, 30 Apr 2012, 09:39 PM UTC] </span> </div> <div id="plainCommentText-${comment.id}" style="margin-left: 15px;"> <p> Design could have been more interactive. </p> </div> </li> </ul> </td> </tr> </tbody> </table> </div> <div class="panel panel-primary"> <div class="panel-heading"> <b> To: </b> Gene Hudson </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Gene Hudson </td> </tr> <tr> <td class="text-preserve-space"> I am the programmer for the team. I did most of the coding. </td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4> Question 3: <span class="text-preserve-space"> My comments about this teammate(confidential and only shown to instructor) </span> </h4> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Charlie Davis </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> A bit weak in terms of technical skills. He spent lots of time in picking up the skills. Although a bit slow in development, his attitude is good. </td> </tr> </tbody> </table> </div> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Francis Gabriel </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> Francis is the designer of the project. He did a good job! </td> </tr> </tbody> </table> </div> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Gene Hudson </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> Gene is the programmer for our team. She put in a lot of effort in coding a significant portion of the project. </td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4> Question 4: <span class="text-preserve-space"> Comments about team dynamics(confidential and only shown to instructor) </span> </h4> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Team 2 </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> I had a great time with this team. Thanks for all the support from the members. </td> </tr> </tbody> </table> </div> </div> </div> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4> Question 5: <span class="text-preserve-space"> My feedback to this teammate(shown anonymously to the teammate) </span> </h4> <div class="panel panel-primary"> <div class="panel-heading"> <b> To: </b> You </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Anonymous student ${participant.hash} </td> </tr> <tr> <td class="text-preserve-space"> Thank you AHPUiT Instrúctör WithPlusInEmail for all the hardwork! </td> </tr> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Anonymous student ${participant.hash} </td> </tr> <tr> <td class="text-preserve-space"> Thank you AHPUiT Instrúctör WithPlusInEmail for all the help in the project. </td> </tr> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> Anonymous student ${participant.hash} </td> </tr> <tr> <td class="text-preserve-space"> Thank you AHPUiT Instrúctör WithPlusInEmail for being such a good team leader! </td> </tr> </tbody> </table> </div> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Charlie Davis </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> Good try Charlie! Thanks for showing great effort in picking up the skills. </td> </tr> </tbody> </table> </div> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Francis Gabriel </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> Nice work Francis! </td> </tr> </tbody> </table> </div> <div class="panel panel-info"> <div class="panel-heading"> <b> To: </b> Gene Hudson </div> <table class="table"> <tbody> <tr class="resultSubheader"> <td> <span class="bold"> <b> From: </b> </span> You </td> </tr> <tr> <td class="text-preserve-space"> Keep up the good work Gene! </td> </tr> </tbody> </table> </div> </div> </div> <br> </div>
thenaesh/teammates
src/test/resources/pages/newlyJoinedInstructorStudentFeedbackResultsPage.html
HTML
gpl-2.0
20,492
/* cast5.c */ /* This file is part of the AVR-Crypto-Lib. Copyright (C) 2006-2015 Daniel Otte ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * \file cast5.c * \author Daniel Otte * \email [email protected] * \date 2006-07-26 * \par License: * GPLv3 or later * \brief Implementation of the CAST5 (aka CAST-128) cipher algorithm as described in RFC 2144 * */ #include <stdint.h> #include <string.h> #include "cast5.h" #include <avr/pgmspace.h> #undef DEBUG #ifdef DEBUG #include "cli.h" #endif #include "cast5-sbox.h" #define S5(x) pgm_read_dword(&s5[(x)]) #define S6(x) pgm_read_dword(&s6[(x)]) #define S7(x) pgm_read_dword(&s7[(x)]) #define S8(x) pgm_read_dword(&s8[(x)]) static void cast5_init_A(uint8_t *dest, uint8_t *src, bool bmode) { uint8_t mask = bmode ? 0x8 : 0; *((uint32_t*) (&dest[0x0])) = *((uint32_t*) (&src[0x0 ^ mask])) ^ S5(src[0xD ^ mask]) ^ S6(src[0xF ^ mask]) ^ S7(src[0xC ^ mask]) ^ S8(src[0xE ^ mask]) ^ S7(src[0x8 ^ mask]); *((uint32_t*) (&dest[0x4])) = *((uint32_t*) (&src[0x8 ^ mask])) ^ S5(dest[0x0]) ^ S6(dest[0x2]) ^ S7(dest[0x1]) ^ S8(dest[0x3]) ^ S8(src[0xA ^ mask]); *((uint32_t*) (&dest[0x8])) = *((uint32_t*) (&src[0xC ^ mask])) ^ S5(dest[0x7]) ^ S6(dest[0x6]) ^ S7(dest[0x5]) ^ S8(dest[0x4]) ^ S5(src[0x9 ^ mask]); *((uint32_t*) (&dest[0xC])) = *((uint32_t*) (&src[0x4 ^ mask])) ^ S5(dest[0xA]) ^ S6(dest[0x9]) ^ S7(dest[0xB]) ^ S8(dest[0x8]) ^ S6(src[0xB ^ mask]); } static void cast5_init_M(uint8_t *dest, uint8_t *src, bool nmode, bool xmode) { uint8_t nmt[] = { 0xB, 0xA, 0x9, 0x8, 0xF, 0xE, 0xD, 0xC, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4 }; /* nmode table */ uint8_t xmt[4][4] = { { 0x2, 0x6, 0x9, 0xC }, { 0x8, 0xD, 0x3, 0x7 }, { 0x3, 0x7, 0x8, 0xD }, { 0x9, 0xC, 0x2, 0x6 } }; #define NMT(x) (src[nmode?nmt[(x)]:(x)]) #define XMT(x) (src[xmt[(xmode<<1) + nmode][(x)]]) *((uint32_t*) (&dest[0x0])) = S5(NMT(0x8)) ^ S6(NMT(0x9)) ^ S7(NMT(0x7)) ^ S8(NMT(0x6)) ^ S5(XMT(0)); *((uint32_t*) (&dest[0x4])) = S5(NMT(0xA)) ^ S6(NMT(0xB)) ^ S7(NMT(0x5)) ^ S8(NMT(0x4)) ^ S6(XMT(1)); *((uint32_t*) (&dest[0x8])) = S5(NMT(0xC)) ^ S6(NMT(0xD)) ^ S7(NMT(0x3)) ^ S8(NMT(0x2)) ^ S7(XMT(2)); *((uint32_t*) (&dest[0xC])) = S5(NMT(0xE)) ^ S6(NMT(0xF)) ^ S7(NMT(0x1)) ^ S8(NMT(0x0)) ^ S8(XMT(3)); } #define S5B(x) pgm_read_byte(3+(uint8_t*)(&s5[(x)])) #define S6B(x) pgm_read_byte(3+(uint8_t*)(&s6[(x)])) #define S7B(x) pgm_read_byte(3+(uint8_t*)(&s7[(x)])) #define S8B(x) pgm_read_byte(3+(uint8_t*)(&s8[(x)])) static void cast5_init_rM(uint8_t *klo, uint8_t *khi, uint8_t offset, uint8_t *src, bool nmode, bool xmode) { uint8_t nmt[] = { 0xB, 0xA, 0x9, 0x8, 0xF, 0xE, 0xD, 0xC, 0x3, 0x2, 0x1, 0x0, 0x7, 0x6, 0x5, 0x4 }; /* nmode table */ uint8_t xmt[4][4] = { { 0x2, 0x6, 0x9, 0xC }, { 0x8, 0xD, 0x3, 0x7 }, { 0x3, 0x7, 0x8, 0xD }, { 0x9, 0xC, 0x2, 0x6 } }; uint8_t t, h = 0; t = S5B(NMT(0x8)) ^ S6B(NMT(0x9)) ^ S7B(NMT(0x7)) ^ S8B(NMT(0x6)) ^ S5B(XMT(0)); klo[offset * 2] |= (t & 0x0f); h |= (t & 0x10); h >>= 1; t = S5B(NMT(0xA)) ^ S6B(NMT(0xB)) ^ S7B(NMT(0x5)) ^ S8B(NMT(0x4)) ^ S6B(XMT(1)); klo[offset * 2] |= (t << 4) & 0xf0; h |= t & 0x10; h >>= 1; t = S5B(NMT(0xC)) ^ S6B(NMT(0xD)) ^ S7B(NMT(0x3)) ^ S8B(NMT(0x2)) ^ S7B(XMT(2)); klo[offset * 2 + 1] |= t & 0xf; h |= t & 0x10; h >>= 1; t = S5B(NMT(0xE)) ^ S6B(NMT(0xF)) ^ S7B(NMT(0x1)) ^ S8B(NMT(0x0)) ^ S8B(XMT(3)); klo[offset * 2 + 1] |= t << 4; h |= t & 0x10; h >>= 1; #ifdef DEBUG cli_putstr("\r\n\t h="); cli_hexdump(&h,1); #endif khi[offset >> 1] |= h << ((offset & 0x1) ? 4 : 0); } #define S_5X(s) pgm_read_dword(&s5[BPX[(s)]]) #define S_6X(s) pgm_read_dword(&s6[BPX[(s)]]) #define S_7X(s) pgm_read_dword(&s7[BPX[(s)]]) #define S_8X(s) pgm_read_dword(&s8[BPX[(s)]]) #define S_5Z(s) pgm_read_dword(&s5[BPZ[(s)]]) #define S_6Z(s) pgm_read_dword(&s6[BPZ[(s)]]) #define S_7Z(s) pgm_read_dword(&s7[BPZ[(s)]]) #define S_8Z(s) pgm_read_dword(&s8[BPZ[(s)]]) void cast5_init(const void *key, uint16_t keylength_b, cast5_ctx_t *s) { /* we migth return if the key is valid and if setup was successful */ uint32_t x[4], z[4]; #define BPX ((uint8_t*)&(x[0])) #define BPZ ((uint8_t*)&(z[0])) s->shortkey = (keylength_b <= 80); /* littel endian only! */ memset(&(x[0]), 0, 16); /* set x to zero */ if (keylength_b > 128) keylength_b = 128; memcpy(&(x[0]), key, (keylength_b + 7) / 8); /* todo: merge a and b and compress the whole stuff */ /***** A *****/ cast5_init_A((uint8_t*) (&z[0]), (uint8_t*) (&x[0]), false); /***** M *****/ cast5_init_M((uint8_t*) (&(s->mask[0])), (uint8_t*) (&z[0]), false, false); /***** B *****/ cast5_init_A((uint8_t*) (&x[0]), (uint8_t*) (&z[0]), true); /***** N *****/ cast5_init_M((uint8_t*) (&(s->mask[4])), (uint8_t*) (&x[0]), true, false); /***** A *****/ cast5_init_A((uint8_t*) (&z[0]), (uint8_t*) (&x[0]), false); /***** N' *****/ cast5_init_M((uint8_t*) (&(s->mask[8])), (uint8_t*) (&z[0]), true, true); /***** B *****/ cast5_init_A((uint8_t*) (&x[0]), (uint8_t*) (&z[0]), true); /***** M' *****/ cast5_init_M((uint8_t*) (&(s->mask[12])), (uint8_t*) (&x[0]), false, true); /* that were the masking keys, now the rotation keys */ /* set the keys to zero */ memset(&(s->rotl[0]), 0, 8); s->roth[0] = s->roth[1] = 0; /***** A *****/ cast5_init_A((uint8_t*) (&z[0]), (uint8_t*) (&x[0]), false); /***** M *****/ cast5_init_rM(&(s->rotl[0]), &(s->roth[0]), 0, (uint8_t*) (&z[0]), false, false); /***** B *****/ cast5_init_A((uint8_t*) (&x[0]), (uint8_t*) (&z[0]), true); /***** N *****/ cast5_init_rM(&(s->rotl[0]), &(s->roth[0]), 1, (uint8_t*) (&x[0]), true, false); /***** A *****/ cast5_init_A((uint8_t*) (&z[0]), (uint8_t*) (&x[0]), false); /***** N' *****/ cast5_init_rM(&(s->rotl[0]), &(s->roth[0]), 2, (uint8_t*) (&z[0]), true, true); /***** B *****/ cast5_init_A((uint8_t*) (&x[0]), (uint8_t*) (&z[0]), true); /***** M' *****/ cast5_init_rM(&(s->rotl[0]), &(s->roth[0]), 3, (uint8_t*) (&x[0]), false, true); /* done ;-) */ } /********************************************************************************************************/ #define ROTL32(a,n) ((a)<<(n) | (a)>>(32-(n))) #define CHANGE_ENDIAN32(x) ((x)<<24 | (x)>>24 | ((x)&0xff00)<<8 | ((x)&0xff0000)>>8 ) typedef uint32_t cast5_f_t(uint32_t, uint32_t, uint8_t); #define IA 3 #define IB 2 #define IC 1 #define ID 0 static uint32_t cast5_f1(uint32_t d, uint32_t m, uint8_t r) { uint32_t t; t = ROTL32((d + m), r); #ifdef DEBUG uint32_t ia,ib,ic,id; cli_putstr("\r\n f1("); cli_hexdump(&d, 4); cli_putc(','); cli_hexdump(&m , 4); cli_putc(','); cli_hexdump(&r, 1);cli_putstr("): I="); cli_hexdump(&t, 4); ia = pgm_read_dword(&s1[((uint8_t*)&t)[IA]] ); ib = pgm_read_dword(&s2[((uint8_t*)&t)[IB]] ); ic = pgm_read_dword(&s3[((uint8_t*)&t)[IC]] ); id = pgm_read_dword(&s4[((uint8_t*)&t)[ID]] ); cli_putstr("\r\n\tIA="); cli_hexdump(&ia, 4); cli_putstr("\r\n\tIB="); cli_hexdump(&ib, 4); cli_putstr("\r\n\tIC="); cli_hexdump(&ic, 4); cli_putstr("\r\n\tID="); cli_hexdump(&id, 4); return (((ia ^ ib) - ic) + id); #else return ((( pgm_read_dword(&s1[((uint8_t*)&t)[IA]]) ^ pgm_read_dword(&s2[((uint8_t*)&t)[IB]])) - pgm_read_dword(&s3[((uint8_t*)&t)[IC]])) + pgm_read_dword(&s4[((uint8_t*)&t)[ID]])); #endif } static uint32_t cast5_f2(uint32_t d, uint32_t m, uint8_t r) { uint32_t t; t = ROTL32((d ^ m), r); #ifdef DEBUG uint32_t ia,ib,ic,id; cli_putstr("\r\n f2("); cli_hexdump(&d, 4); cli_putc(','); cli_hexdump(&m , 4); cli_putc(','); cli_hexdump(&r, 1);cli_putstr("): I="); cli_hexdump(&t, 4); ia = pgm_read_dword(&s1[((uint8_t*)&t)[IA]] ); ib = pgm_read_dword(&s2[((uint8_t*)&t)[IB]] ); ic = pgm_read_dword(&s3[((uint8_t*)&t)[IC]] ); id = pgm_read_dword(&s4[((uint8_t*)&t)[ID]] ); cli_putstr("\r\n\tIA="); cli_hexdump(&ia, 4); cli_putstr("\r\n\tIB="); cli_hexdump(&ib, 4); cli_putstr("\r\n\tIC="); cli_hexdump(&ic, 4); cli_putstr("\r\n\tID="); cli_hexdump(&id, 4); return (((ia - ib) + ic) ^ id); #else return ((( pgm_read_dword(&s1[((uint8_t*)&t)[IA]]) - pgm_read_dword(&s2[((uint8_t*)&t)[IB]])) + pgm_read_dword(&s3[((uint8_t*)&t)[IC]])) ^ pgm_read_dword(&s4[((uint8_t*)&t)[ID]])); #endif } static uint32_t cast5_f3(uint32_t d, uint32_t m, uint8_t r) { uint32_t t; t = ROTL32((m - d), r); #ifdef DEBUG uint32_t ia,ib,ic,id; cli_putstr("\r\n f3("); cli_hexdump(&d, 4); cli_putc(','); cli_hexdump(&m , 4); cli_putc(','); cli_hexdump(&r, 1);cli_putstr("): I="); cli_hexdump(&t, 4); ia = pgm_read_dword(&s1[((uint8_t*)&t)[IA]] ); ib = pgm_read_dword(&s2[((uint8_t*)&t)[IB]] ); ic = pgm_read_dword(&s3[((uint8_t*)&t)[IC]] ); id = pgm_read_dword(&s4[((uint8_t*)&t)[ID]] ); cli_putstr("\r\n\tIA="); cli_hexdump(&ia, 4); cli_putstr("\r\n\tIB="); cli_hexdump(&ib, 4); cli_putstr("\r\n\tIC="); cli_hexdump(&ic, 4); cli_putstr("\r\n\tID="); cli_hexdump(&id, 4); return (((ia + ib) ^ ic) - id); #else return (( pgm_read_dword(&s1[((uint8_t*)&t)[IA]] ) + pgm_read_dword(&s2[((uint8_t*)&t)[IB]])) ^ pgm_read_dword(&s3[((uint8_t*)&t)[IC]])) - pgm_read_dword(&s4[((uint8_t*)&t)[ID]]); #endif } /******************************************************************************/ void cast5_enc(void *block, const cast5_ctx_t *s) { uint32_t l, r, x, y; uint8_t i; cast5_f_t *f[] = { cast5_f1, cast5_f2, cast5_f3 }; l = ((uint32_t*) block)[0]; r = ((uint32_t*) block)[1]; // cli_putstr("\r\n round[-1] = "); // cli_hexdump(&r, 4); for (i = 0; i < (s->shortkey ? 12 : 16); ++i) { x = r; y = (f[i % 3])(CHANGE_ENDIAN32(r), CHANGE_ENDIAN32(s->mask[i]), (((s->roth[i >> 3]) & (1 << (i & 0x7))) ? 0x10 : 0x00) + (((s->rotl[i >> 1]) >> ((i & 1) ? 4 : 0)) & 0x0f)); r = l ^ CHANGE_ENDIAN32(y); // cli_putstr("\r\n round["); DEBUG_B(i); cli_putstr("] = "); // cli_hexdump(&r, 4); l = x; } ((uint32_t*) block)[0] = r; ((uint32_t*) block)[1] = l; } /******************************************************************************/ void cast5_dec(void *block, const cast5_ctx_t *s) { uint32_t l, r, x, y; int8_t i, rounds; cast5_f_t *f[] = { cast5_f1, cast5_f2, cast5_f3 }; l = ((uint32_t*) block)[0]; r = ((uint32_t*) block)[1]; rounds = (s->shortkey ? 12 : 16); for (i = rounds - 1; i >= 0; --i) { x = r; y = (f[i % 3])(CHANGE_ENDIAN32(r), CHANGE_ENDIAN32(s->mask[i]), (((s->roth[i >> 3]) & (1 << (i & 0x7))) ? 0x10 : 0x00) + (((s->rotl[i >> 1]) >> ((i & 1) ? 4 : 0)) & 0x0f)); r = l ^ CHANGE_ENDIAN32(y); l = x; } ((uint32_t*) block)[0] = r; ((uint32_t*) block)[1] = l; } /******************************************************************************/
nerilex/avr-crypto-lib
cast5/cast5.c
C
gpl-2.0
12,161
package org.webbuilder.web.service.script; import org.springframework.stereotype.Service; import org.webbuilder.utils.script.engine.DynamicScriptEngine; import org.webbuilder.utils.script.engine.DynamicScriptEngineFactory; import org.webbuilder.utils.script.engine.ExecuteResult; import org.webbuilder.web.po.script.DynamicScript; import javax.annotation.Resource; import java.util.Map; /** * Created by 浩 on 2015-10-29 0029. */ @Service public class DynamicScriptExecutor { @Resource private DynamicScriptService dynamicScriptService; public ExecuteResult exec(String id, Map<String, Object> param) throws Exception { DynamicScript data = dynamicScriptService.selectByPk(id); if (data == null) { ExecuteResult result = new ExecuteResult(); result.setResult(String.format("script %s not found!", id)); result.setSuccess(false); return result; } DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(data.getType()); return engine.execute(id, param); } }
wb-goup/webbuilder
wb-core/src/main/java/org/webbuilder/web/service/script/DynamicScriptExecutor.java
Java
gpl-2.0
1,079
-- TESTS (1-17 non-calendar time) {- NTest[(* 5 *) b = N[DiscountFactor[1, 9 + 28/100, Compounding -> {Linear, 1}, CompiledDF -> True], 50] , 0.9150805270863837 ] ## HQL discountFactor (InterestRate (Periodic 1) (9+28/100 :: Double)) 1.00 0.0 == 0.9150805270863837 -} {- NTest[(* 7 *) DiscountFactor[1.5, termstructure1, Compounding -> {Linear, 2}] , 0.9203271932613013 ] ## HQL (using term structure) > let termStructure x = 5 + (1/2)*sqrt(x) > let r = (termStructure 1.5) > discountFactor (InterestRate (Periodic 2) r) 1.50 0.0 == 0.9203271932613013 -- refined version -} {- NTest[(* 8 *) DiscountFactor[1.5, termstructure1, Compounding -> {Linear, 2}, CompiledDF -> True] , 0.9203271932613013 ] ## HQL > discountFactor (InterestRate (Periodic 2) (termStructure 1.5)) 1.5 0.0 == 0.9203271932613013 -} {- NTest[(* 9 *) DiscountFactor[3, 8.5, Compounding -> {Exponential, 12}] , 0.7756133702070986 ] ## HQL > discountFactor (InterestRate (Periodic 12) 8.5) 3.0 0.0 == 0.7756133702070988 -} {- NTest[(* 10 *) DiscountFactor[3, 8.5, Compounding -> {Exponential, 12}, CompiledDF -> True] , 0.7756133702070988 ] ## HQL > discountFactor (InterestRate (Periodic 12) 8.5) 3.0 0.0 == 0.7756133702070988 -} {- NTest[(* 16 *) DiscountFactor[1/2, 8.3, Compounding -> Continuous, CompiledDF -> True] , 0.9593493353414723 ] ## HQL > discountFactor (InterestRate Continuous 8.3) 0.5 0 == 0.9593493353414723 -} {- NTest[(* 11 *) DiscountFactor[4.5, termstructure1, Compounding -> {Exponential, 2}] , 0.7643885607510086 ] ## HQL > let termStructure x = 5 + (1/2)*sqrt(x) > let r = (termStructure 4.5) > discountFactor (InterestRate (Periodic 2) r) 4.50 0.0 == 0.7643885607510086 -} {- NTest[(* 12 *) DiscountFactor[4.5, termstructure1, Compounding -> {Exponential, 2}, CompiledDF -> True] , 0.7643885607510086 ] ## HQL > discountFactor (InterestRate (Periodic 2) (termStructure 4.5)) 4.5 0.0 == 0.7643885607510086 -} {- NTest[(* 13 *) DiscountFactor[1/2, 8.5, Compounding -> {LinearExponential, 1}] , 0.9592326139088729 ] ## HQL (convert periodic to continous) > discountFactor (InterestRate (Periodic 2) 8.5) 0.5 0.0 == 0.9592326139088729 -} {- NTest[(* 14 *) DiscountFactor[1/2, 8.5, Compounding -> {LinearExponential, 1}, CompiledDF -> True] , 0.9592326139088729 ] ## HQL > discountFactor (InterestRate (Periodic 2) 8.5) 0.5 0.0 == 0.9592326139088729 -} {- NTest[(* 15 *) DiscountFactor[1/2, 8.3, Compounding -> Continuous] , 0.9593493353414723 ] ## HQL > discountFactor (InterestRate Continuous 8.3) 0.5 0.0 == 0.9593493353414723 -} {- NTest[(* 16 *) DiscountFactor[1/2, 8.3, Compounding -> Continuous, CompiledDF -> True] , 0.9593493353414723 ] ## HQL > discountFactor (InterestRate Continuous 8.3) 0.5 0.0 == 0.9593493353414723 -} {- NTest[(* 17 *) N[DiscountFactor[90/360, termstructure1, Compounding -> Continuous]] , 0.9871663954590084 ] ## HQL > discountFactor (InterestRate Continuous (termStructure (90/360 :: Double))) (90/360 :: Double) 0.0 == 0.9869607572146836 -} ---- FORWARD RATE {- n = 2; theta1 = 0.25; theta2 = 1.5; interest1 = 6.65; interest2 = 7.77; Out[8]= 7.99473 ## HQL > (((discountFactor (InterestRate (Periodic 2) 6.65) 0.25 0.0)/(discountFactor (InterestRate (Periodic 2) 7.77) 1.5))**(1/(2*1.25))-1)*2*100 == 7.994727369824384 -} -- Include in tests error: abs(output - expected) / expected -- Create a new discount factor from input, where several -- ways are supported. Create DiscountFactor from: -- 1) InterestRate -- 2) TermStructure (yield curve) -- 3) Forward rates (has to be two) {- newDF :: InterestRate -> DiscountFactor Create discount factor (ie zero bond) - Interest rate (as percentage) - Time to maturity - Linear, Exponential, Continous => Periodic, Continuous -}
andreasbock/hql
testsuite/DiscountingTest.hs
Haskell
gpl-2.0
3,753
/* * Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package org.n52.io.measurement.img; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Date; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Before; import org.junit.Test; import org.n52.io.IoStyleContext; import org.n52.io.MimeType; import org.n52.io.request.RequestSimpleParameterSet; import org.n52.io.response.dataset.DataCollection; import org.n52.io.response.dataset.measurement.MeasurementData; public class ChartRendererTest { private static final String VALID_ISO8601_RELATIVE_START = "PT6H/2013-08-13TZ"; private static final String VALID_ISO8601_ABSOLUTE_START = "2013-07-13TZ/2013-08-13TZ"; private static final String VALID_ISO8601_DAYLIGHT_SAVING_SWITCH = "2013-10-28T02:00:00+02:00/2013-10-28T02:00:00+01:00"; private MyChartRenderer chartRenderer; @Before public void setUp() { this.chartRenderer = new MyChartRenderer(IoStyleContext.createEmpty()); } @Test public void shouldParseBeginFromIso8601PeriodWithRelativeStart() { Date start = chartRenderer.getStartTime(VALID_ISO8601_RELATIVE_START); assertThat(start, is(DateTime.parse("2013-08-13TZ").minusHours(6).toDate())); } @Test public void shouldParseBeginFromIso8601PeriodWithAbsoluteStart() { Date start = chartRenderer.getStartTime(VALID_ISO8601_ABSOLUTE_START); assertThat(start, is(DateTime.parse("2013-08-13TZ").minusMonths(1).toDate())); } @Test public void shouldParseBeginAndEndFromIso8601PeriodContainingDaylightSavingTimezoneSwith() { Date start = chartRenderer.getStartTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); Date end = chartRenderer.getEndTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); assertThat(start, is(DateTime.parse("2013-10-28T00:00:00Z").toDate())); assertThat(end, is(DateTime.parse("2013-10-28T01:00:00Z").toDate())); } @Test public void shouldHaveCETTimezoneIncludedInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); assertThat(label, is("Time (+01:00)")); } @Test public void shouldHandleEmptyTimespanWhenIncludingTimezoneInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(null); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); //assertThat(label, is("Time (+01:00)")); } @Test public void shouldHaveUTCTimezoneIncludedInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_ABSOLUTE_START); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(VALID_ISO8601_ABSOLUTE_START.split("/")[1]); assertThat(label, is("Time (UTC)")); } static class MyChartRenderer extends ChartIoHandler { public MyChartRenderer(IoStyleContext context) { super(new RequestSimpleParameterSet(), null, context); } public MyChartRenderer() { super(new RequestSimpleParameterSet(), null, null); } @Override public void setMimeType(MimeType mimetype) { throw new UnsupportedOperationException(); } @Override public void writeDataToChart(DataCollection<MeasurementData> data) { throw new UnsupportedOperationException(); } } }
ridoo/timeseries-api
io/src/test/java/org/n52/io/measurement/img/ChartRendererTest.java
Java
gpl-2.0
5,333
<?php class highlighter { public function register_shortcode($shortcodeName) { function shortcode_highlighter($atts, $content = null) { extract( shortcode_atts( array( 'type' => 'colored' ), $atts ) ); return "<span class='highlighted_".$type."'>".$content."</span>"; } add_shortcode($shortcodeName, 'shortcode_highlighter'); } } #Shortcode name $shortcodeName="highlighter"; #Compile UI for admin panel #Don't change this line $gt3_compileShortcodeUI = "<div class='whatInsert whatInsert_".$shortcodeName."'>".$gt3_defaultUI."</div>"; #This function is executed each time when you click "Insert" shortcode button. $gt3_compileShortcodeUI .= " <table> <tr> <td>Type:</td> <td> <select name='".$shortcodeName."_separator_type' class='".$shortcodeName."_type'>"; if (is_array($GLOBALS["pbconfig"]['all_available_highlighters'])) { foreach ($GLOBALS["pbconfig"]['all_available_highlighters'] as $value => $caption) { $gt3_compileShortcodeUI .= "<option value='".$value."'>".$caption."</option>"; } } $gt3_compileShortcodeUI .= "</select> </td> </tr> </table> <script> function ".$shortcodeName."_handler() { /* YOUR CODE HERE */ var type = jQuery('.".$shortcodeName."_type').val(); /* END YOUR CODE */ /* COMPILE SHORTCODE LINE */ var compileline = '[".$shortcodeName." type=\"'+type+'\"][/".$shortcodeName."]'; /* DO NOT CHANGE THIS LINE */ jQuery('.whatInsert_".$shortcodeName."').html(compileline); } </script> "; #Register shortcode & set parameters $highlighter = new highlighter(); $highlighter->register_shortcode($shortcodeName); shortcodesUI::getInstance()->add('highlighter', array("name" => $shortcodeName, "caption" => "Highlighter", "handler" => $gt3_compileShortcodeUI)); unset($gt3_compileShortcodeUI); ?>
jasonglisson/susannerossi
wp-content/plugins/gt3-pagebuilder-custom/core/shortcodes/highlighter.php
PHP
gpl-2.0
1,874
/********************************************************************************************* * Fichero: Bmp.c * Autor: * Descrip: Funciones de control y visualizacion del LCD * Version: *********************************************************************************************/ /*--- Archivos cabecera ---*/ #include "bmp.h" #include "def.h" #include "lcd.h" /*--- variables globales ---*/ /* mapa de bits del cursor del raton */ const INT8U ucMouseMap[] = { BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLACK, BLACK, BLACK, BLACK, BLACK, BLACK, WHITE, WHITE, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, BLACK, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, BLACK, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, WHITE, WHITE, WHITE, BLACK, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, TRANSPARENCY, BLACK, BLACK, BLACK, TRANSPARENCY, TRANSPARENCY }; STRU_BITMAP Stru_Bitmap_gbMouse = {0x10, 4, 12, 20, TRANSPARENCY, (INT8U *)ucMouseMap}; INT16U ulMouseX; INT16U ulMouseY; INT8U ucCursorBackUp[20][12/2]; /*--- codigo de funcion ---*/ /********************************************************************************************* * name: BitmapView() * func: display bitmap * para: x,y -- pot's X-Y coordinate * Stru_Bitmap -- bitmap struct * ret: none * modify: * comment: *********************************************************************************************/ void BitmapView (INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap) { INT32U i, j; INT8U ucColor; for (i = 0; i < Stru_Bitmap.usHeight; i++) { for (j = 0; j <Stru_Bitmap.usWidth; j++) { if ((ucColor = *(INT8U*)(Stru_Bitmap.pucStart + i * Stru_Bitmap.usWidth + j)) != TRANSPARENCY) { LCD_PutPixel(x + j, y + i, ucColor); } } } } /********************************************************************************************* * name: BitmapPush() * func: push bitmap data into LCD active buffer * para: x,y -- pot's X-Y coordinate * Stru_Bitmap -- bitmap struct * ret: none * modify: * comment: *********************************************************************************************/ void BitmapPush (INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap) { INT32U i, j; ulMouseX = x; ulMouseY = y; for (i = 0; i < Stru_Bitmap.usHeight; i++) { for (j = 0; j < Stru_Bitmap.usWidth; j+=2) { if ((x + j)%2) { ucCursorBackUp[i][j/2] = (((*(INT8U*)(LCD_ACTIVE_BUFFER + (y + i) * SCR_XSIZE / 2 + (x + j) / 8 * 4 + 3 - ((x + j)%8) / 2)) << 4) & 0xf0) + (((*(INT8U*)(LCD_ACTIVE_BUFFER + (y + i) * SCR_XSIZE / 2 + (x + j+1) / 8 * 4 + 3 - ((x + j+1)%8) / 2)) >> 4) & 0x0f); } else { ucCursorBackUp[i][j/2] = (*(INT8U*)(LCD_ACTIVE_BUFFER + (y + i) * SCR_XSIZE / 2 + (x + j) / 8 * 4 + 3 - ((x + j)%8) / 2)); } } } } /********************************************************************************************* * name: BitmapPop() * func: pop bitmap data into LCD active buffer * para: x,y -- pot's X-Y coordinate * Stru_Bitmap -- bitmap struct * ret: none * modify: * comment: *********************************************************************************************/ void BitmapPop(INT16U x, INT16U y, STRU_BITMAP Stru_Bitmap) { INT32U i, j; INT32U ulAddr, ulAddr1; for (i = 0; i < Stru_Bitmap.usHeight; i++) { for (j = 0; j <Stru_Bitmap.usWidth; j+=2) { ulAddr = LCD_ACTIVE_BUFFER + (y + i) * SCR_XSIZE / 2 + (x + j) / 8 * 4 + 3 - ((x + j)%8) / 2; ulAddr1 =LCD_ACTIVE_BUFFER + (y + i) * SCR_XSIZE / 2 + (x + j + 1) / 8 * 4 + 3 - ((x + j + 1)%8) / 2; if ((x + j)%2) { (*(INT8U*)ulAddr) &= 0xf0; (*(INT8U*)ulAddr) |= ((ucCursorBackUp[i][j/2] >> 4) & 0x0f); (*(INT8U*)ulAddr1) &= 0x0f; (*(INT8U*)ulAddr1) |= ((ucCursorBackUp[i][j/2] << 4) & 0xf0); } else { (*(INT8U*)ulAddr) = ucCursorBackUp[i][j/2]; } } } } /********************************************************************************************* * name: CursorInit() * func: cursor init * para: none * ret: none * modify: * comment: *********************************************************************************************/ void CursorInit(void) { ulMouseX = 0; ulMouseY = 0; CursorView(ulMouseX, ulMouseY); } /********************************************************************************************* * name: CursorPush() * func: cursor push * para: none * ret: none * modify: * comment: *********************************************************************************************/ void CursorPush(INT16U x, INT16U y) { BitmapPush(x, y, Stru_Bitmap_gbMouse); } /********************************************************************************************* * name: CursorPop() * func: cursor pop * para: none * ret: none * modify: * comment: *********************************************************************************************/ void CursorPop() { BitmapPop(ulMouseX, ulMouseY, Stru_Bitmap_gbMouse); } /********************************************************************************************* * name: CursorView() * func: cursor display * para: none * ret: none * modify: * comment: *********************************************************************************************/ void CursorView(INT16U x, INT16U y) { CursorPush(x, y); BitmapView(x, y, Stru_Bitmap_gbMouse); }
UnizarCurryMicroSystems/ProyectoHardware
PH_3/Bmp.c
C
gpl-2.0
8,483
// CS4005: Async methods cannot have unsafe parameters // Line: 7 // Compiler options: -unsafe class C { public unsafe async void Test (int* arg) { } }
xen2/mcs
errors/cs4005.cs
C#
gpl-2.0
156
<html> <head> <script> window.onload = function() { var d = new Date().getTime(); document.getElementById("tid").value = d; }; </script> </head> <body> <?php if(isset($_GET['token'])) { $token = $_GET['token']; $name = $_GET['name']; $token = $_GET['token']; $token1 = substr($token,6); $email = $_GET['email']; $quantity = (int)1; $currency = $_GET['curr']; $fees = $_GET['fees']; $server = 'http://'.$_SERVER['SERVER_NAME']; ?> <form method="post" id="customerData" name="customerData" action="ccavRequestHandler.php"> <input type="text" name="tid" id="tid" readonly /> <input type="text" name="merchant_id" value="79450"/> <input type="text" name="order_id" value="<?php echo trim($token1); ?>"/> <input type="text" name="amount" value="<?php echo trim($fees); ?>"/> <input type="text" name="currency" value="<?php echo trim($currency); ?>"/> <input type="text" name="redirect_url" value="<?php echo $server.'/ccavenue/nonseam/ccavResponseHandler.php' ?>"/> <input type="text" name="cancel_url" value="<?php echo $server.'/ccavenue/nonseam/ccavResponseHandler.php?payment=fail' ?>"/> <input type="text" name="language" value="EN"/> <input type="text" name="billing_name" value="<?php echo trim($name); ?>"/> <input type="text" name="billing_email" value="<?php echo trim($email); ?>"/> <input type="text" name="billing_address" value="Dummy Address. Please ignore details."/> <input type="text" name="billing_city" value="Ignore City"/> <input type="text" name="billing_state" value="Ignore State"/> <input type="text" name="billing_country" value="India"/> <input type="text" name="billing_zip" value="123456"/> <input type="text" name="billing_tel" value="1234567891"/> <input type="submit" value="CheckOut" /> <?php } ?> </form> <script language='javascript'>document.customerData.submit();</script> </body> </html>
luffy22/aisha
ccavenue/nonseam/ccavenue_payment.php
PHP
gpl-2.0
2,167
/* * USI wm-bn-bm-01-5(bcm4329) sdio wifi power management API * evb gpio define * A10 gpio define: * usi_bm01a_wl_pwr = port:PH12<1><default><default><0> * usi_bm01a_wlbt_regon = port:PI11<1><default><default><0> * usi_bm01a_wl_rst = port:PI10<1><default><default><0> * usi_bm01a_wl_wake = port:PI12<1><default><default><0> * usi_bm01a_bt_rst = port:PB05<1><default><default><0> * usi_bm01a_bt_wake = port:PI20<1><default><default><0> * usi_bm01a_bt_hostwake = port:PI21<0><default><default><0> * ----------------------------------------------------------- * A12 gpio define: * usi_bm01a_wl_pwr = LDO3 * usi_bm01a_wl_wake = port:PA01<1><default><default><0> * usi_bm01a_wlbt_regon = port:PA02<1><default><default><0> * usi_bm01a_wl_rst = port:PA03<1><default><default><0> * usi_bm01a_bt_rst = port:PA04<1><default><default><0> * usi_bm01a_bt_wake = port:PA05<1><default><default><0> * usi_bm01a_bt_hostwake = */ #include <linux/kernel.h> #include <linux/module.h> #include <mach/sys_config.h> #include "mmc_pm.h" #define usi_msg(...) do {printk("[usi_bm01a]: "__VA_ARGS__);} while(0) static int usi_bm01a_wl_on = 0; static int usi_bm01a_bt_on = 0; #if CONFIG_CHIP_ID==1125 #include <linux/regulator/consumer.h> static int usi_bm01a_power_onoff(int onoff) { struct regulator* wifi_ldo = NULL; static int first = 1; #ifndef CONFIG_AW_AXP usi_msg("AXP driver is disabled, pls check !!\n"); return 0; #endif usi_msg("usi_bm01a_power_onoff\n"); wifi_ldo = regulator_get(NULL, "axp20_pll"); if (!wifi_ldo) usi_msg("Get power regulator failed\n"); if (first) { usi_msg("first time\n"); regulator_force_disable(wifi_ldo); first = 0; } if (onoff) { usi_msg("regulator on\n"); regulator_set_voltage(wifi_ldo, 3300000, 3300000); regulator_enable(wifi_ldo); } else { usi_msg("regulator off\n"); regulator_disable(wifi_ldo); } return 0; } #endif static int usi_bm01a_gpio_ctrl(char* name, int level) { struct mmc_pm_ops *ops = &mmc_card_pm_ops; char* gpio_cmd[6] = {"usi_bm01a_wl_regon", "usi_bm01a_bt_regon", "usi_bm01a_wl_rst", "usi_bm01a_wl_wake", "usi_bm01a_bt_rst", "usi_bm01a_bt_wake"}; int i = 0; int ret = 0; for (i=0; i<6; i++) { if (strcmp(name, gpio_cmd[i])==0) break; } if (i==6) { usi_msg("No gpio %s for USI-BM01A module\n", name); return -1; } // usi_msg("Set GPIO %s to %d !\n", name, level); if (strcmp(name, "usi_bm01a_wl_regon") == 0) { if (level) { if (usi_bm01a_bt_on) { usi_msg("USI-BM01A is already powered up by bluetooth\n"); goto change_state; } else { usi_msg("USI-BM01A is powered up by wifi\n"); goto power_change; } } else { if (usi_bm01a_bt_on) { usi_msg("USI-BM01A should stay on because of bluetooth\n"); goto change_state; } else { usi_msg("USI-BM01A is powered off by wifi\n"); goto power_change; } } } if (strcmp(name, "usi_bm01a_bt_regon") == 0) { if (level) { if (usi_bm01a_wl_on) { usi_msg("USI-BM01A is already powered up by wifi\n"); goto change_state; } else { usi_msg("USI-BM01A is powered up by bt\n"); goto power_change; } } else { if (usi_bm01a_wl_on) { usi_msg("USI-BM01A should stay on because of wifi\n"); goto change_state; } else { usi_msg("USI-BM01A is powered off by bt\n"); goto power_change; } } } ret = gpio_write_one_pin_value(ops->pio_hdle, level, name); if (ret) { usi_msg("Failed to set gpio %s to %d !\n", name, level); return -1; } return 0; power_change: #if CONFIG_CHIP_ID==1123 ret = gpio_write_one_pin_value(ops->pio_hdle, level, "usi_bm01a_wl_pwr"); #elif CONFIG_CHIP_ID==1125 ret = usi_bm01a_power_onoff(level); #else #error "Found wrong chip id in wifi onoff\n" #endif if (ret) { usi_msg("Failed to power off USI-BM01A module!\n"); return -1; } ret = gpio_write_one_pin_value(ops->pio_hdle, level, "usi_bm01a_wlbt_regon"); if (ret) { usi_msg("Failed to regon off for USI-BM01A module!\n"); return -1; } change_state: if (strcmp(name, "usi_bm01a_wl_regon")==0) usi_bm01a_wl_on = level; if (strcmp(name, "usi_bm01a_bt_regon")==0) usi_bm01a_bt_on = level; usi_msg("USI-BM01A power state change: wifi %d, bt %d !!\n", usi_bm01a_wl_on, usi_bm01a_bt_on); return 0; } static int usi_bm01a_get_gpio_value(char* name) { struct mmc_pm_ops *ops = &mmc_card_pm_ops; char* bt_hostwake = "usi_bm01a_bt_hostwake"; if (strcmp(name, bt_hostwake)) { usi_msg("No gpio %s for USI-BM01A\n", name); return -1; } return gpio_read_one_pin_value(ops->pio_hdle, name); } void usi_bm01a_gpio_init(void) { struct mmc_pm_ops *ops = &mmc_card_pm_ops; usi_bm01a_wl_on = 0; usi_bm01a_bt_on = 0; ops->gpio_ctrl = usi_bm01a_gpio_ctrl; ops->get_io_val = usi_bm01a_get_gpio_value; }
sdugit/linux-3.0_7025
drivers/mmc/mmc-pm/mmc_pm_usi_bm01a.c
C
gpl-2.0
5,469
<?php /** * jsonRPCClient.php * * Written using the JSON RPC specification - * http://json-rpc.org/wiki/specification * * @author Kacper Rowinski <[email protected]> * http://implix.com */ class jsonRPCClient { protected $url = null, $is_debug = false, $parameters_structure = 'array'; /** * Default options for curl * * @var array */ protected $curl_options = array( CURLOPT_CONNECTTIMEOUT => 8, CURLOPT_TIMEOUT => 8 ); /** * Http error statuses * * Source: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes * * @var array */ private $httpErrors = array( 400 => '400 Bad Request', 401 => '401 Unauthorized', 403 => '403 Forbidden', 404 => '404 Not Found', 405 => '405 Method Not Allowed', 406 => '406 Not Acceptable', 408 => '408 Request Timeout', 500 => '500 Internal Server Error', 502 => '502 Bad Gateway', 503 => '503 Service Unavailable' ); /** * Takes the connection parameter and checks for extentions * * @param string $pUrl - url name like http://example.com/ */ public function __construct($pUrl) { $this->validate(false === extension_loaded('curl'), 'The curl extension must be loaded for using this class!'); $this->validate(false === extension_loaded('json'), 'The json extension must be loaded for using this class!'); // set an url to connect to $this->url = $pUrl; } /** * Return http error message * * @param $pErrorNumber * * @return string|null */ private function getHttpErrorMessage($pErrorNumber) { return isset($this->httpErrors[$pErrorNumber]) ? $this->httpErrors[$pErrorNumber] : null; } /** * Set debug mode * * @param boolean $pIsDebug * * @return jsonRPCClient */ public function setDebug($pIsDebug) { $this->is_debug = !empty($pIsDebug); return $this; } /** * Set structure to use for parameters * * @param string $pParametersStructure 'array' or 'object' * * @throws UnexpectedValueException * @return jsonRPCClient */ public function setParametersStructure($pParametersStructure) { if (in_array($pParametersStructure, array('array', 'object'))) { $this->parameters_structure = $pParametersStructure; } else { throw new UnexpectedValueException('Invalid parameters structure type.'); } return $this; } /** * Set extra options for curl connection * * @param array $pOptionsArray * * @throws InvalidArgumentException * @return jsonRPCClient */ public function setCurlOptions($pOptionsArray) { if (is_array($pOptionsArray)) { $this->curl_options = $pOptionsArray + $this->curl_options; } else { throw new InvalidArgumentException('Invalid options type.'); } return $this; } /** * Performs a request and gets the results * * @param string $pMethod - A String containing the name of the method to be invoked. * @param array $pParams - An Array of objects to pass as arguments to the method. * * @throws RuntimeException * @return array */ public function __call($pMethod, $pParams) { static $requestId = 0; // generating uniuqe id per process $requestId++; // check if given params are correct $this->validate(false === is_scalar($pMethod), 'Method name has no scalar value'); $this->validate(false === is_array($pParams), 'Params must be given as array'); // send params as an object or an array $pParams = ($this->parameters_structure == 'object') ? $pParams[0] : array_values($pParams); // Request (method invocation) $request = json_encode(array('jsonrpc' => '2.0', 'method' => $pMethod, 'params' => $pParams, 'id' => $requestId)); // if is_debug mode is true then add url and request to is_debug $this->debug('Url: ' . $this->url . "\r\n", false); $this->debug('Request: ' . $request . "\r\n", false); $responseMessage = $this->getResponse($request); // if is_debug mode is true then add response to is_debug and display it $this->debug('Response: ' . $responseMessage . "\r\n", true); // decode and create array ( can be object, just set to false ) $responseDecoded = json_decode($responseMessage, true); // check if decoding json generated any errors $jsonErrorMsg = $this->getJsonLastErrorMsg(); $this->validate( !is_null($jsonErrorMsg), $jsonErrorMsg . ': ' . $responseMessage); // check if response is correct $this->validate(empty($responseDecoded['id']), 'Invalid response data structure: ' . $responseMessage); $this->validate($responseDecoded['id'] != $requestId, 'Request id: ' . $requestId . ' is different from Response id: ' . $responseDecoded['id']); if (isset($responseDecoded['error'])) { $errorMessage = 'Request have return error: ' . $responseDecoded['error']['message'] . '; ' . "\n" . 'Request: ' . $request . '; '; if (isset($responseDecoded['error']['data'])) { $errorMessage .= "\n" . 'Error data: ' . $responseDecoded['error']['data']; } $this->validate( !is_null($responseDecoded['error']), $errorMessage); } return $responseDecoded['result']; } /** * When the method invocation completes, the service must reply with a response. * The response is a single object serialized using JSON * * @param string $pRequest * * @throws RuntimeException * @return string */ protected function & getResponse(&$pRequest) { // do the actual connection $ch = curl_init(); if ( !$ch) { throw new RuntimeException('Could\'t initialize a cURL session'); } curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $pRequest); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ( !curl_setopt_array($ch, $this->curl_options)) { throw new RuntimeException('Error while setting curl options'); } // send the request $response = curl_exec($ch); // check http status code $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (isset($this->httpErrors[$httpCode])) { throw new RuntimeException('Response Http Error - ' . $this->httpErrors[$httpCode]); } // check for curl error if (0 < curl_errno($ch)) { throw new RuntimeException('Unable to connect to '.$this->url . ' Error: ' . curl_error($ch)); } // close the connection curl_close($ch); return $response; } /** * Throws exception if validation is failed * * @param bool $pFailed * @param string $pErrMsg * * @throws RuntimeException */ protected function validate($pFailed, $pErrMsg) { if ($pFailed) { throw new RuntimeException($pErrMsg); } } /** * For is_debug and performance stats * * @param string $pAdd * @param bool $pShow */ protected function debug($pAdd, $pShow = false) { static $debug, $startTime; // is_debug off return if (false === $this->is_debug) { return; } // add $debug .= $pAdd; // get starttime $startTime = empty($startTime) ? array_sum(explode(' ', microtime())) : $startTime; if (true === $pShow and !empty($debug)) { // get endtime $endTime = array_sum(explode(' ', microtime())); // performance summary $debug .= 'Request time: ' . round($endTime - $startTime, 3) . ' s Memory usage: ' . round(memory_get_usage() / 1024) . " kb\r\n"; echo nl2br($debug); // send output imidiately flush(); // clean static $debug = $startTime = null; } } /** * Getting JSON last error message * Function json_last_error_msg exists from PHP 5.5 * * @return string */ function getJsonLastErrorMsg() { if (!function_exists('json_last_error_msg')) { function json_last_error_msg() { static $errors = array( JSON_ERROR_NONE => 'No error', JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded' ); $error = json_last_error(); return array_key_exists($error, $errors) ? $errors[$error] : 'Unknown error (' . $error . ')'; } } // Fix PHP 5.2 error caused by missing json_last_error function if (function_exists('json_last_error')) { return json_last_error() ? json_last_error_msg() : null; } else { return null; } } }
mssdeepakkumar/keenlo
wp-content/plugins/formcraft-add-on-pack/getresponse.php
PHP
gpl-2.0
9,967
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.bind.v2.util; import java.util.AbstractList; import java.util.Arrays; import java.util.List; import java.util.Stack; /** * {@link Stack}-like data structure that allows the following efficient operations: * * <ol> * <li>Push/pop operation. * <li>Duplicate check. When an object that's already in the stack is pushed, * this class will tell you so. * </ol> * * <p> * Object equality is their identity equality. * * <p> * This class implements {@link List} for accessing items in the stack, * but {@link List} methods that alter the stack is not supported. * * @author Kohsuke Kawaguchi */ public final class CollisionCheckStack<E> extends AbstractList<E> { private Object[] data; private int[] next; private int size = 0; /** * True if the check shall be done by using the object identity. * False if the check shall be done with the equals method. */ private boolean useIdentity = true; // for our purpose, there isn't much point in resizing this as we don't expect // the stack to grow that much. private final int[] initialHash; public CollisionCheckStack() { initialHash = new int[17]; data = new Object[16]; next = new int[16]; } /** * Set to false to use {@link Object#equals(Object)} to detect cycles. * This method can be only used when the stack is empty. */ public void setUseIdentity(boolean useIdentity) { this.useIdentity = useIdentity; } public boolean getUseIdentity() { return useIdentity; } /** * Pushes a new object to the stack. * * @return * true if this object has already been pushed */ public boolean push(E o) { if(data.length==size) expandCapacity(); data[size] = o; int hash = hash(o); boolean r = findDuplicate(o, hash); next[size] = initialHash[hash]; initialHash[hash] = size+1; size++; return r; } /** * Pushes a new object to the stack without making it participate * with the collision check. */ public void pushNocheck(E o) { if(data.length==size) expandCapacity(); data[size] = o; next[size] = -1; size++; } @Override public E get(int index) { return (E)data[index]; } @Override public int size() { return size; } private int hash(Object o) { return ((useIdentity?System.identityHashCode(o):o.hashCode())&0x7FFFFFFF) % initialHash.length; } /** * Pops an object from the stack */ public E pop() { size--; Object o = data[size]; data[size] = null; // keeping references too long == memory leak int n = next[size]; if(n<0) { // pushed by nocheck. no need to update hash } else { int hash = hash(o); assert initialHash[hash]==size+1; initialHash[hash] = n; } return (E)o; } /** * Returns the top of the stack. */ public E peek() { return (E)data[size-1]; } private boolean findDuplicate(E o, int hash) { int p = initialHash[hash]; while(p!=0) { p--; Object existing = data[p]; if (useIdentity) { if(existing==o) return true; } else { if (o.equals(existing)) return true; } p = next[p]; } return false; } private void expandCapacity() { int oldSize = data.length; int newSize = oldSize * 2; Object[] d = new Object[newSize]; int[] n = new int[newSize]; System.arraycopy(data,0,d,0,oldSize); System.arraycopy(next,0,n,0,oldSize); data = d; next = n; } /** * Clears all the contents in the stack. */ public void reset() { if(size>0) { size = 0; Arrays.fill(initialHash,0); } } /** * String that represents the cycle. */ public String getCycleString() { StringBuilder sb = new StringBuilder(); int i=size()-1; E obj = get(i); sb.append(obj); Object x; do { sb.append(" -> "); x = get(--i); sb.append(x); } while(obj!=x); return sb.toString(); } }
samskivert/ikvm-openjdk
build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/util/CollisionCheckStack.java
Java
gpl-2.0
5,703
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Thu Oct 02 16:39:51 BST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>com.hp.hpl.jena.sparql (Apache Jena ARQ)</title> <meta name="date" content="2014-10-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../com/hp/hpl/jena/sparql/package-summary.html" target="classFrame">com.hp.hpl.jena.sparql</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ARQConstants.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">ARQConstants</a></li> <li><a href="SystemARQ.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">SystemARQ</a></li> </ul> <h2 title="Exceptions">Exceptions</h2> <ul title="Exceptions"> <li><a href="AlreadyExists.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">AlreadyExists</a></li> <li><a href="ARQException.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">ARQException</a></li> <li><a href="ARQInternalErrorException.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">ARQInternalErrorException</a></li> <li><a href="ARQNotImplemented.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">ARQNotImplemented</a></li> <li><a href="DoesNotExist.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">DoesNotExist</a></li> <li><a href="JenaTransactionException.html" title="class in com.hp.hpl.jena.sparql" target="classFrame">JenaTransactionException</a></li> </ul> </div> </body> </html>
knil-sama/YADDW
lib/apache-jena-2.12.1/javadoc-arq/com/hp/hpl/jena/sparql/package-frame.html
HTML
gpl-2.0
1,782
/* * arch/arm/mach-at91/include/mach/gpio.h * * Copyright (C) 2005 HP Labs * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ #ifndef __ASM_ARCH_AT91RM9200_GPIO_H #define __ASM_ARCH_AT91RM9200_GPIO_H #include <linux/kernel.h> #include <asm/irq.h> #define MAX_GPIO_BANKS 5 #define NR_BUILTIN_GPIO (MAX_GPIO_BANKS * 32) /* these pin numbers double as IRQ numbers, like AT91xxx_ID_* values */ #define AT91_PIN_PA0 (0x00 + 0) #define AT91_PIN_PA1 (0x00 + 1) #define AT91_PIN_PA2 (0x00 + 2) #define AT91_PIN_PA3 (0x00 + 3) #define AT91_PIN_PA4 (0x00 + 4) #define AT91_PIN_PA5 (0x00 + 5) #define AT91_PIN_PA6 (0x00 + 6) #define AT91_PIN_PA7 (0x00 + 7) #define AT91_PIN_PA8 (0x00 + 8) #define AT91_PIN_PA9 (0x00 + 9) #define AT91_PIN_PA10 (0x00 + 10) #define AT91_PIN_PA11 (0x00 + 11) #define AT91_PIN_PA12 (0x00 + 12) #define AT91_PIN_PA13 (0x00 + 13) #define AT91_PIN_PA14 (0x00 + 14) #define AT91_PIN_PA15 (0x00 + 15) #define AT91_PIN_PA16 (0x00 + 16) #define AT91_PIN_PA17 (0x00 + 17) #define AT91_PIN_PA18 (0x00 + 18) #define AT91_PIN_PA19 (0x00 + 19) #define AT91_PIN_PA20 (0x00 + 20) #define AT91_PIN_PA21 (0x00 + 21) #define AT91_PIN_PA22 (0x00 + 22) #define AT91_PIN_PA23 (0x00 + 23) #define AT91_PIN_PA24 (0x00 + 24) #define AT91_PIN_PA25 (0x00 + 25) #define AT91_PIN_PA26 (0x00 + 26) #define AT91_PIN_PA27 (0x00 + 27) #define AT91_PIN_PA28 (0x00 + 28) #define AT91_PIN_PA29 (0x00 + 29) #define AT91_PIN_PA30 (0x00 + 30) #define AT91_PIN_PA31 (0x00 + 31) #define AT91_PIN_PB0 (0x20 + 0) #define AT91_PIN_PB1 (0x20 + 1) #define AT91_PIN_PB2 (0x20 + 2) #define AT91_PIN_PB3 (0x20 + 3) #define AT91_PIN_PB4 (0x20 + 4) #define AT91_PIN_PB5 (0x20 + 5) #define AT91_PIN_PB6 (0x20 + 6) #define AT91_PIN_PB7 (0x20 + 7) #define AT91_PIN_PB8 (0x20 + 8) #define AT91_PIN_PB9 (0x20 + 9) #define AT91_PIN_PB10 (0x20 + 10) #define AT91_PIN_PB11 (0x20 + 11) #define AT91_PIN_PB12 (0x20 + 12) #define AT91_PIN_PB13 (0x20 + 13) #define AT91_PIN_PB14 (0x20 + 14) #define AT91_PIN_PB15 (0x20 + 15) #define AT91_PIN_PB16 (0x20 + 16) #define AT91_PIN_PB17 (0x20 + 17) #define AT91_PIN_PB18 (0x20 + 18) #define AT91_PIN_PB19 (0x20 + 19) #define AT91_PIN_PB20 (0x20 + 20) #define AT91_PIN_PB21 (0x20 + 21) #define AT91_PIN_PB22 (0x20 + 22) #define AT91_PIN_PB23 (0x20 + 23) #define AT91_PIN_PB24 (0x20 + 24) #define AT91_PIN_PB25 (0x20 + 25) #define AT91_PIN_PB26 (0x20 + 26) #define AT91_PIN_PB27 (0x20 + 27) #define AT91_PIN_PB28 (0x20 + 28) #define AT91_PIN_PB29 (0x20 + 29) #define AT91_PIN_PB30 (0x20 + 30) #define AT91_PIN_PB31 (0x20 + 31) #define AT91_PIN_PC0 (0x40 + 0) #define AT91_PIN_PC1 (0x40 + 1) #define AT91_PIN_PC2 (0x40 + 2) #define AT91_PIN_PC3 (0x40 + 3) #define AT91_PIN_PC4 (0x40 + 4) #define AT91_PIN_PC5 (0x40 + 5) #define AT91_PIN_PC6 (0x40 + 6) #define AT91_PIN_PC7 (0x40 + 7) #define AT91_PIN_PC8 (0x40 + 8) #define AT91_PIN_PC9 (0x40 + 9) #define AT91_PIN_PC10 (0x40 + 10) #define AT91_PIN_PC11 (0x40 + 11) #define AT91_PIN_PC12 (0x40 + 12) #define AT91_PIN_PC13 (0x40 + 13) #define AT91_PIN_PC14 (0x40 + 14) #define AT91_PIN_PC15 (0x40 + 15) #define AT91_PIN_PC16 (0x40 + 16) #define AT91_PIN_PC17 (0x40 + 17) #define AT91_PIN_PC18 (0x40 + 18) #define AT91_PIN_PC19 (0x40 + 19) #define AT91_PIN_PC20 (0x40 + 20) #define AT91_PIN_PC21 (0x40 + 21) #define AT91_PIN_PC22 (0x40 + 22) #define AT91_PIN_PC23 (0x40 + 23) #define AT91_PIN_PC24 (0x40 + 24) #define AT91_PIN_PC25 (0x40 + 25) #define AT91_PIN_PC26 (0x40 + 26) #define AT91_PIN_PC27 (0x40 + 27) #define AT91_PIN_PC28 (0x40 + 28) #define AT91_PIN_PC29 (0x40 + 29) #define AT91_PIN_PC30 (0x40 + 30) #define AT91_PIN_PC31 (0x40 + 31) #define AT91_PIN_PD0 (0x60 + 0) #define AT91_PIN_PD1 (0x60 + 1) #define AT91_PIN_PD2 (0x60 + 2) #define AT91_PIN_PD3 (0x60 + 3) #define AT91_PIN_PD4 (0x60 + 4) #define AT91_PIN_PD5 (0x60 + 5) #define AT91_PIN_PD6 (0x60 + 6) #define AT91_PIN_PD7 (0x60 + 7) #define AT91_PIN_PD8 (0x60 + 8) #define AT91_PIN_PD9 (0x60 + 9) #define AT91_PIN_PD10 (0x60 + 10) #define AT91_PIN_PD11 (0x60 + 11) #define AT91_PIN_PD12 (0x60 + 12) #define AT91_PIN_PD13 (0x60 + 13) #define AT91_PIN_PD14 (0x60 + 14) #define AT91_PIN_PD15 (0x60 + 15) #define AT91_PIN_PD16 (0x60 + 16) #define AT91_PIN_PD17 (0x60 + 17) #define AT91_PIN_PD18 (0x60 + 18) #define AT91_PIN_PD19 (0x60 + 19) #define AT91_PIN_PD20 (0x60 + 20) #define AT91_PIN_PD21 (0x60 + 21) #define AT91_PIN_PD22 (0x60 + 22) #define AT91_PIN_PD23 (0x60 + 23) #define AT91_PIN_PD24 (0x60 + 24) #define AT91_PIN_PD25 (0x60 + 25) #define AT91_PIN_PD26 (0x60 + 26) #define AT91_PIN_PD27 (0x60 + 27) #define AT91_PIN_PD28 (0x60 + 28) #define AT91_PIN_PD29 (0x60 + 29) #define AT91_PIN_PD30 (0x60 + 30) #define AT91_PIN_PD31 (0x60 + 31) #define AT91_PIN_PE0 (0x80 + 0) #define AT91_PIN_PE1 (0x80 + 1) #define AT91_PIN_PE2 (0x80 + 2) #define AT91_PIN_PE3 (0x80 + 3) #define AT91_PIN_PE4 (0x80 + 4) #define AT91_PIN_PE5 (0x80 + 5) #define AT91_PIN_PE6 (0x80 + 6) #define AT91_PIN_PE7 (0x80 + 7) #define AT91_PIN_PE8 (0x80 + 8) #define AT91_PIN_PE9 (0x80 + 9) #define AT91_PIN_PE10 (0x80 + 10) #define AT91_PIN_PE11 (0x80 + 11) #define AT91_PIN_PE12 (0x80 + 12) #define AT91_PIN_PE13 (0x80 + 13) #define AT91_PIN_PE14 (0x80 + 14) #define AT91_PIN_PE15 (0x80 + 15) #define AT91_PIN_PE16 (0x80 + 16) #define AT91_PIN_PE17 (0x80 + 17) #define AT91_PIN_PE18 (0x80 + 18) #define AT91_PIN_PE19 (0x80 + 19) #define AT91_PIN_PE20 (0x80 + 20) #define AT91_PIN_PE21 (0x80 + 21) #define AT91_PIN_PE22 (0x80 + 22) #define AT91_PIN_PE23 (0x80 + 23) #define AT91_PIN_PE24 (0x80 + 24) #define AT91_PIN_PE25 (0x80 + 25) #define AT91_PIN_PE26 (0x80 + 26) #define AT91_PIN_PE27 (0x80 + 27) #define AT91_PIN_PE28 (0x80 + 28) #define AT91_PIN_PE29 (0x80 + 29) #define AT91_PIN_PE30 (0x80 + 30) #define AT91_PIN_PE31 (0x80 + 31) #ifndef __ASSEMBLY__ /* setup setup routines, called from board init or driver probe() */ extern int __init_or_module at91_set_GPIO_periph(unsigned pin, int use_pullup); extern int __init_or_module at91_set_A_periph(unsigned pin, int use_pullup); extern int __init_or_module at91_set_B_periph(unsigned pin, int use_pullup); extern int __init_or_module at91_set_C_periph(unsigned pin, int use_pullup); extern int __init_or_module at91_set_D_periph(unsigned pin, int use_pullup); extern int __init_or_module at91_set_gpio_input(unsigned pin, int use_pullup); extern int __init_or_module at91_set_gpio_output(unsigned pin, int value); extern int __init_or_module at91_set_deglitch(unsigned pin, int is_on); extern int __init_or_module at91_set_debounce(unsigned pin, int is_on, int div); extern int __init_or_module at91_set_multi_drive(unsigned pin, int is_on); extern int __init_or_module at91_set_pulldown(unsigned pin, int is_on); extern int __init_or_module at91_disable_schmitt_trig(unsigned pin); /* callable at any time */ extern int at91_set_gpio_value(unsigned pin, int value); extern int at91_get_gpio_value(unsigned pin); /* callable only from core power-management code */ extern void at91_gpio_suspend(void); extern void at91_gpio_resume(void); #ifdef CONFIG_PINCTRL_AT91 void at91_pinctrl_gpio_suspend(void); void at91_pinctrl_gpio_resume(void); #else static inline void at91_pinctrl_gpio_suspend(void) {} static inline void at91_pinctrl_gpio_resume(void) {} #endif #endif /* __ASSEMBLY__ */ #endif
ubuntu-chu/linux3.6.9-at91
arch/arm/mach-at91/include/mach/gpio.h
C
gpl-2.0
7,473
/* * #%L * OME SCIFIO package for reading and converting scientific file formats. * %% * Copyright (C) 2005 - 2012 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package loci.common; import java.io.IOException; /** * A legacy delegator class for ome.scifio.common.IniWriter. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/common/src/loci/common/IniWriter.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/common/src/loci/common/IniWriter.java;hb=HEAD">Gitweb</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class IniWriter { // -- Fields -- private ome.scifio.common.IniWriter writer; // -- Constructor -- public IniWriter() { writer = new ome.scifio.common.IniWriter(); } // -- IniWriter API methods -- /** * Saves the given IniList to the given file. * If the given file already exists, then the IniList will be appended. */ public void saveINI(IniList ini, String path) throws IOException { writer.saveINI(ini.list, path); } /** Saves the given IniList to the given file. */ public void saveINI(IniList ini, String path, boolean append) throws IOException { writer.saveINI(ini.list, path, append); } // -- Object delegators -- @Override public boolean equals(Object obj) { return writer.equals(obj); } @Override public int hashCode() { return writer.hashCode(); } @Override public String toString() { return writer.toString(); } }
ximenesuk/bioformats
components/loci-legacy/src/loci/common/IniWriter.java
Java
gpl-2.0
3,258
var mysql_wn_data_noun_quantity = { "morsel":[["noun.quantity"],["morsel","small indefinite quantity"]], "section":[["noun.quantity","noun.group","noun.location","verb.contact:section","noun.group"],["section","square mile","section2","team","platoon1","section1","area1","section4","discussion section","class3"]], "mate":[["noun.quantity","noun.person","noun.person","adj.all:friendly1^matey","noun.location:Australia","noun.location:Britain","noun.person","verb.contact:mate","noun.Tops:animal"],["mate","fellow","singleton","couple","mate2","first mate","officer4","mate3","friend","mate1"]], "exposure":[["noun.quantity","verb.perception:expose1"],["exposure","light unit"]], "parking":[["noun.quantity","verb.contact:park"],["parking","room"]], "shtik":[["noun.quantity","noun.communication:Yiddish"],["shtik","shtick","schtik","schtick","small indefinite quantity"]], "basket":[["noun.quantity","noun.artifact","noun.person:basketeer"],["basket","basketful","containerful","basket1","basketball hoop","hoop3","goal","basketball equipment"]], "correction":[["noun.quantity","noun.communication"],["correction","fudge factor","indefinite quantity","correction1","editing"]], "footstep":[["noun.quantity","verb.change:pace","verb.motion:pace1","verb.motion:pace","verb.change:step","verb.motion:step3","verb.motion:step1","verb.motion:step","verb.motion:stride3","verb.motion:stride"],["footstep","pace1","step","stride","indefinite quantity"]], "addition":[["noun.quantity","verb.change:increase2","verb.change:increase"],["addition","increase","gain","indefinite quantity"]], "circulation":[["noun.quantity","verb.motion:circulate3","noun.quantity","noun.cognition:library science"],["circulation","count","circulation1","count"]], "breakage":[["noun.quantity"],["breakage","indefinite quantity"]], "craps":[["noun.quantity"],["craps","snake eyes","two"]], "utility":[["noun.quantity","noun.cognition:economics"],["utility","system of measurement"]], "blood count":[["noun.quantity"],["blood count","count"]], "sperm count":[["noun.quantity"],["sperm count","count"]], "eyedrop":[["noun.quantity"],["eyedrop","eye-drop","drop"]], "picking":[["noun.quantity","verb.contact:pick1"],["picking","pick","output"]], "capacity":[["noun.quantity","adj.all:large^capacious","verb.stative:contain13"],["capacity","content","volume"]], "pitcher":[["noun.quantity"],["pitcher","pitcherful","containerful"]], "tankage":[["noun.quantity"],["tankage","indefinite quantity"]], "nip":[["noun.quantity","verb.contact","noun.act:nip1"],["nip","shot","small indefinite quantity","nip2","bite"]], "headroom":[["noun.quantity"],["headroom","headway","clearance","room"]], "population":[["noun.quantity","noun.group","noun.Tops:group"],["population","integer","population1"]], "nit":[["noun.quantity"],["nit","luminance unit"]], "quetzal":[["noun.quantity"],["quetzal","Guatemalan monetary unit"]], "lari":[["noun.quantity"],["lari","Georgian monetary unit"]], "agora":[["noun.quantity"],["agora","shekel","Israeli monetary unit"]], "barn":[["noun.quantity","noun.cognition:atomic physics"],["barn","b","area unit"]], "barrow":[["noun.quantity"],["barrow","barrowful","containerful"]], "basin":[["noun.quantity"],["basin","basinful","containerful"]], "bit":[["noun.quantity","noun.artifact","noun.artifact"],["bit","unit of measurement","byte","bit1","stable gear","bridle","bit2","part","key"]], "carton":[["noun.quantity"],["carton","cartonful","containerful"]], "cordage":[["noun.quantity","noun.Tops:measure"],["cordage"]], "cutoff":[["noun.quantity"],["cutoff","limit"]], "dustpan":[["noun.quantity"],["dustpan","dustpanful","containerful"]], "firkin":[["noun.quantity"],["firkin","British capacity unit","kilderkin"]], "flask":[["noun.quantity"],["flask","flaskful","containerful"]], "frail":[["noun.quantity"],["frail","weight unit"]], "keg":[["noun.quantity"],["keg","kegful","containerful"]], "kettle":[["noun.quantity","noun.artifact","noun.person:tympanist","noun.person:timpanist","noun.person:tympanist","noun.person:timpanist","adj.pert:tympanic1","noun.person:timpanist"],["kettle","kettleful","containerful","kettle1","kettledrum","tympanum","tympani","timpani","percussion instrument"]], "load":[["noun.quantity","noun.artifact","verb.contact","noun.artifact:load","noun.artifact:load2","noun.person:loader","noun.act:loading","noun.artifact:lading","verb.change:fill1","verb.possession","noun.cognition:computer science","verb.contact","noun.artifact:load1","noun.person:loader1","noun.artifact:charge","verb.change:fill1","verb.contact","noun.artifact:load2","noun.artifact:load","noun.person:loader","noun.act:loading"],["load","loading","indefinite quantity","load3","electrical device","load1","lade1","laden1","load up","frames:1","21","load12","transfer1","load2","charge2","load10","put"]], "reservoir":[["noun.quantity","noun.artifact","noun.object:lake"],["reservoir","supply","reservoir1","artificial lake","man-made lake","water system"]], "seventy-eight":[["noun.quantity"],["seventy-eight","78\"","LXXVIII","large integer"]], "sextant":[["noun.quantity","noun.attribute:circumference1"],["sextant","angular unit"]], "singleton":[["noun.quantity"],["singleton","one"]], "skeleton":[["noun.quantity"],["skeleton","minimum"]], "standard":[["noun.quantity","verb.change:standardize","verb.change:standardise"],["standard","volume unit"]], "teacup":[["noun.quantity"],["teacup","teacupful","containerful"]], "thimble":[["noun.quantity"],["thimble","thimbleful","containerful"]], "tub":[["noun.quantity"],["tub","tubful","containerful"]], "twenty-two":[["noun.quantity"],["twenty-two","22\"","XXII","large integer"]], "yard":[["noun.quantity","verb.change:pace","noun.location","noun.artifact","noun.location:field","noun.artifact","noun.location:tract"],["yard","pace","linear unit","fathom1","chain","rod1","lea","yard1","tract","yard2","grounds","curtilage","yard3","railway yard","railyard"]], "yarder":[["noun.quantity","noun.communication:combining form"],["yarder","linear unit"]], "common denominator":[["noun.quantity"],["common denominator","denominator"]], "volume":[["noun.quantity","adj.all:large^voluminous","noun.Tops:quantity","noun.quantity","noun.Tops:quantity"],["volume","volume1"]], "magnetization":[["noun.quantity","verb.communication:magnetize","verb.change:magnetize","noun.Tops:measure"],["magnetization","magnetisation"]], "precipitation":[["noun.quantity","verb.weather:precipitate"],["precipitation","indefinite quantity"]], "degree":[["noun.quantity","noun.state","noun.Tops:state","noun.quantity"],["degree","arcdegree","angular unit","oxtant","sextant","degree1","level","stage","point","degree3","temperature unit"]], "solubility":[["noun.quantity","adj.all:soluble1","noun.substance:solution"],["solubility","definite quantity"]], "lumen":[["noun.quantity"],["lumen","lm","luminous flux unit"]], "headful":[["noun.quantity"],["headful","containerful"]], "palm":[["noun.quantity","verb.contact:palm"],["palm","linear unit"]], "digit":[["noun.quantity","verb.change:digitize","verb.change:digitise","verb.change:digitalize"],["digit","figure","integer"]], "point system":[["noun.quantity"],["point system","system of measurement"]], "constant":[["noun.quantity"],["constant","number"]], "one":[["noun.quantity"],["one","1\"","I","ace","single","unity","digit"]], "region":[["noun.quantity","noun.location","noun.Tops:location"],["region","neighborhood","indefinite quantity","region1"]], "word":[["noun.quantity","noun.communication","verb.communication:word","noun.communication"],["word","kilobyte","computer memory unit","word3","statement","word6","order3"]], "quota":[["noun.quantity"],["quota","number"]], "dollar":[["noun.quantity","noun.possession"],["dollar","monetary unit","dollar1","coin2"]], "e":[["noun.quantity"],["e","transcendental number"]], "gamma":[["noun.quantity"],["gamma","oersted","field strength unit"]], "pi":[["noun.quantity"],["pi","transcendental number"]], "radical":[["noun.quantity","noun.Tops:measure","noun.cognition:mathematics"],["radical"]], "pascal":[["noun.quantity"],["pascal","Pa","pressure unit"]], "guarani":[["noun.quantity"],["guarani","Paraguayan monetary unit"]], "pengo":[["noun.quantity"],["pengo","Hungarian monetary unit"]], "outage":[["noun.quantity"],["outage","indefinite quantity"]], "couple":[["noun.quantity","verb.contact:couple2","verb.contact:pair3","verb.contact:pair4","verb.contact","noun.artifact:coupler","noun.artifact:coupling"],["couple","pair","twosome","twain","brace","span2","yoke","couplet","distich","duo","duet","dyad","duad","two","couple1","uncouple","couple on","couple up","attach1"]], "yuan":[["noun.quantity"],["yuan","kwai","Chinese monetary unit"]], "battalion":[["noun.quantity","adj.all:incalculable^multitudinous"],["battalion","large number","multitude","plurality1","pack","large indefinite quantity"]], "moiety":[["noun.quantity"],["moiety","mediety","one-half"]], "maximum":[["noun.quantity","verb.change:maximize1","verb.change:maximize","verb.change:maximise1","verb.change:maximise"],["maximum","minimum","upper limit","extremum","large indefinite quantity"]], "minimum":[["noun.quantity","verb.communication:minimize1","verb.communication:minimize","verb.change:minimize","verb.communication:minimise1","verb.change:minimise"],["minimum","maximum","lower limit","extremum","small indefinite quantity"]], "cordoba":[["noun.quantity"],["cordoba","Nicaraguan monetary unit"]], "troy":[["noun.quantity"],["troy","troy weight","system of weights"]], "acre":[["noun.quantity","noun.location"],["acre","area unit","Acre1","district","Brazil"]], "sucre":[["noun.quantity"],["sucre","Ecuadoran monetary unit"]], "tanga":[["noun.quantity"],["tanga","Tajikistani monetary unit"]], "lepton":[["noun.quantity"],["lepton","drachma","Greek monetary unit"]], "ocean":[["noun.quantity","adj.all:unlimited^oceanic"],["ocean","sea","large indefinite quantity"]], "para":[["noun.quantity"],["para","Yugoslavian monetary unit","Yugoslavian dinar"]], "swath":[["noun.quantity","noun.shape:space"],["swath"]], "bel":[["noun.quantity"],["Bel","B3","sound unit"]], "denier":[["noun.quantity"],["denier","unit of measurement"]], "miler":[["noun.quantity","noun.quantity:mile6","noun.quantity:mile5","noun.quantity:mile4","noun.quantity:mile3","noun.quantity:mile2","noun.quantity:mile1","noun.event:mile","noun.communication:combining form"],["miler","linear unit"]], "welterweight":[["noun.quantity","noun.person","noun.person"],["welterweight","weight unit","welterweight1","wrestler","welterweight2","boxer"]], "balboa":[["noun.quantity"],["balboa","Panamanian monetary unit"]], "bolivar":[["noun.quantity"],["bolivar","Venezuelan monetary unit"]], "cicero":[["noun.quantity"],["cicero","linear unit"]], "coulomb":[["noun.quantity"],["coulomb","C","ampere-second","charge unit","abcoulomb","ampere-minute"]], "curie":[["noun.quantity","noun.person"],["curie","Ci","radioactivity unit","Curie1","Pierre Curie","physicist"]], "gauss":[["noun.quantity"],["gauss","flux density unit","tesla"]], "gilbert":[["noun.quantity","noun.person","noun.person","noun.person","adj.pert:gilbertian"],["gilbert","Gb1","Gi","magnetomotive force unit","Gilbert1","Humphrey Gilbert","Sir Humphrey Gilbert","navigator","Gilbert2","William Gilbert","physician","physicist","Gilbert3","William Gilbert1","William S. Gilbert","William Schwenk Gilbert","Sir William Gilbert","librettist","poet"]], "gram":[["noun.quantity"],["gram","gramme","gm","g","metric weight unit","dekagram"]], "henry":[["noun.quantity","noun.person","noun.person"],["henry","H","inductance unit","Henry1","Patrick Henry","American Revolutionary leader","orator","Henry2","William Henry","chemist"]], "joule":[["noun.quantity"],["joule","J","watt second","work unit"]], "kelvin":[["noun.quantity"],["kelvin","K5","temperature unit"]], "lambert":[["noun.quantity"],["lambert","L7","illumination unit"]], "langley":[["noun.quantity"],["langley","unit of measurement"]], "maxwell":[["noun.quantity"],["maxwell","Mx","flux unit","weber"]], "newton":[["noun.quantity"],["newton","N1","force unit","sthene"]], "oersted":[["noun.quantity"],["oersted","field strength unit"]], "ohm":[["noun.quantity","adj.pert:ohmic"],["ohm","resistance unit","megohm"]], "rand":[["noun.quantity"],["rand","South African monetary unit"]], "roentgen":[["noun.quantity"],["roentgen","R","radioactivity unit"]], "rutherford":[["noun.quantity","noun.person"],["rutherford","radioactivity unit","Rutherford1","Daniel Rutherford","chemist"]], "sabin":[["noun.quantity"],["sabin","absorption unit"]], "tesla":[["noun.quantity"],["tesla","flux density unit"]], "watt":[["noun.quantity"],["watt","W","power unit","kilowatt","horsepower"]], "weber":[["noun.quantity","noun.person","noun.person","noun.person","noun.person"],["weber","Wb","flux unit","Weber1","Carl Maria von Weber","Baron Karl Maria Friedrich Ernst von Weber","conductor","composer","Weber2","Max Weber","sociologist","Weber3","Max Weber1","painter","Weber4","Wilhelm Eduard Weber","physicist"]], "scattering":[["noun.quantity","verb.contact:sprinkle1"],["scattering","sprinkling","small indefinite quantity"]], "accretion":[["noun.quantity","adj.all:increasing^accretionary","noun.process","adj.all:increasing^accretionary","noun.cognition:geology","noun.process","adj.all:increasing^accretionary","verb.change:accrete1","noun.cognition:biology","noun.process","adj.all:increasing^accretionary","noun.cognition:astronomy"],["accretion","addition","accretion1","increase","accretion2","increase","accretion3","increase"]], "dividend":[["noun.quantity"],["dividend","number"]], "linage":[["noun.quantity"],["linage","lineage","number"]], "penny":[["noun.quantity"],["penny","fractional monetary unit","Irish pound","British pound"]], "double eagle":[["noun.quantity","noun.act:golf"],["double eagle","score"]], "spoilage":[["noun.quantity"],["spoilage","indefinite quantity"]], "fundamental quantity":[["noun.quantity","noun.Tops:measure"],["fundamental quantity","fundamental measure"]], "definite quantity":[["noun.quantity","noun.Tops:measure"],["definite quantity"]], "indefinite quantity":[["noun.quantity","noun.Tops:measure"],["indefinite quantity"]], "relative quantity":[["noun.quantity","noun.Tops:measure"],["relative quantity"]], "system of measurement":[["noun.quantity","noun.Tops:measure"],["system of measurement","metric"]], "system of weights and measures":[["noun.quantity"],["system of weights and measures","system of measurement"]], "british imperial system":[["noun.quantity"],["British Imperial System","English system","British system","system of weights and measures"]], "metric system":[["noun.quantity"],["metric system","system of weights and measures"]], "cgs":[["noun.quantity"],["cgs","cgs system","metric system"]], "systeme international d'unites":[["noun.quantity"],["Systeme International d'Unites","Systeme International","SI system","SI","SI unit","International System of Units","International System","metric system"]], "united states customary system":[["noun.quantity"],["United States Customary System","system of weights and measures"]], "information measure":[["noun.quantity"],["information measure","system of measurement"]], "bandwidth":[["noun.quantity"],["bandwidth","information measure"]], "baud":[["noun.quantity","noun.cognition:computer science"],["baud","baud rate","information measure"]], "octane number":[["noun.quantity","noun.Tops:measure"],["octane number","octane rating"]], "marginal utility":[["noun.quantity","noun.cognition:economics"],["marginal utility","utility"]], "enough":[["noun.quantity","adj.all:sufficient^enough","adj.all:sufficient","verb.stative:suffice"],["enough","sufficiency","relative quantity"]], "absolute value":[["noun.quantity"],["absolute value","numerical value","definite quantity"]], "acid value":[["noun.quantity","noun.cognition:chemistry"],["acid value","definite quantity"]], "chlorinity":[["noun.quantity"],["chlorinity","definite quantity"]], "quire":[["noun.quantity"],["quire","definite quantity","ream"]], "toxicity":[["noun.quantity","adj.all:toxic"],["toxicity","definite quantity"]], "cytotoxicity":[["noun.quantity"],["cytotoxicity","toxicity"]], "unit of measurement":[["noun.quantity","verb.social:unitize","verb.change:unitize"],["unit of measurement","unit","definite quantity"]], "measuring unit":[["noun.quantity"],["measuring unit","measuring block","unit of measurement"]], "diopter":[["noun.quantity"],["diopter","dioptre","unit of measurement"]], "karat":[["noun.quantity"],["karat","carat2","kt","unit of measurement"]], "decimal":[["noun.quantity","verb.change:decimalize","verb.change:decimalise"],["decimal1","number"]], "avogadro's number":[["noun.quantity"],["Avogadro's number","Avogadro number","constant"]], "boltzmann's constant":[["noun.quantity"],["Boltzmann's constant","constant"]], "coefficient":[["noun.quantity"],["coefficient","constant"]], "absorption coefficient":[["noun.quantity"],["absorption coefficient","coefficient of absorption","absorptance","coefficient"]], "drag coefficient":[["noun.quantity"],["drag coefficient","coefficient of drag","coefficient"]], "coefficient of friction":[["noun.quantity"],["coefficient of friction","coefficient"]], "coefficient of mutual induction":[["noun.quantity"],["coefficient of mutual induction","mutual inductance","coefficient"]], "coefficient of self induction":[["noun.quantity"],["coefficient of self induction","self-inductance","coefficient"]], "modulus":[["noun.quantity","noun.cognition:physics","noun.quantity","noun.quantity"],["modulus","coefficient","modulus1","absolute value","modulus2","integer"]], "coefficient of elasticity":[["noun.quantity","noun.cognition:physics"],["coefficient of elasticity","modulus of elasticity","elastic modulus","modulus"]], "bulk modulus":[["noun.quantity"],["bulk modulus","coefficient of elasticity"]], "modulus of rigidity":[["noun.quantity"],["modulus of rigidity","coefficient of elasticity"]], "young's modulus":[["noun.quantity"],["Young's modulus","coefficient of elasticity"]], "coefficient of expansion":[["noun.quantity"],["coefficient of expansion","expansivity","coefficient"]], "coefficient of reflection":[["noun.quantity"],["coefficient of reflection","reflection factor","reflectance","reflectivity","coefficient"]], "transmittance":[["noun.quantity"],["transmittance","transmission","coefficient"]], "coefficient of viscosity":[["noun.quantity"],["coefficient of viscosity","absolute viscosity","dynamic viscosity","coefficient"]], "cosmological constant":[["noun.quantity"],["cosmological constant","constant"]], "equilibrium constant":[["noun.quantity","noun.cognition:chemistry"],["equilibrium constant","constant"]], "dissociation constant":[["noun.quantity"],["dissociation constant","equilibrium constant"]], "gas constant":[["noun.quantity","noun.cognition:physics"],["gas constant","universal gas constant","R1","constant"]], "gravitational constant":[["noun.quantity","noun.cognition:law of gravitation","noun.cognition:physics"],["gravitational constant","universal gravitational constant","constant of gravitation","G8","constant"]], "hubble's constant":[["noun.quantity","noun.cognition:cosmology"],["Hubble's constant","Hubble constant","Hubble's parameter","Hubble parameter","constant"]], "ionic charge":[["noun.quantity"],["ionic charge","constant"]], "planck's constant":[["noun.quantity"],["Planck's constant","h1","factor of proportionality"]], "oxidation number":[["noun.quantity"],["oxidation number","oxidation state","number"]], "cardinality":[["noun.quantity","noun.cognition:mathematics"],["cardinality","number"]], "body count":[["noun.quantity"],["body count","count"]], "head count":[["noun.quantity"],["head count","headcount","count"]], "pollen count":[["noun.quantity"],["pollen count","count"]], "conversion factor":[["noun.quantity"],["conversion factor","factor1"]], "factor of proportionality":[["noun.quantity"],["factor of proportionality","constant of proportionality","factor1","constant"]], "fibonacci number":[["noun.quantity"],["Fibonacci number","number"]], "prime factor":[["noun.quantity"],["prime factor","divisor1"]], "prime number":[["noun.quantity"],["prime number","prime"]], "composite number":[["noun.quantity"],["composite number","number"]], "double-bogey":[["noun.quantity","verb.contact:double bogey","noun.act:golf"],["double-bogey","score"]], "compound number":[["noun.quantity"],["compound number","number"]], "ordinal number":[["noun.quantity","adj.all:ordinal"],["ordinal number","ordinal","no.","number"]], "cardinal number":[["noun.quantity"],["cardinal number","cardinal","number"]], "floating-point number":[["noun.quantity"],["floating-point number","number"]], "fixed-point number":[["noun.quantity"],["fixed-point number","number"]], "googol":[["noun.quantity"],["googol","cardinal number"]], "googolplex":[["noun.quantity"],["googolplex","cardinal number"]], "atomic number":[["noun.quantity"],["atomic number","number"]], "magic number":[["noun.quantity"],["magic number","atomic number"]], "baryon number":[["noun.quantity"],["baryon number","number"]], "long measure":[["noun.quantity"],["long measure","linear unit"]], "magnetic flux":[["noun.quantity"],["magnetic flux","magnetization"]], "absorption unit":[["noun.quantity"],["absorption unit","unit of measurement"]], "acceleration unit":[["noun.quantity"],["acceleration unit","unit of measurement"]], "angular unit":[["noun.quantity"],["angular unit","unit of measurement"]], "area unit":[["noun.quantity"],["area unit","square measure","unit of measurement"]], "volume unit":[["noun.quantity"],["volume unit","capacity unit","capacity measure","cubage unit","cubic measure","cubic content unit","displacement unit","cubature unit","unit of measurement","volume"]], "cubic inch":[["noun.quantity"],["cubic inch","cu in","volume unit"]], "cubic foot":[["noun.quantity"],["cubic foot","cu ft","volume unit"]], "computer memory unit":[["noun.quantity"],["computer memory unit","unit of measurement"]], "electromagnetic unit":[["noun.quantity"],["electromagnetic unit","emu","unit of measurement"]], "explosive unit":[["noun.quantity"],["explosive unit","unit of measurement"]], "force unit":[["noun.quantity"],["force unit","unit of measurement"]], "linear unit":[["noun.quantity"],["linear unit","linear measure","unit of measurement"]], "metric unit":[["noun.quantity"],["metric unit","metric1","unit of measurement"]], "miles per gallon":[["noun.quantity"],["miles per gallon","unit of measurement"]], "monetary unit":[["noun.quantity"],["monetary unit","unit of measurement"]], "megaflop":[["noun.quantity","noun.cognition:computer science"],["megaflop","MFLOP","million floating point operations per second","unit of measurement","teraflop"]], "teraflop":[["noun.quantity","noun.cognition:computer science"],["teraflop","trillion floating point operations per second","unit of measurement"]], "mips":[["noun.quantity","noun.cognition:computer science"],["MIPS","million instructions per second","unit of measurement"]], "pain unit":[["noun.quantity"],["pain unit","unit of measurement"]], "pressure unit":[["noun.quantity"],["pressure unit","unit of measurement"]], "printing unit":[["noun.quantity"],["printing unit","unit of measurement"]], "sound unit":[["noun.quantity"],["sound unit","unit of measurement"]], "telephone unit":[["noun.quantity"],["telephone unit","unit of measurement"]], "temperature unit":[["noun.quantity"],["temperature unit","unit of measurement"]], "weight unit":[["noun.quantity"],["weight unit","weight","unit of measurement"]], "mass unit":[["noun.quantity"],["mass unit","unit of measurement"]], "unit of viscosity":[["noun.quantity"],["unit of viscosity","unit of measurement"]], "work unit":[["noun.quantity"],["work unit","heat unit","energy unit","unit of measurement"]], "brinell number":[["noun.quantity"],["Brinell number","unit of measurement"]], "brix scale":[["noun.quantity"],["Brix scale","system of measurement"]], "set point":[["noun.quantity","noun.act:tennis"],["set point","point1"]], "match point":[["noun.quantity","noun.act:tennis"],["match point","point1"]], "circular measure":[["noun.quantity"],["circular measure","system of measurement"]], "mil":[["noun.quantity","noun.quantity","noun.quantity"],["mil3","angular unit","mil1","linear unit","inch","mil4","Cypriot pound","Cypriot monetary unit"]], "microradian":[["noun.quantity"],["microradian","angular unit","milliradian"]], "milliradian":[["noun.quantity"],["milliradian","angular unit","radian"]], "radian":[["noun.quantity"],["radian","rad1","angular unit"]], "grad":[["noun.quantity","noun.shape:right angle"],["grad","grade","angular unit"]], "oxtant":[["noun.quantity"],["oxtant","angular unit"]], "straight angle":[["noun.quantity","noun.attribute:circumference1"],["straight angle","angular unit"]], "steradian":[["noun.quantity","noun.shape:sphere1"],["steradian","sr","angular unit"]], "square inch":[["noun.quantity"],["square inch","sq in","area unit"]], "square foot":[["noun.quantity"],["square foot","sq ft","area unit"]], "square yard":[["noun.quantity"],["square yard","sq yd","area unit"]], "square meter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["square meter","square metre","centare","area unit"]], "square mile":[["noun.quantity"],["square mile","area unit"]], "quarter section":[["noun.quantity"],["quarter section","area unit"]], "are":[["noun.quantity"],["are","ar","area unit","hectare"]], "hectare":[["noun.quantity"],["hectare","area unit"]], "arpent":[["noun.quantity"],["arpent","area unit"]], "dessiatine":[["noun.quantity"],["dessiatine","area unit"]], "morgen":[["noun.quantity"],["morgen","area unit"]], "liquid unit":[["noun.quantity"],["liquid unit","liquid measure","capacity unit"]], "dry unit":[["noun.quantity"],["dry unit","dry measure","capacity unit"]], "united states liquid unit":[["noun.quantity"],["United States liquid unit","liquid unit"]], "british capacity unit":[["noun.quantity"],["British capacity unit","Imperial capacity unit","liquid unit","dry unit"]], "metric capacity unit":[["noun.quantity"],["metric capacity unit","capacity unit","metric unit"]], "ardeb":[["noun.quantity"],["ardeb","dry unit"]], "arroba":[["noun.quantity","noun.quantity"],["arroba2","liquid unit","arroba1","weight unit"]], "cran":[["noun.quantity"],["cran","capacity unit"]], "ephah":[["noun.quantity"],["ephah","epha","dry unit","homer"]], "field capacity":[["noun.quantity"],["field capacity","capacity unit"]], "hin":[["noun.quantity"],["hin","capacity unit"]], "acre-foot":[["noun.quantity"],["acre-foot","volume unit"]], "acre inch":[["noun.quantity"],["acre inch","volume unit"]], "board measure":[["noun.quantity"],["board measure","system of measurement"]], "board foot":[["noun.quantity"],["board foot","volume unit"]], "cubic yard":[["noun.quantity"],["cubic yard","yard1","volume unit"]], "mutchkin":[["noun.quantity"],["mutchkin","liquid unit"]], "oka":[["noun.quantity","noun.quantity"],["oka2","liquid unit","oka1","weight unit"]], "minim":[["noun.quantity","noun.quantity"],["minim1","United States liquid unit","fluidram1","minim2","British capacity unit","fluidram2"]], "fluidram":[["noun.quantity","noun.quantity"],["fluidram1","fluid dram1","fluid drachm1","drachm1","United States liquid unit","fluidounce1","fluidram2","fluid dram2","fluid drachm2","drachm2","British capacity unit","fluidounce2"]], "fluidounce":[["noun.quantity","noun.quantity"],["fluidounce1","fluid ounce1","United States liquid unit","gill1","fluidounce2","fluid ounce2","British capacity unit","gill2"]], "pint":[["noun.quantity","noun.quantity","noun.quantity"],["pint1","United States liquid unit","quart1","pint3","dry pint","United States dry unit","quart3","pint2","British capacity unit","quart2"]], "quart":[["noun.quantity","noun.quantity","noun.quantity"],["quart1","United States liquid unit","gallon1","quart3","dry quart","United States dry unit","peck1","quart2","British capacity unit","gallon2"]], "gallon":[["noun.quantity","noun.quantity"],["gallon1","gal","United States liquid unit","barrel1","gallon2","Imperial gallon","congius","British capacity unit","bushel1","barrel1","firkin"]], "united states dry unit":[["noun.quantity"],["United States dry unit","dry unit"]], "bushel":[["noun.quantity","noun.quantity"],["bushel2","United States dry unit","bushel1","British capacity unit","quarter4"]], "kilderkin":[["noun.quantity"],["kilderkin","British capacity unit"]], "chaldron":[["noun.quantity"],["chaldron","British capacity unit"]], "cubic millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic millimeter","cubic millimetre","metric capacity unit","milliliter"]], "milliliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["milliliter","millilitre","mil2","ml","cubic centimeter","cubic centimetre","cc","metric capacity unit","centiliter"]], "centiliter":[["noun.quantity"],["centiliter","centilitre","cl","metric capacity unit","deciliter"]], "deciliter":[["noun.quantity"],["deciliter","decilitre","dl","metric capacity unit","liter"]], "liter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["liter","litre","l","cubic decimeter","cubic decimetre","metric capacity unit","dekaliter"]], "dekaliter":[["noun.quantity"],["dekaliter","dekalitre","decaliter","decalitre","dal","dkl","metric capacity unit","hectoliter"]], "hectoliter":[["noun.quantity"],["hectoliter","hectolitre","hl","metric capacity unit","kiloliter"]], "kiloliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kiloliter","kilolitre","cubic meter","cubic metre","metric capacity unit","cubic kilometer"]], "cubic kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic kilometer","cubic kilometre","metric capacity unit"]], "parity bit":[["noun.quantity","noun.cognition:computer science"],["parity bit","parity","check bit","bit"]], "nybble":[["noun.quantity","verb.consumption:nibble1","verb.contact:nibble"],["nybble","nibble","byte","computer memory unit"]], "byte":[["noun.quantity"],["byte","computer memory unit","word"]], "bad block":[["noun.quantity","noun.cognition:computer science"],["bad block","block"]], "allocation unit":[["noun.quantity"],["allocation unit","computer memory unit"]], "kilobyte":[["noun.quantity","noun.quantity"],["kilobyte","kibibyte","K","KB","kB1","KiB","mebibyte","computer memory unit","kilobyte1","K1","KB2","kB3","megabyte1","computer memory unit"]], "kilobit":[["noun.quantity"],["kilobit","kbit","kb4","megabit","computer memory unit"]], "kibibit":[["noun.quantity"],["kibibit","kibit","mebibit","computer memory unit"]], "megabyte":[["noun.quantity","noun.quantity"],["megabyte","mebibyte","M2","MB","MiB","gibibyte","computer memory unit","megabyte1","M3","MB1","gigabyte1","computer memory unit"]], "megabit":[["noun.quantity"],["megabit","Mbit","Mb2","gigabit","computer memory unit"]], "mebibit":[["noun.quantity"],["mebibit","Mibit","gibibit","computer memory unit"]], "gigabyte":[["noun.quantity","noun.quantity"],["gigabyte","gibibyte","G2","GB2","GiB","tebibyte","computer memory unit","gigabyte1","G3","GB3","terabyte1","computer memory unit"]], "gigabit":[["noun.quantity"],["gigabit","Gbit","Gb4","terabit","computer memory unit"]], "gibibit":[["noun.quantity"],["gibibit","Gibit","tebibit","computer memory unit"]], "terabyte":[["noun.quantity","noun.quantity"],["terabyte","tebibyte","TB","TiB","pebibyte","computer memory unit","terabyte1","TB1","petabyte1","computer memory unit"]], "terabit":[["noun.quantity"],["terabit","Tbit","Tb2","petabit","computer memory unit"]], "tebibit":[["noun.quantity"],["tebibit","Tibit","pebibit","computer memory unit"]], "petabyte":[["noun.quantity","noun.quantity"],["petabyte","pebibyte","PB","PiB","exbibyte","computer memory unit","petabyte1","PB1","exabyte1","computer memory unit"]], "petabit":[["noun.quantity"],["petabit","Pbit","Pb2","exabit","computer memory unit"]], "pebibit":[["noun.quantity"],["pebibit","Pibit","exbibit","computer memory unit"]], "exabyte":[["noun.quantity","noun.quantity"],["exabyte","exbibyte","EB","EiB","zebibyte","computer memory unit","exabyte1","EB1","zettabyte1","computer memory unit"]], "exabit":[["noun.quantity"],["exabit","Ebit","Eb2","zettabit","computer memory unit"]], "exbibit":[["noun.quantity"],["exbibit","Eibit","zebibit","computer memory unit"]], "zettabyte":[["noun.quantity","noun.quantity"],["zettabyte","zebibyte","ZB","ZiB","yobibyte","computer memory unit","zettabyte1","ZB1","yottabyte1","computer memory unit"]], "zettabit":[["noun.quantity"],["zettabit","Zbit","Zb2","yottabit","computer memory unit"]], "zebibit":[["noun.quantity"],["zebibit","Zibit","yobibit","computer memory unit"]], "yottabyte":[["noun.quantity","noun.quantity"],["yottabyte","yobibyte","YB","YiB","computer memory unit","yottabyte1","YB1","computer memory unit"]], "yottabit":[["noun.quantity"],["yottabit","Ybit","Yb2","computer memory unit"]], "yobibit":[["noun.quantity"],["yobibit","Yibit","computer memory unit"]], "capacitance unit":[["noun.quantity"],["capacitance unit","electromagnetic unit"]], "charge unit":[["noun.quantity"],["charge unit","quantity unit","electromagnetic unit"]], "conductance unit":[["noun.quantity"],["conductance unit","electromagnetic unit"]], "current unit":[["noun.quantity"],["current unit","electromagnetic unit"]], "elastance unit":[["noun.quantity"],["elastance unit","electromagnetic unit"]], "field strength unit":[["noun.quantity"],["field strength unit","electromagnetic unit"]], "flux density unit":[["noun.quantity"],["flux density unit","electromagnetic unit"]], "flux unit":[["noun.quantity"],["flux unit","magnetic flux unit","magnetic flux"]], "inductance unit":[["noun.quantity"],["inductance unit","electromagnetic unit"]], "light unit":[["noun.quantity"],["light unit","electromagnetic unit"]], "magnetomotive force unit":[["noun.quantity"],["magnetomotive force unit","electromagnetic unit"]], "potential unit":[["noun.quantity"],["potential unit","electromagnetic unit"]], "power unit":[["noun.quantity"],["power unit","electromagnetic unit"]], "radioactivity unit":[["noun.quantity"],["radioactivity unit","electromagnetic unit"]], "resistance unit":[["noun.quantity"],["resistance unit","electromagnetic unit"]], "electrostatic unit":[["noun.quantity"],["electrostatic unit","unit of measurement"]], "picofarad":[["noun.quantity"],["picofarad","capacitance unit","microfarad"]], "microfarad":[["noun.quantity"],["microfarad","capacitance unit","millifarad"]], "millifarad":[["noun.quantity"],["millifarad","capacitance unit","farad"]], "farad":[["noun.quantity"],["farad","F","capacitance unit","abfarad"]], "abfarad":[["noun.quantity"],["abfarad","capacitance unit"]], "abcoulomb":[["noun.quantity"],["abcoulomb","charge unit"]], "ampere-minute":[["noun.quantity"],["ampere-minute","charge unit","ampere-hour"]], "ampere-hour":[["noun.quantity"],["ampere-hour","charge unit"]], "mho":[["noun.quantity"],["mho","siemens","reciprocal ohm","S","conductance unit"]], "ampere":[["noun.quantity","noun.quantity"],["ampere","amp","A","current unit","abampere","ampere2","international ampere","current unit"]], "milliampere":[["noun.quantity"],["milliampere","mA","current unit","ampere"]], "abampere":[["noun.quantity"],["abampere","abamp","current unit"]], "daraf":[["noun.quantity"],["daraf","elastance unit"]], "microgauss":[["noun.quantity"],["microgauss","flux density unit","gauss"]], "abhenry":[["noun.quantity"],["abhenry","inductance unit","henry"]], "millihenry":[["noun.quantity"],["millihenry","inductance unit","henry"]], "illumination unit":[["noun.quantity"],["illumination unit","light unit"]], "luminance unit":[["noun.quantity"],["luminance unit","light unit"]], "luminous flux unit":[["noun.quantity"],["luminous flux unit","light unit"]], "luminous intensity unit":[["noun.quantity"],["luminous intensity unit","candlepower unit","light unit"]], "footcandle":[["noun.quantity"],["footcandle","illumination unit"]], "lux":[["noun.quantity"],["lux","lx1","illumination unit","phot"]], "phot":[["noun.quantity"],["phot","illumination unit"]], "foot-lambert":[["noun.quantity"],["foot-lambert","ft-L","luminance unit"]], "international candle":[["noun.quantity"],["international candle","luminous intensity unit"]], "ampere-turn":[["noun.quantity"],["ampere-turn","magnetomotive force unit"]], "magneton":[["noun.quantity"],["magneton","magnetomotive force unit"]], "abvolt":[["noun.quantity"],["abvolt","potential unit","volt"]], "millivolt":[["noun.quantity"],["millivolt","mV","potential unit","volt"]], "microvolt":[["noun.quantity"],["microvolt","potential unit","volt"]], "nanovolt":[["noun.quantity"],["nanovolt","potential unit","volt"]], "picovolt":[["noun.quantity"],["picovolt","potential unit","volt"]], "femtovolt":[["noun.quantity"],["femtovolt","potential unit","volt"]], "volt":[["noun.quantity","adj.pert:voltaic"],["volt","V","potential unit","kilovolt"]], "kilovolt":[["noun.quantity"],["kilovolt","kV","potential unit"]], "rydberg":[["noun.quantity"],["rydberg","rydberg constant","rydberg unit","wave number"]], "wave number":[["noun.quantity","noun.time:frequency"],["wave number"]], "abwatt":[["noun.quantity"],["abwatt","power unit","milliwatt"]], "milliwatt":[["noun.quantity"],["milliwatt","power unit","watt"]], "kilowatt":[["noun.quantity"],["kilowatt","kW","power unit","megawatt"]], "megawatt":[["noun.quantity"],["megawatt","power unit"]], "horsepower":[["noun.quantity","H.P."],["horsepower","HP","power unit"]], "volt-ampere":[["noun.quantity"],["volt-ampere","var","power unit","kilovolt-ampere"]], "kilovolt-ampere":[["noun.quantity"],["kilovolt-ampere","power unit"]], "millicurie":[["noun.quantity"],["millicurie","radioactivity unit","curie"]], "rem":[["noun.quantity"],["rem","radioactivity unit"]], "mrem":[["noun.quantity"],["mrem","millirem","radioactivity unit"]], "rad":[["noun.quantity"],["rad","radioactivity unit"]], "abohm":[["noun.quantity"],["abohm","resistance unit","ohm"]], "megohm":[["noun.quantity"],["megohm","resistance unit"]], "kiloton":[["noun.quantity"],["kiloton","avoirdupois unit","megaton"]], "megaton":[["noun.quantity"],["megaton","avoirdupois unit"]], "dyne":[["noun.quantity"],["dyne","force unit","newton"]], "sthene":[["noun.quantity"],["sthene","force unit"]], "poundal":[["noun.quantity"],["poundal","pdl","force unit"]], "pounder":[["noun.quantity","noun.communication:combining form"],["pounder","force unit"]], "astronomy unit":[["noun.quantity"],["astronomy unit","linear unit"]], "metric linear unit":[["noun.quantity"],["metric linear unit","linear unit","metric unit"]], "nautical linear unit":[["noun.quantity"],["nautical linear unit","linear unit"]], "inch":[["noun.quantity","verb.motion:inch","noun.location:US","noun.location:Britain"],["inch","in","linear unit","foot"]], "footer":[["noun.quantity","noun.communication:combining form"],["footer","linear unit"]], "furlong":[["noun.quantity"],["furlong","linear unit","mile1"]], "half mile":[["noun.quantity"],["half mile","880 yards","linear unit","mile1"]], "quarter mile":[["noun.quantity"],["quarter mile","440 yards","linear unit","mile1"]], "ligne":[["noun.quantity"],["ligne","linear unit","inch"]], "archine":[["noun.quantity"],["archine","linear unit"]], "kos":[["noun.quantity"],["kos","coss","linear unit"]], "vara":[["noun.quantity"],["vara","linear unit"]], "verst":[["noun.quantity"],["verst","linear unit"]], "gunter's chain":[["noun.quantity"],["Gunter's chain","chain","furlong"]], "engineer's chain":[["noun.quantity"],["engineer's chain","chain"]], "cubit":[["noun.quantity"],["cubit","linear unit"]], "fistmele":[["noun.quantity"],["fistmele","linear unit"]], "body length":[["noun.quantity"],["body length","linear unit"]], "extremum":[["noun.quantity","adj.all:high3^peaky","verb.motion:peak"],["extremum","peak","limit"]], "handbreadth":[["noun.quantity"],["handbreadth","handsbreadth","linear unit"]], "lea":[["noun.quantity"],["lea","linear unit"]], "li":[["noun.quantity"],["li","linear unit"]], "roman pace":[["noun.quantity"],["Roman pace","linear unit"]], "geometric pace":[["noun.quantity"],["geometric pace","linear unit"]], "military pace":[["noun.quantity"],["military pace","linear unit"]], "survey mile":[["noun.quantity"],["survey mile","linear unit"]], "light year":[["noun.quantity"],["light year","light-year","astronomy unit"]], "light hour":[["noun.quantity"],["light hour","astronomy unit","light year"]], "light minute":[["noun.quantity"],["light minute","astronomy unit","light year"]], "light second":[["noun.quantity"],["light second","astronomy unit","light year"]], "astronomical unit":[["noun.quantity"],["Astronomical Unit","AU","astronomy unit"]], "parsec":[["noun.quantity"],["parsec","secpar","astronomy unit"]], "femtometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["femtometer","femtometre","fermi","metric linear unit","picometer"]], "picometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["picometer","picometre","micromicron","metric linear unit","angstrom"]], "angstrom":[["noun.quantity"],["angstrom","angstrom unit","A1","metric linear unit","nanometer"]], "nanometer":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["nanometer","nanometre","nm","millimicron","micromillimeter","micromillimetre","metric linear unit","micron"]], "micron":[["noun.quantity"],["micron","micrometer","metric linear unit","millimeter"]], "millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["millimeter","millimetre","mm","metric linear unit","centimeter"]], "centimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["centimeter","centimetre","cm","metric linear unit","decimeter"]], "decimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["decimeter","decimetre","dm","metric linear unit","meter"]], "decameter":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["decameter","dekameter","decametre","dekametre","dam","dkm","metric linear unit","hectometer"]], "hectometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["hectometer","hectometre","hm","metric linear unit","kilometer"]], "kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kilometer","kilometre","km","klick","metric linear unit","myriameter"]], "myriameter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["myriameter","myriametre","mym","metric linear unit"]], "nautical chain":[["noun.quantity"],["nautical chain","chain"]], "nautical mile":[["noun.quantity","noun.quantity:miler","noun.quantity","noun.quantity:miler"],["nautical mile1","mile4","mi4","naut mi","international nautical mile","air mile","nautical linear unit","nautical mile2","naut mi1","mile6","mi5","geographical mile","Admiralty mile","nautical linear unit"]], "sea mile":[["noun.quantity","noun.quantity:miler"],["sea mile","mile5","nautical linear unit"]], "halfpennyworth":[["noun.quantity"],["halfpennyworth","ha'p'orth","worth"]], "pennyworth":[["noun.quantity"],["pennyworth","penn'orth","worth"]], "euro":[["noun.quantity"],["euro","monetary unit"]], "franc":[["noun.quantity"],["franc","monetary unit"]], "fractional monetary unit":[["noun.quantity"],["fractional monetary unit","subunit","monetary unit"]], "afghan monetary unit":[["noun.quantity"],["Afghan monetary unit","monetary unit"]], "afghani":[["noun.quantity"],["afghani","Afghan monetary unit"]], "pul":[["noun.quantity"],["pul","afghani","Afghan monetary unit"]], "argentine monetary unit":[["noun.quantity"],["Argentine monetary unit","monetary unit"]], "austral":[["noun.quantity"],["austral","Argentine monetary unit"]], "thai monetary unit":[["noun.quantity"],["Thai monetary unit","monetary unit"]], "baht":[["noun.quantity"],["baht","tical","Thai monetary unit"]], "satang":[["noun.quantity"],["satang","baht","Thai monetary unit"]], "panamanian monetary unit":[["noun.quantity"],["Panamanian monetary unit","monetary unit"]], "ethiopian monetary unit":[["noun.quantity"],["Ethiopian monetary unit","monetary unit"]], "birr":[["noun.quantity"],["birr","Ethiopian monetary unit"]], "cent":[["noun.quantity"],["cent","fractional monetary unit","birr","dollar","gulden1","leone","lilangeni","rand","Mauritian rupee","Seychelles rupee","Sri Lanka rupee","shilling1"]], "centesimo":[["noun.quantity"],["centesimo","fractional monetary unit","balboa","Italian lira","Uruguayan peso","Chilean peso"]], "centimo":[["noun.quantity"],["centimo","fractional monetary unit","bolivar","Costa Rican colon","guarani","peseta"]], "centavo":[["noun.quantity"],["centavo","fractional monetary unit","austral","El Salvadoran colon","dobra","escudo1","escudo2","cordoba","lempira","metical","boliviano","peso3","peso4","peso5","peso6","peso7","peso8","peso10","quetzal","real1","sucre"]], "centime":[["noun.quantity"],["centime","fractional monetary unit","franc","Algerian dinar","Belgian franc","Burkina Faso franc","Burundi franc","Cameroon franc","Chadian franc","Congo franc","Gabon franc","Ivory Coast franc","Luxembourg franc","Mali franc","Moroccan dirham","Niger franc","Rwanda franc","Senegalese franc","Swiss franc","Togo franc"]], "venezuelan monetary unit":[["noun.quantity"],["Venezuelan monetary unit","monetary unit"]], "ghanian monetary unit":[["noun.quantity"],["Ghanian monetary unit","monetary unit"]], "cedi":[["noun.quantity"],["cedi","Ghanian monetary unit"]], "pesewa":[["noun.quantity"],["pesewa","cedi","Ghanian monetary unit"]], "costa rican monetary unit":[["noun.quantity"],["Costa Rican monetary unit","monetary unit"]], "el salvadoran monetary unit":[["noun.quantity"],["El Salvadoran monetary unit","monetary unit"]], "brazilian monetary unit":[["noun.quantity"],["Brazilian monetary unit","monetary unit"]], "gambian monetary unit":[["noun.quantity"],["Gambian monetary unit","monetary unit"]], "dalasi":[["noun.quantity"],["dalasi","Gambian monetary unit"]], "butut":[["noun.quantity"],["butut","butat","dalasi","Gambian monetary unit"]], "algerian monetary unit":[["noun.quantity"],["Algerian monetary unit","monetary unit"]], "algerian dinar":[["noun.quantity"],["Algerian dinar","dinar","Algerian monetary unit"]], "algerian centime":[["noun.quantity"],["Algerian centime","centime","Algerian dinar"]], "bahrainian monetary unit":[["noun.quantity"],["Bahrainian monetary unit","monetary unit"]], "bahrain dinar":[["noun.quantity"],["Bahrain dinar","dinar1","Bahrainian monetary unit"]], "fils":[["noun.quantity"],["fils","fractional monetary unit","Bahrain dinar","Iraqi dinar","Jordanian dinar","Kuwaiti dirham"]], "iraqi monetary unit":[["noun.quantity"],["Iraqi monetary unit","monetary unit"]], "iraqi dinar":[["noun.quantity"],["Iraqi dinar","dinar2","Iraqi monetary unit"]], "jordanian monetary unit":[["noun.quantity"],["Jordanian monetary unit","monetary unit"]], "jordanian dinar":[["noun.quantity"],["Jordanian dinar","dinar3","Jordanian monetary unit"]], "kuwaiti monetary unit":[["noun.quantity"],["Kuwaiti monetary unit","monetary unit"]], "kuwaiti dinar":[["noun.quantity"],["Kuwaiti dinar","dinar4","Kuwaiti monetary unit"]], "kuwaiti dirham":[["noun.quantity"],["Kuwaiti dirham","dirham1","Kuwaiti monetary unit","Kuwaiti dinar"]], "libyan monetary unit":[["noun.quantity"],["Libyan monetary unit","monetary unit"]], "libyan dinar":[["noun.quantity"],["Libyan dinar","dinar5","Libyan monetary unit"]], "libyan dirham":[["noun.quantity"],["Libyan dirham","dirham2","Libyan monetary unit","Libyan dinar"]], "tunisian monetary unit":[["noun.quantity"],["Tunisian monetary unit","monetary unit"]], "tunisian dinar":[["noun.quantity"],["Tunisian dinar","dinar7","Tunisian monetary unit"]], "tunisian dirham":[["noun.quantity"],["Tunisian dirham","dirham3","Tunisian monetary unit","Tunisian dinar"]], "millime":[["noun.quantity"],["millime","Tunisian monetary unit","Tunisian dirham"]], "yugoslavian monetary unit":[["noun.quantity"],["Yugoslavian monetary unit","monetary unit"]], "yugoslavian dinar":[["noun.quantity"],["Yugoslavian dinar","dinar8","Yugoslavian monetary unit"]], "moroccan monetary unit":[["noun.quantity"],["Moroccan monetary unit","monetary unit"]], "moroccan dirham":[["noun.quantity"],["Moroccan dirham","dirham4","Moroccan monetary unit"]], "united arab emirate monetary unit":[["noun.quantity"],["United Arab Emirate monetary unit","monetary unit"]], "united arab emirate dirham":[["noun.quantity"],["United Arab Emirate dirham","dirham5","United Arab Emirate monetary unit"]], "australian dollar":[["noun.quantity"],["Australian dollar","dollar"]], "bahamian dollar":[["noun.quantity"],["Bahamian dollar","dollar"]], "barbados dollar":[["noun.quantity"],["Barbados dollar","dollar"]], "belize dollar":[["noun.quantity"],["Belize dollar","dollar"]], "bermuda dollar":[["noun.quantity"],["Bermuda dollar","dollar"]], "brunei dollar":[["noun.quantity"],["Brunei dollar","dollar"]], "sen":[["noun.quantity"],["sen","fractional monetary unit","rupiah","riel","ringgit","yen"]], "canadian dollar":[["noun.quantity"],["Canadian dollar","loonie","dollar"]], "cayman islands dollar":[["noun.quantity"],["Cayman Islands dollar","dollar"]], "dominican dollar":[["noun.quantity"],["Dominican dollar","dollar"]], "fiji dollar":[["noun.quantity"],["Fiji dollar","dollar"]], "grenada dollar":[["noun.quantity"],["Grenada dollar","dollar"]], "guyana dollar":[["noun.quantity"],["Guyana dollar","dollar"]], "hong kong dollar":[["noun.quantity"],["Hong Kong dollar","dollar"]], "jamaican dollar":[["noun.quantity"],["Jamaican dollar","dollar"]], "kiribati dollar":[["noun.quantity"],["Kiribati dollar","dollar"]], "liberian dollar":[["noun.quantity"],["Liberian dollar","dollar"]], "new zealand dollar":[["noun.quantity"],["New Zealand dollar","dollar"]], "singapore dollar":[["noun.quantity"],["Singapore dollar","dollar"]], "taiwan dollar":[["noun.quantity"],["Taiwan dollar","dollar"]], "trinidad and tobago dollar":[["noun.quantity"],["Trinidad and Tobago dollar","dollar"]], "tuvalu dollar":[["noun.quantity"],["Tuvalu dollar","dollar"]], "united states dollar":[["noun.quantity"],["United States dollar","dollar"]], "eurodollar":[["noun.quantity","noun.possession:Eurocurrency"],["Eurodollar","United States dollar"]], "zimbabwean dollar":[["noun.quantity"],["Zimbabwean dollar","dollar"]], "vietnamese monetary unit":[["noun.quantity"],["Vietnamese monetary unit","monetary unit"]], "dong":[["noun.quantity"],["dong","Vietnamese monetary unit"]], "hao":[["noun.quantity"],["hao","dong","Vietnamese monetary unit"]], "greek monetary unit":[["noun.quantity"],["Greek monetary unit","monetary unit"]], "drachma":[["noun.quantity"],["drachma","Greek drachma","Greek monetary unit"]], "sao thome e principe monetary unit":[["noun.quantity"],["Sao Thome e Principe monetary unit","monetary unit"]], "dobra":[["noun.quantity"],["dobra","Sao Thome e Principe monetary unit"]], "cape verde monetary unit":[["noun.quantity"],["Cape Verde monetary unit","monetary unit"]], "cape verde escudo":[["noun.quantity"],["Cape Verde escudo","escudo1","Cape Verde monetary unit"]], "portuguese monetary unit":[["noun.quantity"],["Portuguese monetary unit","monetary unit"]], "portuguese escudo":[["noun.quantity"],["Portuguese escudo","escudo2","Portuguese monetary unit","conto"]], "conto":[["noun.quantity"],["conto","Portuguese monetary unit"]], "hungarian monetary unit":[["noun.quantity"],["Hungarian monetary unit","monetary unit"]], "forint":[["noun.quantity"],["forint","Hungarian monetary unit"]], "belgian franc":[["noun.quantity"],["Belgian franc","franc"]], "benin franc":[["noun.quantity"],["Benin franc","franc"]], "burundi franc":[["noun.quantity"],["Burundi franc","franc"]], "cameroon franc":[["noun.quantity"],["Cameroon franc","franc"]], "central african republic franc":[["noun.quantity"],["Central African Republic franc","franc"]], "chadian franc":[["noun.quantity"],["Chadian franc","franc"]], "congo franc":[["noun.quantity"],["Congo franc","franc"]], "djibouti franc":[["noun.quantity"],["Djibouti franc","franc"]], "french franc":[["noun.quantity"],["French franc","franc"]], "gabon franc":[["noun.quantity"],["Gabon franc","franc"]], "ivory coast franc":[["noun.quantity"],["Ivory Coast franc","Cote d'Ivoire franc","franc"]], "luxembourg franc":[["noun.quantity"],["Luxembourg franc","franc"]], "madagascar franc":[["noun.quantity"],["Madagascar franc","franc"]], "mali franc":[["noun.quantity"],["Mali franc","franc"]], "niger franc":[["noun.quantity"],["Niger franc","franc"]], "rwanda franc":[["noun.quantity"],["Rwanda franc","franc"]], "senegalese franc":[["noun.quantity"],["Senegalese franc","franc"]], "swiss franc":[["noun.quantity"],["Swiss franc","franc"]], "togo franc":[["noun.quantity"],["Togo franc","franc"]], "burkina faso franc":[["noun.quantity"],["Burkina Faso franc","franc"]], "haitian monetary unit":[["noun.quantity"],["Haitian monetary unit","monetary unit"]], "gourde":[["noun.quantity"],["gourde","Haitian monetary unit"]], "haitian centime":[["noun.quantity"],["Haitian centime","centime","gourde"]], "paraguayan monetary unit":[["noun.quantity"],["Paraguayan monetary unit","monetary unit"]], "dutch monetary unit":[["noun.quantity"],["Dutch monetary unit","monetary unit"]], "guilder":[["noun.quantity","noun.quantity"],["guilder1","gulden1","florin1","Dutch florin","Dutch monetary unit","guilder2","gulden2","florin2","Surinamese monetary unit"]], "surinamese monetary unit":[["noun.quantity"],["Surinamese monetary unit","monetary unit"]], "peruvian monetary unit":[["noun.quantity"],["Peruvian monetary unit","monetary unit"]], "inti":[["noun.quantity"],["inti","Peruvian monetary unit"]], "papuan monetary unit":[["noun.quantity"],["Papuan monetary unit","monetary unit"]], "kina":[["noun.quantity"],["kina","Papuan monetary unit"]], "toea":[["noun.quantity"],["toea","kina","Papuan monetary unit"]], "laotian monetary unit":[["noun.quantity"],["Laotian monetary unit","monetary unit"]], "at":[["noun.quantity"],["at","kip","Laotian monetary unit"]], "czech monetary unit":[["noun.quantity"],["Czech monetary unit","monetary unit"]], "koruna":[["noun.quantity","noun.quantity"],["koruna","Czech monetary unit","koruna1","Slovakian monetary unit"]], "haler":[["noun.quantity","noun.quantity"],["haler","heller","koruna","Czech monetary unit","haler1","heller1","Slovakian monetary unit","koruna"]], "slovakian monetary unit":[["noun.quantity"],["Slovakian monetary unit","monetary unit"]], "icelandic monetary unit":[["noun.quantity"],["Icelandic monetary unit","monetary unit"]], "icelandic krona":[["noun.quantity"],["Icelandic krona","krona1","Icelandic monetary unit"]], "eyrir":[["noun.quantity"],["eyrir","Icelandic krona","Icelandic monetary unit"]], "swedish monetary unit":[["noun.quantity"],["Swedish monetary unit","monetary unit"]], "swedish krona":[["noun.quantity"],["Swedish krona","krona2","Swedish monetary unit"]], "danish monetary unit":[["noun.quantity"],["Danish monetary unit","monetary unit"]], "danish krone":[["noun.quantity"],["Danish krone","krone1","Danish monetary unit"]], "norwegian monetary unit":[["noun.quantity"],["Norwegian monetary unit","monetary unit"]], "norwegian krone":[["noun.quantity"],["Norwegian krone","krone2","Norwegian monetary unit"]], "malawian monetary unit":[["noun.quantity"],["Malawian monetary unit","monetary unit"]], "malawi kwacha":[["noun.quantity"],["Malawi kwacha","kwacha1","Malawian monetary unit"]], "tambala":[["noun.quantity"],["tambala","Malawi kwacha","Malawian monetary unit"]], "zambian monetary unit":[["noun.quantity"],["Zambian monetary unit","monetary unit"]], "zambian kwacha":[["noun.quantity"],["Zambian kwacha","kwacha2","Zambian monetary unit"]], "ngwee":[["noun.quantity"],["ngwee","Zambian kwacha","Zambian monetary unit"]], "angolan monetary unit":[["noun.quantity"],["Angolan monetary unit","monetary unit"]], "kwanza":[["noun.quantity"],["kwanza","Angolan monetary unit"]], "lwei":[["noun.quantity"],["lwei","kwanza","Angolan monetary unit"]], "myanmar monetary unit":[["noun.quantity","noun.location:Burma"],["Myanmar monetary unit","monetary unit"]], "kyat":[["noun.quantity"],["kyat","Myanmar monetary unit"]], "pya":[["noun.quantity"],["pya","kyat","Myanmar monetary unit"]], "albanian monetary unit":[["noun.quantity"],["Albanian monetary unit","monetary unit"]], "lek":[["noun.quantity"],["lek","Albanian monetary unit"]], "qindarka":[["noun.quantity"],["qindarka","qintar","lek","Albanian monetary unit"]], "honduran monetary unit":[["noun.quantity"],["Honduran monetary unit","monetary unit"]], "lempira":[["noun.quantity"],["lempira","Honduran monetary unit"]], "sierra leone monetary unit":[["noun.quantity"],["Sierra Leone monetary unit","monetary unit"]], "leone":[["noun.quantity"],["leone","Sierra Leone monetary unit"]], "romanian monetary unit":[["noun.quantity"],["Romanian monetary unit","monetary unit"]], "leu":[["noun.quantity","noun.quantity"],["leu","Romanian monetary unit","leu1","Moldovan monetary unit"]], "bulgarian monetary unit":[["noun.quantity"],["Bulgarian monetary unit","monetary unit"]], "lev":[["noun.quantity"],["lev","Bulgarian monetary unit"]], "stotinka":[["noun.quantity"],["stotinka","lev","Bulgarian monetary unit"]], "swaziland monetary unit":[["noun.quantity"],["Swaziland monetary unit","monetary unit"]], "lilangeni":[["noun.quantity"],["lilangeni","Swaziland monetary unit"]], "italian monetary unit":[["noun.quantity"],["Italian monetary unit","monetary unit"]], "lira":[["noun.quantity","noun.quantity","noun.quantity"],["lira1","Italian lira","Italian monetary unit","lira2","Turkish lira","Turkish monetary unit","lira3","Maltese lira","Maltese monetary unit"]], "british monetary unit":[["noun.quantity"],["British monetary unit","monetary unit"]], "british pound":[["noun.quantity"],["British pound","pound1","British pound sterling","pound sterling","quid","British monetary unit"]], "british shilling":[["noun.quantity"],["British shilling","shilling1","bob","British monetary unit"]], "turkish monetary unit":[["noun.quantity"],["Turkish monetary unit","monetary unit"]], "kurus":[["noun.quantity"],["kurus","piaster1","piastre1","lira2","Turkish monetary unit"]], "asper":[["noun.quantity"],["asper","kurus","Turkish monetary unit"]], "lesotho monetary unit":[["noun.quantity"],["Lesotho monetary unit","monetary unit"]], "loti":[["noun.quantity"],["loti","Lesotho monetary unit"]], "sente":[["noun.quantity"],["sente","loti","Lesotho monetary unit"]], "german monetary unit":[["noun.quantity"],["German monetary unit","monetary unit"]], "pfennig":[["noun.quantity"],["pfennig","German monetary unit","mark"]], "finnish monetary unit":[["noun.quantity"],["Finnish monetary unit","monetary unit"]], "markka":[["noun.quantity"],["markka","Finnish mark","Finnish monetary unit"]], "penni":[["noun.quantity"],["penni","markka","Finnish monetary unit"]], "mozambique monetary unit":[["noun.quantity"],["Mozambique monetary unit","monetary unit"]], "metical":[["noun.quantity"],["metical","Mozambique monetary unit"]], "nigerian monetary unit":[["noun.quantity"],["Nigerian monetary unit","monetary unit"]], "naira":[["noun.quantity"],["naira","Nigerian monetary unit"]], "kobo":[["noun.quantity"],["kobo","naira","Nigerian monetary unit"]], "bhutanese monetary unit":[["noun.quantity"],["Bhutanese monetary unit","monetary unit"]], "ngultrum":[["noun.quantity"],["ngultrum","Bhutanese monetary unit"]], "chetrum":[["noun.quantity"],["chetrum","ngultrum","Bhutanese monetary unit"]], "mauritanian monetary unit":[["noun.quantity"],["Mauritanian monetary unit","monetary unit"]], "ouguiya":[["noun.quantity"],["ouguiya","Mauritanian monetary unit"]], "khoum":[["noun.quantity"],["khoum","ouguiya","Mauritanian monetary unit"]], "tongan monetary unit":[["noun.quantity"],["Tongan monetary unit","monetary unit"]], "pa'anga":[["noun.quantity"],["pa'anga","Tongan monetary unit"]], "seniti":[["noun.quantity"],["seniti","pa'anga","Tongan monetary unit"]], "macao monetary unit":[["noun.quantity"],["Macao monetary unit","monetary unit"]], "pataca":[["noun.quantity"],["pataca","Macao monetary unit"]], "avo":[["noun.quantity"],["avo","pataca","Macao monetary unit"]], "spanish monetary unit":[["noun.quantity"],["Spanish monetary unit","monetary unit"]], "peseta":[["noun.quantity"],["peseta","Spanish peseta","Spanish monetary unit"]], "bolivian monetary unit":[["noun.quantity"],["Bolivian monetary unit","monetary unit"]], "boliviano":[["noun.quantity"],["boliviano","Bolivian monetary unit"]], "nicaraguan monetary unit":[["noun.quantity"],["Nicaraguan monetary unit","monetary unit"]], "chilean monetary unit":[["noun.quantity"],["Chilean monetary unit","monetary unit"]], "chilean peso":[["noun.quantity"],["Chilean peso","peso9","Chilean monetary unit"]], "colombian monetary unit":[["noun.quantity"],["Colombian monetary unit","monetary unit"]], "colombian peso":[["noun.quantity"],["Colombian peso","peso3","Colombian monetary unit"]], "cuban monetary unit":[["noun.quantity"],["Cuban monetary unit","monetary unit"]], "cuban peso":[["noun.quantity"],["Cuban peso","peso4","Cuban monetary unit"]], "dominican monetary unit":[["noun.quantity"],["Dominican monetary unit","monetary unit"]], "dominican peso":[["noun.quantity"],["Dominican peso","peso5","Dominican monetary unit"]], "guinea-bissau monetary unit":[["noun.quantity"],["Guinea-Bissau monetary unit","monetary unit"]], "guinea-bissau peso":[["noun.quantity"],["Guinea-Bissau peso","peso10","Guinea-Bissau monetary unit"]], "mexican monetary unit":[["noun.quantity"],["Mexican monetary unit","monetary unit"]], "mexican peso":[["noun.quantity"],["Mexican peso","peso6","Mexican monetary unit"]], "philippine monetary unit":[["noun.quantity"],["Philippine monetary unit","monetary unit"]], "philippine peso":[["noun.quantity"],["Philippine peso","peso7","Philippine monetary unit"]], "uruguayan monetary unit":[["noun.quantity"],["Uruguayan monetary unit","monetary unit"]], "uruguayan peso":[["noun.quantity"],["Uruguayan peso","peso8","Uruguayan monetary unit"]], "cypriot monetary unit":[["noun.quantity"],["Cypriot monetary unit","monetary unit"]], "cypriot pound":[["noun.quantity"],["Cypriot pound","pound2","Cypriot monetary unit"]], "egyptian monetary unit":[["noun.quantity"],["Egyptian monetary unit","monetary unit"]], "egyptian pound":[["noun.quantity"],["Egyptian pound","pound3","Egyptian monetary unit"]], "piaster":[["noun.quantity"],["piaster","piastre","fractional monetary unit","Egyptian pound","Lebanese pound","Sudanese pound","Syrian pound"]], "irish monetary unit":[["noun.quantity"],["Irish monetary unit","monetary unit"]], "irish pound":[["noun.quantity"],["Irish pound","Irish punt","punt","pound4","Irish monetary unit"]], "lebanese monetary unit":[["noun.quantity"],["Lebanese monetary unit","monetary unit"]], "lebanese pound":[["noun.quantity"],["Lebanese pound","pound5","Lebanese monetary unit"]], "maltese monetary unit":[["noun.quantity"],["Maltese monetary unit","monetary unit"]], "sudanese monetary unit":[["noun.quantity"],["Sudanese monetary unit","monetary unit"]], "sudanese pound":[["noun.quantity"],["Sudanese pound","pound7","Sudanese monetary unit"]], "syrian monetary unit":[["noun.quantity"],["Syrian monetary unit","monetary unit"]], "syrian pound":[["noun.quantity"],["Syrian pound","pound8","Syrian monetary unit"]], "botswana monetary unit":[["noun.quantity"],["Botswana monetary unit","monetary unit"]], "pula":[["noun.quantity"],["pula","Botswana monetary unit"]], "thebe":[["noun.quantity"],["thebe","pula","Botswana monetary unit"]], "guatemalan monetary unit":[["noun.quantity"],["Guatemalan monetary unit","monetary unit"]], "south african monetary unit":[["noun.quantity"],["South African monetary unit","monetary unit"]], "iranian monetary unit":[["noun.quantity"],["Iranian monetary unit","monetary unit"]], "iranian rial":[["noun.quantity"],["Iranian rial","rial1","Iranian monetary unit"]], "iranian dinar":[["noun.quantity"],["Iranian dinar","dinar9","Iranian monetary unit","Iranian rial"]], "omani monetary unit":[["noun.quantity"],["Omani monetary unit","monetary unit"]], "riyal-omani":[["noun.quantity"],["riyal-omani","Omani rial","rial2","Omani monetary unit"]], "baiza":[["noun.quantity"],["baiza","baisa","Omani monetary unit","riyal-omani"]], "yemeni monetary unit":[["noun.quantity"],["Yemeni monetary unit","monetary unit"]], "yemeni rial":[["noun.quantity"],["Yemeni rial","rial","Yemeni monetary unit"]], "yemeni fils":[["noun.quantity"],["Yemeni fils","fils1","Yemeni monetary unit"]], "cambodian monetary unit":[["noun.quantity"],["Cambodian monetary unit","monetary unit"]], "riel":[["noun.quantity"],["riel","Cambodian monetary unit"]], "malaysian monetary unit":[["noun.quantity"],["Malaysian monetary unit","monetary unit"]], "ringgit":[["noun.quantity"],["ringgit","Malaysian monetary unit"]], "qatari monetary unit":[["noun.quantity"],["Qatari monetary unit","monetary unit"]], "qatari riyal":[["noun.quantity"],["Qatari riyal","riyal2","Qatari monetary unit"]], "qatari dirham":[["noun.quantity"],["Qatari dirham","dirham6","Qatari monetary unit","Qatari riyal"]], "saudi arabian monetary unit":[["noun.quantity"],["Saudi Arabian monetary unit","monetary unit"]], "saudi arabian riyal":[["noun.quantity"],["Saudi Arabian riyal","riyal3","Saudi Arabian monetary unit"]], "qurush":[["noun.quantity"],["qurush","Saudi Arabian riyal","Saudi Arabian monetary unit"]], "russian monetary unit":[["noun.quantity"],["Russian monetary unit","monetary unit"]], "ruble":[["noun.quantity","noun.quantity"],["ruble","rouble","Russian monetary unit","ruble1","Tajikistani monetary unit"]], "kopek":[["noun.quantity"],["kopek","kopeck","copeck","ruble","Russian monetary unit"]], "armenian monetary unit":[["noun.quantity"],["Armenian monetary unit","monetary unit"]], "dram":[["noun.quantity","noun.quantity","noun.quantity"],["dram","Armenian monetary unit","dram1","avoirdupois unit","ounce1","dram2","drachm","drachma2","apothecaries' unit","ounce2"]], "lumma":[["noun.quantity"],["lumma","Armenian monetary unit"]], "azerbaijani monetary unit":[["noun.quantity"],["Azerbaijani monetary unit","monetary unit"]], "manat":[["noun.quantity","noun.quantity"],["manat","Azerbaijani monetary unit","manat1","Turkmen monetary unit"]], "qepiq":[["noun.quantity"],["qepiq","Azerbaijani monetary unit"]], "belarusian monetary unit":[["noun.quantity"],["Belarusian monetary unit","monetary unit"]], "rubel":[["noun.quantity"],["rubel","Belarusian monetary unit"]], "kapeika":[["noun.quantity"],["kapeika","Belarusian monetary unit"]], "estonian monetary unit":[["noun.quantity"],["Estonian monetary unit","monetary unit"]], "kroon":[["noun.quantity"],["kroon","Estonian monetary unit"]], "sent":[["noun.quantity"],["sent","Estonian monetary unit"]], "georgian monetary unit":[["noun.quantity"],["Georgian monetary unit","monetary unit"]], "tetri":[["noun.quantity"],["tetri","Georgian monetary unit","lari"]], "kazakhstani monetary unit":[["noun.quantity"],["Kazakhstani monetary unit","monetary unit"]], "tenge":[["noun.quantity","noun.quantity"],["tenge","Kazakhstani monetary unit","tenge1","Turkmen monetary unit"]], "tiyin":[["noun.quantity","noun.quantity"],["tiyin","Kazakhstani monetary unit","tiyin1","Uzbekistani monetary unit"]], "latvian monetary unit":[["noun.quantity"],["Latvian monetary unit","monetary unit"]], "lats":[["noun.quantity"],["lats","Latvian monetary unit"]], "santims":[["noun.quantity"],["santims","Latvian monetary unit"]], "lithuanian monetary unit":[["noun.quantity"],["Lithuanian monetary unit","monetary unit"]], "litas":[["noun.quantity"],["litas","Lithuanian monetary unit"]], "centas":[["noun.quantity"],["centas","Lithuanian monetary unit"]], "kyrgyzstani monetary unit":[["noun.quantity"],["Kyrgyzstani monetary unit","monetary unit"]], "som":[["noun.quantity","noun.quantity"],["som","Kyrgyzstani monetary unit","som1","Uzbekistani monetary unit"]], "tyiyn":[["noun.quantity"],["tyiyn","Kyrgyzstani monetary unit"]], "moldovan monetary unit":[["noun.quantity"],["Moldovan monetary unit","monetary unit"]], "tajikistani monetary unit":[["noun.quantity"],["Tajikistani monetary unit","monetary unit"]], "turkmen monetary unit":[["noun.quantity"],["Turkmen monetary unit","monetary unit"]], "ukranian monetary unit":[["noun.quantity"],["Ukranian monetary unit","monetary unit"]], "hryvnia":[["noun.quantity"],["hryvnia","Ukranian monetary unit"]], "kopiyka":[["noun.quantity"],["kopiyka","Ukranian monetary unit","hryvnia"]], "uzbekistani monetary unit":[["noun.quantity"],["Uzbekistani monetary unit","monetary unit"]], "indian monetary unit":[["noun.quantity"],["Indian monetary unit","monetary unit"]], "indian rupee":[["noun.quantity"],["Indian rupee","rupee1","Indian monetary unit"]], "paisa":[["noun.quantity"],["paisa","fractional monetary unit","Indian rupee","Nepalese rupee","Pakistani rupee","taka"]], "pakistani monetary unit":[["noun.quantity"],["Pakistani monetary unit","monetary unit"]], "pakistani rupee":[["noun.quantity"],["Pakistani rupee","rupee2","Pakistani monetary unit"]], "anna":[["noun.quantity"],["anna","Pakistani monetary unit","Indian monetary unit"]], "mauritian monetary unit":[["noun.quantity"],["Mauritian monetary unit","monetary unit"]], "mauritian rupee":[["noun.quantity"],["Mauritian rupee","rupee3","Mauritian monetary unit"]], "nepalese monetary unit":[["noun.quantity"],["Nepalese monetary unit","monetary unit"]], "nepalese rupee":[["noun.quantity"],["Nepalese rupee","rupee4","Nepalese monetary unit"]], "seychelles monetary unit":[["noun.quantity"],["Seychelles monetary unit","monetary unit"]], "seychelles rupee":[["noun.quantity"],["Seychelles rupee","rupee5","Seychelles monetary unit"]], "sri lankan monetary unit":[["noun.quantity"],["Sri Lankan monetary unit","monetary unit"]], "sri lanka rupee":[["noun.quantity"],["Sri Lanka rupee","rupee6","Sri Lankan monetary unit"]], "indonesian monetary unit":[["noun.quantity"],["Indonesian monetary unit","monetary unit"]], "rupiah":[["noun.quantity"],["rupiah","Indonesian monetary unit"]], "austrian monetary unit":[["noun.quantity"],["Austrian monetary unit","monetary unit"]], "schilling":[["noun.quantity"],["schilling","Austrian schilling","Austrian monetary unit"]], "groschen":[["noun.quantity"],["groschen","schilling","Austrian monetary unit"]], "israeli monetary unit":[["noun.quantity"],["Israeli monetary unit","monetary unit"]], "shekel":[["noun.quantity"],["shekel","Israeli monetary unit"]], "kenyan monetary unit":[["noun.quantity"],["Kenyan monetary unit","monetary unit"]], "kenyan shilling":[["noun.quantity"],["Kenyan shilling","shilling2","kenyan monetary unit"]], "somalian monetary unit":[["noun.quantity"],["Somalian monetary unit","monetary unit"]], "somalian shilling":[["noun.quantity"],["Somalian shilling","shilling3","Somalian monetary unit"]], "tanzanian monetary unit":[["noun.quantity"],["Tanzanian monetary unit","monetary unit"]], "tanzanian shilling":[["noun.quantity"],["Tanzanian shilling","shilling4","Tanzanian monetary unit"]], "ugandan monetary unit":[["noun.quantity"],["Ugandan monetary unit","monetary unit"]], "ugandan shilling":[["noun.quantity"],["Ugandan shilling","shilling5","Ugandan monetary unit"]], "ecuadoran monetary unit":[["noun.quantity"],["Ecuadoran monetary unit","monetary unit"]], "guinean monetary unit":[["noun.quantity"],["Guinean monetary unit","monetary unit"]], "guinean franc":[["noun.quantity"],["Guinean franc","franc"]], "bangladeshi monetary unit":[["noun.quantity"],["Bangladeshi monetary unit","monetary unit"]], "taka":[["noun.quantity"],["taka","Bangladeshi monetary unit"]], "western samoan monetary unit":[["noun.quantity"],["Western Samoan monetary unit","monetary unit"]], "tala":[["noun.quantity"],["tala","Western Samoan monetary unit"]], "sene":[["noun.quantity"],["sene","tala","Western Samoan monetary unit"]], "mongolian monetary unit":[["noun.quantity"],["Mongolian monetary unit","monetary unit"]], "tugrik":[["noun.quantity"],["tugrik","tughrik","Mongolian monetary unit"]], "mongo":[["noun.quantity"],["mongo","tugrik","Mongolian monetary unit"]], "north korean monetary unit":[["noun.quantity"],["North Korean monetary unit","monetary unit"]], "north korean won":[["noun.quantity"],["North Korean won","won1","North Korean monetary unit"]], "chon":[["noun.quantity","noun.quantity"],["chon1","North Korean monetary unit","North Korean won","chon2","South Korean monetary unit","South Korean won"]], "south korean monetary unit":[["noun.quantity"],["South Korean monetary unit","monetary unit"]], "south korean won":[["noun.quantity"],["South Korean won","won2","South Korean monetary unit"]], "japanese monetary unit":[["noun.quantity"],["Japanese monetary unit","monetary unit"]], "yen":[["noun.quantity"],["yen","Japanese monetary unit"]], "chinese monetary unit":[["noun.quantity"],["Chinese monetary unit","monetary unit"]], "jiao":[["noun.quantity"],["jiao","yuan","Chinese monetary unit"]], "fen":[["noun.quantity"],["fen","Chinese monetary unit","jiao"]], "zairese monetary unit":[["noun.quantity"],["Zairese monetary unit","monetary unit"]], "zaire":[["noun.quantity"],["zaire","Zairese monetary unit"]], "likuta":[["noun.quantity"],["likuta","zaire","Zairese monetary unit"]], "polish monetary unit":[["noun.quantity"],["Polish monetary unit","monetary unit"]], "zloty":[["noun.quantity"],["zloty","Polish monetary unit"]], "grosz":[["noun.quantity"],["grosz","zloty","Polish monetary unit"]], "dol":[["noun.quantity"],["dol","pain unit"]], "standard atmosphere":[["noun.quantity"],["standard atmosphere","atmosphere","atm","standard pressure","pressure unit"]], "torr":[["noun.quantity"],["torr","millimeter of mercury","mm Hg","pressure unit"]], "pounds per square inch":[["noun.quantity"],["pounds per square inch","psi","pressure unit"]], "millibar":[["noun.quantity"],["millibar","pressure unit","bar"]], "barye":[["noun.quantity"],["barye","bar absolute","microbar","pressure unit","bar"]], "em":[["noun.quantity","noun.quantity"],["em2","pica em","pica","linear unit","inch","em1","em quad","mutton quad","area unit"]], "en":[["noun.quantity"],["en","nut","linear unit","em2"]], "agate line":[["noun.quantity"],["agate line","line","area unit"]], "milline":[["noun.quantity"],["milline","printing unit"]], "column inch":[["noun.quantity"],["column inch","inch2","area unit"]], "decibel":[["noun.quantity"],["decibel","dB","sound unit"]], "sone":[["noun.quantity"],["sone","sound unit","phon"]], "phon":[["noun.quantity"],["phon","sound unit"]], "erlang":[["noun.quantity"],["Erlang","telephone unit"]], "millidegree":[["noun.quantity"],["millidegree","temperature unit"]], "degree centigrade":[["noun.quantity"],["degree centigrade","degree Celsius","C2","degree3"]], "degree fahrenheit":[["noun.quantity"],["degree Fahrenheit","F2","degree3"]], "rankine":[["noun.quantity"],["Rankine","temperature unit"]], "degree day":[["noun.quantity"],["degree day","temperature unit"]], "standard temperature":[["noun.quantity"],["standard temperature","degree centigrade"]], "atomic mass unit":[["noun.quantity"],["atomic mass unit","mass unit"]], "mass number":[["noun.quantity"],["mass number","nucleon number","mass unit"]], "system of weights":[["noun.quantity"],["system of weights","weight1","system of measurement"]], "avoirdupois":[["noun.quantity"],["avoirdupois","avoirdupois weight","system of weights"]], "avoirdupois unit":[["noun.quantity"],["avoirdupois unit","mass unit","avoirdupois weight","English system"]], "troy unit":[["noun.quantity"],["troy unit","weight unit","troy weight"]], "apothecaries' unit":[["noun.quantity"],["apothecaries' unit","apothecaries' weight","weight unit"]], "metric weight unit":[["noun.quantity"],["metric weight unit","weight unit2","mass unit","metric unit","metric system"]], "catty":[["noun.quantity","noun.location:China"],["catty","cattie","weight unit"]], "crith":[["noun.quantity"],["crith","weight unit"]], "maund":[["noun.quantity"],["maund","weight unit"]], "obolus":[["noun.quantity"],["obolus","weight unit","gram"]], "picul":[["noun.quantity"],["picul","weight unit"]], "pood":[["noun.quantity"],["pood","weight unit"]], "rotl":[["noun.quantity"],["rotl","weight unit"]], "tael":[["noun.quantity"],["tael","weight unit"]], "tod":[["noun.quantity","noun.location:Britain"],["tod","weight unit"]], "ounce":[["noun.quantity","noun.quantity"],["ounce1","oz.","avoirdupois unit","pound9","ounce2","troy ounce","apothecaries' ounce","apothecaries' unit","troy unit","troy pound"]], "half pound":[["noun.quantity"],["half pound","avoirdupois unit","pound9"]], "quarter pound":[["noun.quantity"],["quarter pound","avoirdupois unit","pound"]], "hundredweight":[["noun.quantity","noun.quantity","noun.quantity"],["hundredweight1","cwt1","long hundredweight","avoirdupois unit","long ton","hundredweight2","cwt2","short hundredweight","centner1","cental","quintal1","avoirdupois unit","short ton","hundredweight3","metric hundredweight","doppelzentner","centner3","metric weight unit","quintal2"]], "long ton":[["noun.quantity"],["long ton","ton1","gross ton","avoirdupois unit"]], "short ton":[["noun.quantity"],["short ton","ton2","net ton","avoirdupois unit","kiloton"]], "pennyweight":[["noun.quantity"],["pennyweight","troy unit","ounce2"]], "troy pound":[["noun.quantity"],["troy pound","apothecaries' pound","apothecaries' unit","troy unit"]], "microgram":[["noun.quantity"],["microgram","mcg","metric weight unit","milligram"]], "milligram":[["noun.quantity"],["milligram","mg","metric weight unit","grain3"]], "nanogram":[["noun.quantity"],["nanogram","ng","metric weight unit","microgram"]], "decigram":[["noun.quantity"],["decigram","dg","metric weight unit","carat"]], "carat":[["noun.quantity"],["carat","metric weight unit","gram"]], "gram atom":[["noun.quantity"],["gram atom","gram-atomic weight","metric weight unit"]], "gram molecule":[["noun.quantity","adj.pert:molal","adj.pert:molar2","adj.pert:molar"],["gram molecule","mole","mol","metric weight unit"]], "dekagram":[["noun.quantity"],["dekagram","decagram","dkg","dag","metric weight unit","hectogram"]], "hectogram":[["noun.quantity"],["hectogram","hg","metric weight unit","kilogram"]], "kilogram":[["noun.quantity"],["kilogram","kg","kilo","metric weight unit","myriagram"]], "myriagram":[["noun.quantity"],["myriagram","myg","metric weight unit","centner2"]], "centner":[["noun.quantity"],["centner2","metric weight unit","hundredweight3"]], "quintal":[["noun.quantity"],["quintal2","metric weight unit","metric ton"]], "metric ton":[["noun.quantity"],["metric ton","MT","tonne","t1","metric weight unit"]], "erg":[["noun.quantity"],["erg","work unit","joule"]], "electron volt":[["noun.quantity"],["electron volt","eV","work unit"]], "calorie":[["noun.quantity","adj.pert:caloric","noun.quantity","adj.pert:caloric2"],["calorie1","gram calorie","small calorie","work unit","Calorie2","Calorie2","kilogram calorie","kilocalorie","large calorie","nutritionist's calorie","work unit"]], "british thermal unit":[["noun.quantity","B.Th.U."],["British thermal unit","BTU","work unit","therm"]], "therm":[["noun.quantity"],["therm","work unit"]], "watt-hour":[["noun.quantity"],["watt-hour","work unit","kilowatt hour"]], "kilowatt hour":[["noun.quantity","B.T.U."],["kilowatt hour","kW-hr","Board of Trade unit","work unit"]], "foot-pound":[["noun.quantity"],["foot-pound","work unit","foot-ton"]], "foot-ton":[["noun.quantity"],["foot-ton","work unit"]], "foot-poundal":[["noun.quantity"],["foot-poundal","work unit"]], "horsepower-hour":[["noun.quantity"],["horsepower-hour","work unit"]], "kilogram-meter":[["noun.quantity"],["kilogram-meter","work unit"]], "natural number":[["noun.quantity"],["natural number","number"]], "integer":[["noun.quantity"],["integer","whole number","number"]], "addend":[["noun.quantity"],["addend","number"]], "augend":[["noun.quantity"],["augend","number"]], "minuend":[["noun.quantity"],["minuend","number"]], "subtrahend":[["noun.quantity"],["subtrahend","number"]], "complex number":[["noun.quantity","noun.cognition:mathematics"],["complex number","complex quantity","imaginary number","imaginary","number"]], "complex conjugate":[["noun.quantity"],["complex conjugate","complex number"]], "real number":[["noun.quantity"],["real number","real","complex number"]], "pure imaginary number":[["noun.quantity"],["pure imaginary number","complex number"]], "imaginary part":[["noun.quantity"],["imaginary part","imaginary part of a complex number","pure imaginary number","complex number"]], "rational number":[["noun.quantity"],["rational number","rational","real number"]], "irrational number":[["noun.quantity"],["irrational number","irrational","real number"]], "transcendental number":[["noun.quantity"],["transcendental number","irrational number"]], "algebraic number":[["noun.quantity"],["algebraic number","irrational number"]], "biquadrate":[["noun.quantity","adj.pert:biquadratic","adj.pert:biquadratic"],["biquadrate","biquadratic","quartic","fourth power","number"]], "square root":[["noun.quantity"],["square root","root"]], "cube root":[["noun.quantity"],["cube root","root"]], "common fraction":[["noun.quantity"],["common fraction","simple fraction","fraction"]], "numerator":[["noun.quantity"],["numerator","dividend"]], "denominator":[["noun.quantity"],["denominator","divisor"]], "divisor":[["noun.quantity","noun.quantity","verb.cognition:factor","verb.cognition:factorize"],["divisor","number","divisor1","factor","integer"]], "multiplier":[["noun.quantity","verb.cognition:multiply"],["multiplier","multiplier factor","number"]], "multiplicand":[["noun.quantity"],["multiplicand","number"]], "scale factor":[["noun.quantity"],["scale factor","multiplier"]], "time-scale factor":[["noun.quantity","noun.cognition:simulation"],["time-scale factor","scale factor"]], "equivalent-binary-digit factor":[["noun.quantity"],["equivalent-binary-digit factor","divisor1"]], "aliquot":[["noun.quantity","adj.all:fractional^aliquot"],["aliquot","aliquant","aliquot part","divisor"]], "aliquant":[["noun.quantity"],["aliquant","aliquot","aliquant part","divisor"]], "common divisor":[["noun.quantity"],["common divisor","common factor","common measure","divisor1"]], "greatest common divisor":[["noun.quantity"],["greatest common divisor","greatest common factor","highest common factor","common divisor"]], "common multiple":[["noun.quantity"],["common multiple","integer"]], "improper fraction":[["noun.quantity"],["improper fraction","fraction"]], "proper fraction":[["noun.quantity"],["proper fraction","fraction"]], "complex fraction":[["noun.quantity"],["complex fraction","compound fraction","fraction"]], "decimal fraction":[["noun.quantity","verb.change:decimalize1","verb.change:decimalise1"],["decimal fraction","decimal","proper fraction"]], "circulating decimal":[["noun.quantity"],["circulating decimal","recurring decimal","repeating decimal","decimal fraction"]], "continued fraction":[["noun.quantity"],["continued fraction","fraction"]], "one-half":[["noun.quantity"],["one-half","half","common fraction"]], "fifty percent":[["noun.quantity"],["fifty percent","one-half"]], "one-third":[["noun.quantity"],["one-third","third","tierce","common fraction"]], "two-thirds":[["noun.quantity"],["two-thirds","common fraction"]], "one-fourth":[["noun.quantity","verb.contact:quarter1","verb.social:quarter"],["one-fourth","fourth","one-quarter","quarter1","fourth part","twenty-five percent","quartern","common fraction"]], "three-fourths":[["noun.quantity"],["three-fourths","three-quarters","common fraction"]], "one-fifth":[["noun.quantity"],["one-fifth","fifth","fifth part","twenty percent","common fraction"]], "one-sixth":[["noun.quantity"],["one-sixth","sixth","common fraction"]], "one-seventh":[["noun.quantity"],["one-seventh","seventh","common fraction"]], "one-eighth":[["noun.quantity"],["one-eighth","eighth","common fraction"]], "one-ninth":[["noun.quantity"],["one-ninth","ninth","common fraction"]], "one-tenth":[["noun.quantity"],["one-tenth","tenth","tenth part","ten percent","common fraction"]], "one-twelfth":[["noun.quantity"],["one-twelfth","twelfth","twelfth part","duodecimal","common fraction"]], "one-sixteenth":[["noun.quantity"],["one-sixteenth","sixteenth","sixteenth part","common fraction"]], "one-thirty-second":[["noun.quantity"],["one-thirty-second","thirty-second","thirty-second part","common fraction"]], "one-sixtieth":[["noun.quantity"],["one-sixtieth","sixtieth","common fraction"]], "one-sixty-fourth":[["noun.quantity"],["one-sixty-fourth","sixty-fourth","common fraction"]], "one-hundredth":[["noun.quantity"],["one-hundredth","hundredth","one percent","common fraction"]], "one-thousandth":[["noun.quantity"],["one-thousandth","thousandth","common fraction"]], "one-ten-thousandth":[["noun.quantity"],["one-ten-thousandth","ten-thousandth","common fraction"]], "one-hundred-thousandth":[["noun.quantity"],["one-hundred-thousandth","common fraction"]], "one-millionth":[["noun.quantity"],["one-millionth","millionth","common fraction"]], "one-hundred-millionth":[["noun.quantity"],["one-hundred-millionth","common fraction"]], "one-billionth":[["noun.quantity"],["one-billionth","billionth","common fraction"]], "one-trillionth":[["noun.quantity"],["one-trillionth","trillionth","common fraction"]], "one-quadrillionth":[["noun.quantity"],["one-quadrillionth","quadrillionth","common fraction"]], "one-quintillionth":[["noun.quantity"],["one-quintillionth","quintillionth","common fraction"]], "nothing":[["noun.quantity","verb.change:zero1"],["nothing","nil","nix","nada","null","aught","cipher","cypher","goose egg","naught","zero2","zilch","zip","zippo","relative quantity"]], "nihil":[["noun.quantity","noun.communication:Latin"],["nihil","nothing"]], "bugger all":[["noun.quantity","noun.location:Britain","noun.communication:obscenity"],["bugger all","fuck all","Fanny Adams","sweet Fanny Adams","nothing"]], "binary digit":[["noun.quantity"],["binary digit","digit"]], "octal digit":[["noun.quantity"],["octal digit","digit"]], "decimal digit":[["noun.quantity"],["decimal digit","digit"]], "duodecimal digit":[["noun.quantity"],["duodecimal digit","digit"]], "hexadecimal digit":[["noun.quantity"],["hexadecimal digit","digit"]], "significant digit":[["noun.quantity"],["significant digit","significant figure","digit"]], "two":[["noun.quantity"],["two","2\"","II","deuce","digit"]], "doubleton":[["noun.quantity","noun.act:bridge"],["doubleton","couple"]], "three":[["noun.quantity"],["three","3\"","III","trio","threesome","tierce1","leash","troika","triad","trine","trinity","ternary","ternion","triplet","tercet","terzetto","trey","deuce-ace","digit"]], "four":[["noun.quantity"],["four","4\"","IV","tetrad","quatern","quaternion","quaternary","quaternity","quartet","quadruplet","foursome","Little Joe","digit"]], "five":[["noun.quantity"],["five","5\"","V2","cinque","quint","quintet","fivesome","quintuplet","pentad","fin","Phoebe","Little Phoebe","digit"]], "six":[["noun.quantity"],["six","6\"","VI","sixer","sise","Captain Hicks","half a dozen","sextet","sestet","sextuplet","hexad","digit"]], "seven":[["noun.quantity","adj.all:cardinal^seven"],["seven","7\"","VII","sevener","heptad","septet","septenary","digit"]], "eight":[["noun.quantity"],["eight","8\"","VIII","eighter","eighter from Decatur","octad","ogdoad","octonary","octet","digit"]], "nine":[["noun.quantity"],["nine","9\"","IX","niner","Nina from Carolina","ennead","digit"]], "large integer":[["noun.quantity"],["large integer","integer"]], "double digit":[["noun.quantity"],["double digit","integer"]], "ten":[["noun.quantity"],["ten","10\"","X","tenner","decade","large integer"]], "eleven":[["noun.quantity"],["eleven","11\"","XI","large integer"]], "twelve":[["noun.quantity","adj.all:cardinal^dozen"],["twelve","12\"","XII","dozen","large integer"]], "boxcars":[["noun.quantity","noun.communication:plural"],["boxcars","twelve"]], "thirteen":[["noun.quantity"],["thirteen","13\"","XIII","baker's dozen","long dozen","large integer"]], "fourteen":[["noun.quantity"],["fourteen","14\"","XIV","large integer"]], "fifteen":[["noun.quantity","adj.all:cardinal^fifteen"],["fifteen","15\"","XV","large integer"]], "sixteen":[["noun.quantity"],["sixteen","16\"","XVI","large integer"]], "seventeen":[["noun.quantity","adj.all:cardinal^seventeen"],["seventeen","17\"","XVII","large integer"]], "eighteen":[["noun.quantity"],["eighteen","18\"","XVIII","large integer"]], "nineteen":[["noun.quantity","adj.all:cardinal^nineteen"],["nineteen","19\"","XIX","large integer"]], "twenty":[["noun.quantity"],["twenty","20\"","XX","large integer"]], "twenty-one":[["noun.quantity"],["twenty-one","21\"","XXI","large integer"]], "twenty-three":[["noun.quantity"],["twenty-three","23\"","XXIII","large integer"]], "twenty-four":[["noun.quantity"],["twenty-four","24\"","XXIV","two dozen","large integer"]], "twenty-five":[["noun.quantity"],["twenty-five","25\"","XXV","large integer"]], "twenty-six":[["noun.quantity"],["twenty-six","26\"","XXVI","large integer"]], "twenty-seven":[["noun.quantity"],["twenty-seven","27\"","XXVII","large integer"]], "twenty-eight":[["noun.quantity"],["twenty-eight","28\"","XXVIII","large integer"]], "twenty-nine":[["noun.quantity"],["twenty-nine","29\"","XXIX","large integer"]], "thirty":[["noun.quantity"],["thirty","30\"","XXX","large integer"]], "forty":[["noun.quantity"],["forty","40\"","XL","large integer"]], "fifty":[["noun.quantity","adj.all:cardinal^fifty"],["fifty","50\"","L6","large integer"]], "sixty":[["noun.quantity"],["sixty","60\"","LX","large integer"]], "seventy":[["noun.quantity","adj.all:cardinal^seventy"],["seventy","70\"","LXX","large integer"]], "eighty":[["noun.quantity"],["eighty","80\"","LXXX","fourscore","large integer"]], "ninety":[["noun.quantity"],["ninety","90\"","XC","large integer"]], "hundred":[["noun.quantity"],["hundred","100\"","C1","century","one C","large integer"]], "long hundred":[["noun.quantity"],["long hundred","great hundred","120\"","large integer"]], "five hundred":[["noun.quantity"],["five hundred","500\"","D","large integer"]], "thousand":[["noun.quantity"],["thousand","one thousand","1000\"","M1","K6","chiliad","G1","grand","thou","yard2","large integer"]], "millenary":[["noun.quantity"],["millenary","thousand"]], "great gross":[["noun.quantity"],["great gross","1728\"","large integer"]], "ten thousand":[["noun.quantity"],["ten thousand","10000\"","myriad","large integer"]], "hundred thousand":[["noun.quantity"],["hundred thousand","100000\"","lakh","large integer"]], "million":[["noun.quantity","noun.quantity"],["million","1000000\"","one thousand thousand","meg","large integer","million1","billion2","trillion2","zillion","jillion","gazillion","bazillion","large indefinite quantity"]], "crore":[["noun.quantity","noun.location:India"],["crore","large integer"]], "billion":[["noun.quantity","adj.all:cardinal^billion","noun.location:US","noun.quantity","adj.all:cardinal^billion1","noun.location:Britain"],["billion","one thousand million","1000000000\"","large integer","billion1","one million million","1000000000000\"","large integer"]], "milliard":[["noun.quantity","noun.location:Britain"],["milliard","billion"]], "trillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["trillion","one million million1","1000000000000\"1","large integer","trillion1","one million million million","large integer"]], "quadrillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["quadrillion","large integer","quadrillion1","large integer"]], "quintillion":[["noun.quantity","noun.location:US","noun.location:France"],["quintillion","large integer"]], "sextillion":[["noun.quantity","noun.location:US","noun.location:France"],["sextillion","large integer"]], "septillion":[["noun.quantity","noun.location:US","noun.location:France"],["septillion","large integer"]], "octillion":[["noun.quantity","noun.location:US","noun.location:France"],["octillion","large integer"]], "aleph-null":[["noun.quantity"],["aleph-null","aleph-nought","aleph-zero","large integer"]], "formatted capacity":[["noun.quantity","noun.cognition:computer science"],["formatted capacity","capacity1"]], "unformatted capacity":[["noun.quantity","noun.cognition:computer science"],["unformatted capacity","capacity1"]], "containerful":[["noun.quantity"],["containerful","indefinite quantity"]], "headspace":[["noun.quantity"],["headspace","indefinite quantity"]], "large indefinite quantity":[["noun.quantity"],["large indefinite quantity","large indefinite amount","indefinite quantity"]], "chunk":[["noun.quantity"],["chunk","large indefinite quantity"]], "pulmonary reserve":[["noun.quantity"],["pulmonary reserve","reserve"]], "small indefinite quantity":[["noun.quantity"],["small indefinite quantity","small indefinite amount","indefinite quantity"]], "hair's-breadth":[["noun.quantity"],["hair's-breadth","hairsbreadth","hair","whisker","small indefinite quantity"]], "modicum":[["noun.quantity"],["modicum","small indefinite quantity"]], "shoestring":[["noun.quantity"],["shoestring","shoe string","small indefinite quantity"]], "little":[["noun.quantity"],["little","small indefinite quantity"]], "shtikl":[["noun.quantity"],["shtikl","shtickl","schtikl","schtickl","shtik"]], "tad":[["noun.quantity"],["tad","shade","small indefinite quantity"]], "spillage":[["noun.quantity"],["spillage","indefinite quantity"]], "ullage":[["noun.quantity"],["ullage","indefinite quantity"]], "top-up":[["noun.quantity","noun.location:Britain"],["top-up","indefinite quantity"]], "armful":[["noun.quantity"],["armful","containerful"]], "barnful":[["noun.quantity"],["barnful","containerful"]], "busload":[["noun.quantity"],["busload","large indefinite quantity"]], "capful":[["noun.quantity"],["capful","containerful"]], "carful":[["noun.quantity"],["carful","containerful"]], "cartload":[["noun.quantity"],["cartload","containerful"]], "cask":[["noun.quantity"],["cask","caskful","containerful"]], "handful":[["noun.quantity","noun.quantity"],["handful","fistful","containerful","handful1","smattering","small indefinite quantity"]], "hatful":[["noun.quantity"],["hatful","containerful"]], "houseful":[["noun.quantity"],["houseful","containerful"]], "lapful":[["noun.quantity"],["lapful","containerful"]], "mouthful":[["noun.quantity"],["mouthful","containerful"]], "pail":[["noun.quantity"],["pail","pailful","containerful"]], "pipeful":[["noun.quantity"],["pipeful","containerful"]], "pocketful":[["noun.quantity"],["pocketful","containerful"]], "roomful":[["noun.quantity"],["roomful","containerful"]], "shelfful":[["noun.quantity"],["shelfful","containerful"]], "shoeful":[["noun.quantity"],["shoeful","containerful"]], "skinful":[["noun.quantity","noun.communication:slang"],["skinful","indefinite quantity"]], "skepful":[["noun.quantity"],["skepful","containerful"]], "dessertspoon":[["noun.quantity"],["dessertspoon","dessertspoonful","containerful"]], "droplet":[["noun.quantity","noun.shape:drop","noun.quantity:drop"],["droplet","drop"]], "dollop":[["noun.quantity"],["dollop","small indefinite quantity"]], "trainload":[["noun.quantity"],["trainload","load"]], "dreg":[["noun.quantity"],["dreg","small indefinite quantity"]], "tot":[["noun.quantity"],["tot","small indefinite quantity"]], "barrels":[["noun.quantity"],["barrels","large indefinite quantity"]], "billyo":[["noun.quantity"],["billyo","billyoh","billy-ho","all get out","large indefinite quantity"]], "boatload":[["noun.quantity"],["boatload","shipload","carload","large indefinite quantity"]], "haymow":[["noun.quantity"],["haymow","batch"]], "infinitude":[["noun.quantity"],["infinitude","large indefinite quantity"]], "much":[["noun.quantity"],["much","large indefinite quantity"]], "myriad":[["noun.quantity","adj.all:incalculable^myriad"],["myriad1","large indefinite quantity"]], "small fortune":[["noun.quantity"],["small fortune","large indefinite quantity"]], "tons":[["noun.quantity"],["tons","dozens","heaps","lots","piles","scores","stacks","loads","rafts","slews","wads","oodles","gobs","scads","lashings","large indefinite quantity"]], "breathing room":[["noun.quantity"],["breathing room","breathing space","room"]], "houseroom":[["noun.quantity"],["houseroom","room"]], "living space":[["noun.quantity"],["living space","lebensraum","room"]], "sea room":[["noun.quantity"],["sea room","room"]], "vital capacity":[["noun.quantity","noun.cognition:diagnostic test"],["vital capacity","capacity"]], "stp":[["noun.quantity","s.t.p."],["STP","standard temperature","standard pressure"]] }
Seagat2011/NLP-Story-Engine
wn/DICT/mysql-wn-data.noun.quantity.js
JavaScript
gpl-2.0
96,743