code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Menu.ascx.cs" Inherits="WebChamCong.Menu" %> <ul id="main-nav"> <li> <a href="/Default.aspx" class="nav-top-item"> Home </a> </li> <li> <a href="/Personal.aspx" class="nav-top-item"> Personal </a> </li> <li> <a href="/Activities.aspx" class="nav-top-item"> Activities </a> </li> <li> <a href="/Contact.aspx" class="nav-top-item"> Contact </a> </li> </ul>
1041448-ec-daily-practices
trunk/Week01/EC2011-hk2-BT1-1041448/EC2011-hk2-BT1-1041448/UserControls/Menu.ascx
ASP.NET
asf20
542
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebChamCong { public partial class Menu : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } }
1041448-ec-daily-practices
trunk/Week01/EC2011-hk2-BT1-1041448/EC2011-hk2-BT1-1041448/UserControls/Menu.ascx.cs
C#
asf20
336
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace EC2011_hk2_BT1_1041448.MasterPages { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
1041448-ec-daily-practices
trunk/Week01/EC2011-hk2-BT1-1041448/EC2011-hk2-BT1-1041448/Personal.aspx.cs
C#
asf20
358
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Admin.Master" AutoEventWireup="true" CodeBehind="Personal.aspx.cs" Inherits="EC2011_hk2_BT1_1041448.MasterPages.WebForm2" %> <asp:Content ID="Content1" ContentPlaceHolderID="page_title" runat="server"> Personal page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="javascript_extenation" runat="server"> <script type="text/javascript" src="/Resources/Javascript/Admin/jquery.jflip-0.4.js"></script> <script type="text/javascript"> $(function($) { $(function() { $("#g1").jFlip(400, 400, { background: "green", cornersTop: false, scale: "fix" }) .bind("flip.jflip", function(event, index, total) { $("#l1").html("Image " + (index + 1) + " of " + total); }); }); }); </script> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="content_header" runat="server"> My Abum </asp:Content> <asp:Content ID="Content4" ContentPlaceHolderID="content" runat="server"> <asp:Panel ID="Panel1" runat="server" CssClass="content_center"> <ul id="g1"> <li> <asp:Image ID="Image1" runat="server" ImageUrl="~/Resources/Image/Gallery/Pic2.JPG" /> </li> <li> <asp:Image ID="Image2" runat="server" ImageUrl="~/Resources/Image/Gallery/Pic1.JPG"/> </li> </ul> <div id="l1"></div> </asp:Panel> </asp:Content>
1041448-ec-daily-practices
trunk/Week01/EC2011-hk2-BT1-1041448/EC2011-hk2-BT1-1041448/Personal.aspx
ASP.NET
asf20
1,613
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/Admin.Master" AutoEventWireup="true" CodeBehind="Activities.aspx.cs" Inherits="EC2011_hk2_BT1_1041448.MasterPages.WebForm3" %> <asp:Content ID="Content1" ContentPlaceHolderID="page_title" runat="server"> Activities page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="javascript_extenation" runat="server"> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="content_header" runat="server"> Activities page </asp:Content> <asp:Content ID="Content4" ContentPlaceHolderID="content" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Panel ID="Panel1" runat="server"> <div class="sub_content"> <asp:Calendar ID="Calendar1" runat="server" Width="100%" OnSelectionChanged="Calendar1OnChanged"> <TodayDayStyle BackColor="Azure" ForeColor="Red"/> </asp:Calendar> </div> </asp:Panel> <asp:Panel ID="Panel2" runat="server"> </asp:Panel> </ContentTemplate> </asp:UpdatePanel> </asp:Content>
1041448-ec-daily-practices
trunk/Week01/EC2011-hk2-BT1-1041448/EC2011-hk2-BT1-1041448/Activities.aspx
ASP.NET
asf20
1,240
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; /** * * @author Saketh Kasibatla */ import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * * @author Saketh Kasibatla */ public class MultiLineInputElement extends ScoutingElement{ private JLabel label; private JScrollPane scrolling; private JTextArea input; String name; protected boolean inComments; public MultiLineInputElement(String name) { super(); this.inComments=false; if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.input = new JTextArea(); this.scrolling = new JScrollPane(this.input); this.setLayout(new BorderLayout()); this.label.setAlignmentX(Component.LEFT_ALIGNMENT); this.input.setAlignmentX(Component.LEFT_ALIGNMENT); this.add(label,BorderLayout.WEST); this.add(scrolling,BorderLayout.CENTER); } public String getText(){ return this.label.getText(); } public String getInput(){ return this.input.getText()+"\n"; } public boolean isInComments() { return inComments; } public void setInComments(boolean inComments) { this.inComments = inComments; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MultiLineInputElement other = (MultiLineInputElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public void clear() { this.input.setText(""); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/MultiLineInputElement.java
Java
gpl3
2,242
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * This class is used with a card layout to go to the next card in the layout. * @author Saketh Kasibatla */ public class NextMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a NextButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public NextMenuItem(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic NextButton with the name "next" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public NextMenuItem(CardLayoutPacket layout) { super("next"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the next card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().next(this.layout.getParent()); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/NextMenuItem.java
Java
gpl3
1,426
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; import javax.swing.JLabel; import javax.swing.JSlider; /** * * @author Saketh Kasibatla */ public class WeightingSliderElement extends ScoutingElement{ /** * label with slider's name */ private JLabel label; /** * actual slider */ private JSlider slider; /** * the name that is displayed in the jlabel */ private String name; private int hashCode; public WeightingSliderElement(String name, int hashCode) { super(); if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.slider=new JSlider(); this.slider.setMaximum(100); this.slider.setMinimum(0); this.slider.setMajorTickSpacing(10); this.slider.setMinorTickSpacing(2); this.slider.setPaintTicks(true); this.slider.setSnapToTicks(true); this.slider.setPaintLabels(true); this.add(label); this.add(slider); this.hashCode = hashCode; } @Override public String getInput() { int value=this.slider.getValue(); return Integer.toString(value); } @Override public String getText() { return this.label.getText(); } @Override public void clear() { this.slider.setValue(50); } public void setValue(int n) { slider.setValue(n); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WeightingSliderElement other = (WeightingSliderElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } @Override public int hashCode() { return this.hashCode; } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/WeightingSliderElement.java
Java
gpl3
2,160
package com.team1160.scouting.frontend.elements; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTextField; /** * A scouting element meant to take its input in a single line. * @author Saketh Kasibatla */ public class SingleLineInputElement extends ScoutingElement{ /** * the label that displays the name of the scouting element */ private JLabel label; /** * the input text field */ private JTextField input; /** * the type of the the input. Can be INTEGER, STRING, or DOUBLE */ private int type; /** * the name that is displayed in the jlabel */ private String name; public static final int INTEGER = 1, STRING = 2, DOUBLE = 3; protected boolean inComments; protected boolean isNegative; protected boolean isTime; protected int maxTime; /** * creates a new SingleLineInputElement with the specified name and type. * if there is no : at the end of the name, one is added. * @param name the name displayed in the label. * @param type the type of input this element recieves. */ public SingleLineInputElement(String name,int type, boolean isNegative, boolean isTime, int maxTime) { super(); this.isNegative = isNegative; this.isTime =isTime; this.maxTime = maxTime; this.inComments=false; if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.input=new JTextField(); this.input.setColumns(10); // this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); // this.setBackground(Color.red); this.label.setAlignmentX(Component.LEFT_ALIGNMENT); this.input.setAlignmentX(Component.LEFT_ALIGNMENT); this.add(label); this.add(input); } public SingleLineInputElement(String name, int type, boolean isNegative){ this(name,type,isNegative, false, 0); } public SingleLineInputElement (String name, int type){ this(name, type, false, false, 0); } /** * * @return the text of the label */ public String getText(){ return this.label.getText().substring(0,this.label.getText().length()); } /** * * @return the input in the input field */ public String getInput(){ String text = this.input.getText(); if(this.isNegative){ if(text.startsWith("-")){ return text; } else{ return "-"+text; } }else if(this.isTime){ int value = Math.abs(Integer.parseInt(text)); return Integer.toString(this.maxTime-value); }else { return text; } } /** * * @return the type of input that this element takes */ public int getType() { return type; } public boolean isNegative(){ return this.isNegative; } public boolean isTime(){ return this.isTime; } public int getMaxTime(){ return this.maxTime; } public void setInComments(boolean b){ this.inComments=b; } public boolean isInComments(){ return this.inComments; } /** * tests if this element is equal to another object. * @param obj the object to test equality with * @return wether or not this equals obj */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SingleLineInputElement other = (SingleLineInputElement) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } /** * hash code method. used for identification purposes. * @return the hash code */ @Override public int hashCode() { int hash = 3; hash = 59 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } /** * resets this element. */ @Override public void clear() { this.input.setText(""); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/SingleLineInputElement.java
Java
gpl3
4,372
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * This class is used with a card layout to go to the next card in the layout. * @author Saketh Kasibatla */ public class NextButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a NextButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public NextButton(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic NextButton with the name "next" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public NextButton(CardLayoutPacket layout) { super("next"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the next card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().next(this.layout.getParent()); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/NextButton.java
Java
gpl3
1,388
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * A button like NextButton or PrevButton , but to go to a specific slide. * @author Saketh Kasibatla */ public class JumpButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * the name of the slide that the JumpButton goes to. */ String slideName; /** * creates a JumpButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param text the text displayed on the button. * @param slideName the name of the slide that the button will jump to */ public JumpButton(CardLayoutPacket layout,String text, String slideName) { super(text); this.layout = layout; this.slideName = slideName; this.addActionListener(this); } /** * when the button is clicked, will go to the indicated card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().show(this.layout.getParent(),slideName); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/JumpButton.java
Java
gpl3
1,319
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; /** * This class is used with a card layout to go to the previous card in the layout. * @author Saketh Kasibatla */ public class PrevButton extends JButton implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a PrevButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public PrevButton(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic PrevButton with the name "prev" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public PrevButton(CardLayoutPacket layout) { super("prev"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the previous card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { //cardlayout.previous(parent); this.layout.getLayout().previous(this.layout.getParent()); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/PrevButton.java
Java
gpl3
1,433
package com.team1160.scouting.frontend.elements; import java.util.Vector; import javax.swing.JComboBox; import javax.swing.JLabel; /** * A scouting element with a dropdown box which contains numbers for the user to choose from. * @author Saketh Kasibatla */ public class NumberDropDownElement extends ScoutingElement{ /** * the label that displays the name of the scouting element */ private JLabel label; /** * the input dropdown box. */ private JComboBox dropDown; /** * the lowest and highest numbers in the dropdown box. */ private int bottom,top; /** * the name that is displayed in the jlabel */ private String name; /** * Creates a new NumberDropDownElement. * @param name the name of the new element * @param bottom the lowest number in the dropdown box * @param top the highest element in the dropdown box. */ public NumberDropDownElement(String name, int bottom, int top) { super(); if(!(name.endsWith(":"))){ label=new JLabel(name+":"); this.name=name+":"; } else{ label=new JLabel(name); this.name=name; } this.bottom=bottom; this.top=top; Vector<Integer> items = new Vector<Integer>(); for(int i=bottom;i<=top;i++){ items.add(i); } this.dropDown=new JComboBox(items); this.add(this.label); this.add(this.dropDown); } /** * * @return the text of the label */ public String getText(){ return this.label.getText().substring(0,this.label.getText().length()); } /** * * @return the input in the input field */ public String getInput(){ return this.dropDown.getSelectedItem().toString(); } /** * tests if this element is equal to another object. * @param obj the object to test equality with * @return wether or not this equals obj */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final NumberDropDownElement other = (NumberDropDownElement) obj; if (this.bottom != other.bottom) { return false; } if (this.top != other.top) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } /** * hash code method. used for identification purposes. * @return the hash code */ @Override public int hashCode() { int hash = 3; hash = 97 * hash + this.bottom; hash = 97 * hash + this.top; hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } /** * resets this element. */ @Override public void clear() { this.dropDown.setSelectedItem(new Integer(1)); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/NumberDropDownElement.java
Java
gpl3
3,120
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.elements; import java.awt.Component; import java.awt.Dimension; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.table.TableCellRenderer; public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer{ public MultiLineTableCellRenderer() { setLineWrap(true); setWrapStyleWord(true); setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setFont(table.getFont()); if (hasFocus) { setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); if (table.isCellEditable(row, column)) { setForeground(UIManager.getColor("Table.focusCellForeground")); setBackground(UIManager.getColor("Table.focusCellBackground")); } } else { setBorder(new EmptyBorder(1, 2, 1, 2)); } setText((value == null) ? "" : value.toString()); int count=((String) value).split("\n").length; this.setPreferredSize(new Dimension(267,16*count)); int height_wanted = (int)getPreferredSize().getHeight(); if (height_wanted != table.getRowHeight(row)) table.setRowHeight(row, height_wanted); return this; } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/MultiLineTableCellRenderer.java
Java
gpl3
2,037
package com.team1160.scouting.frontend.elements; import java.awt.Component; import java.awt.FlowLayout; import javax.swing.JPanel; /** * abstract superclass for all xml-generated elements in the app. * @author Saketh Kasibatla */ public abstract class ScoutingElement extends JPanel{ /** * whether or not the element is weighted */ public boolean isWeighted; /** * default superconstructor for all scouting elements */ public ScoutingElement(){ this.setAlignmentX(Component.LEFT_ALIGNMENT); } /** * gets the input value of the element * @return the string value of the input */ public abstract String getInput(); /** * gets the name of the element * @return the string name of the element */ public abstract String getText(); /** * resets the element to its default state */ public abstract void clear(); }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/ScoutingElement.java
Java
gpl3
939
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * A button like NextButton or PrevButton , but to go to a specific slide. * @author Saketh Kasibatla */ public class JumpMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * the name of the slide that the JumpButton goes to. */ String slideName; /** * creates a JumpButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param text the text displayed on the button. * @param slideName the name of the slide that the button will jump to */ public JumpMenuItem(CardLayoutPacket layout,String text, String slideName) { super(text); this.layout = layout; this.slideName = slideName; this.addActionListener(this); } /** * when the button is clicked, will go to the indicated card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { this.layout.getLayout().show(this.layout.getParent(),slideName); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/JumpMenuItem.java
Java
gpl3
1,327
package com.team1160.scouting.frontend.elements; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import javax.swing.JMenuItem; /** * This class is used with a card layout to go to the previous card in the layout. * @author Saketh Kasibatla */ public class PrevMenuItem extends JMenuItem implements ActionListener{ /** * Contains the card layout and its parent. */ CardLayoutPacket layout; /** * creates a PrevButton with text name. * @param layout a CardLayoutPacket whose cards the button will flip thru. * @param name the text displayed on the button. */ public PrevMenuItem(CardLayoutPacket layout, String name) { super(name); this.layout = layout; this.addActionListener(this); } /** * creates a generic PrevButton with the name "prev" * @param layout a CardLayoutPacket whose cards the button will flip thru. */ public PrevMenuItem(CardLayoutPacket layout) { super("prev"); this.layout = layout; this.addActionListener(this); } /** * when the button is clicked, will go to the previous card. * @param e the actionevent */ public void actionPerformed(ActionEvent e) { //cardlayout.previous(parent); this.layout.getLayout().previous(this.layout.getParent()); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/elements/PrevMenuItem.java
Java
gpl3
1,471
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author sakekasi */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { try { // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } ScoutingAppWindow window = new ScoutingAppWindow(); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/Main.java
Java
gpl3
1,009
package com.team1160.scouting.frontend.resourcePackets; import java.awt.CardLayout; import java.awt.Container; /** * contains a cardlayout and its container. * @author Saketh Kasibatla */ public class CardLayoutPacket { protected CardLayout layout; protected Container parent; public CardLayoutPacket(Container parent){ layout=new CardLayout(); this.parent=parent; } public CardLayout getLayout() { return layout; } public void setLayout(CardLayout layout) { this.layout = layout; } public Container getParent() { return parent; } public void setParent(Container parent) { this.parent = parent; } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/resourcePackets/CardLayoutPacket.java
Java
gpl3
716
package com.team1160.scouting.frontend; import com.team1160.scouting.frontend.panels.CommentPanel; import com.team1160.scouting.frontend.panels.GraphPanel; import java.awt.HeadlessException; import javax.swing.JFrame; import javax.swing.JPanel; import com.team1160.scouting.frontend.panels.InitialPanel; import com.team1160.scouting.frontend.panels.MatchScoutingPanel; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import java.io.File; /** * The actual JFrame that contains the application * @author Saketh Kasibatla */ public class ScoutingAppWindow extends JFrame{ /** * the splash pane which displays the FIRST logo and 1160 logo */ private InitialPanel splash; private MatchScoutingPanel match; /** * Contains the card layout and its parent. */ private CardLayoutPacket layout; /** * the panel upon which the cardlayout will change panels. */ private JPanel cards; private GraphPanel graph; private CommentPanel comment; /** * makes a new window * @param title the title of the window * @throws HeadlessException */ private MatchScoutingTable scoutingTable; private WeightingTable weightingTable; private DictTable dictTable; private CommentTable commentTable; public ScoutingAppWindow(String title) throws Exception{ super(title); this.scoutingTable = new MatchScoutingTable( "."+File.separator+"data"+File.separator+"database"); this.weightingTable = new WeightingTable( "."+File.separator+"data"+File.separator+"database"); this.dictTable = new DictTable( "."+File.separator+"data"+File.separator+"database"); this.commentTable = new CommentTable( "."+File.separator+"data"+File.separator+"database"); this.cards=new JPanel(); layout = new CardLayoutPacket(cards); cards.setLayout(this.layout.getLayout()); splash = new InitialPanel(layout); splash.setOpaque(true); match = new MatchScoutingPanel(layout, this.scoutingTable, this.weightingTable, this.dictTable, this.commentTable); graph = new GraphPanel(layout, this.scoutingTable, this.weightingTable, this.dictTable); comment = new CommentPanel(layout, this.commentTable); cards.add(splash,"splashscreen"); cards.add(match, "match"); cards.add(graph, "graph"); cards.add(comment, "comment"); this.add(cards); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(820,710); this.setVisible(true); } /** * creates a new window with the default title of 1160 Scouting App * @throws HeadlessException */ public ScoutingAppWindow() throws Exception{ this("1160 Scouting App"); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/ScoutingAppWindow.java
Java
gpl3
3,077
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.elements.MultiLineTableCellRenderer; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; /** * * @author sakekasi */ public class CommentPanel extends JPanel{ JMenuBar menubar; JToolBar toolbar; JMenu go; private final JButton refresh; private final JButton deleteData; CommentTable commentTable; JTable table; JScrollPane scroll; CardLayoutPacket layout; public CommentPanel(CardLayoutPacket layout, CommentTable commentTable) throws SQLException { this.commentTable = commentTable; this.layout = layout; this.menubar = new JMenuBar(); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.toolbar = new JToolBar(); this.toolbar.setFloatable(false); this.deleteData = new JButton("Delete Data"); this.deleteData.setMnemonic(KeyEvent.VK_D); this.deleteData.addActionListener(this.new DeleteData()); this.deleteData.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.deleteData); this.refresh = new JButton("Refresh"); this.refresh.setMnemonic(KeyEvent.VK_R); this.refresh.addActionListener(this.new Refresh()); this.refresh.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.refresh); this.table = new JTable(new CommentTableModel(this.getData())); //this.table.setDefaultRenderer(Object.class, new MultiLineTableCellRenderer()); table.getColumnModel().getColumn(2).setCellRenderer(new MultiLineTableCellRenderer()); this.scroll = new JScrollPane(this.table); this.setLayout(new BorderLayout()); JPanel top = new JPanel(new BorderLayout()); top.add(this.menubar, BorderLayout.NORTH); top.add(this.toolbar, BorderLayout.SOUTH); this.add(top, BorderLayout.NORTH); this.add(this.scroll, BorderLayout.CENTER); } public void refresh() throws SQLException{ this.remove(this.scroll); this.table=null; this.scroll = null; this.table = new JTable(new CommentTableModel(this.getData())); table.getColumnModel().getColumn(2).setCellRenderer(new MultiLineTableCellRenderer()); //this.table.setDefaultRenderer(Object.class, new MultiLineTableCellRenderer()); this.scroll = new JScrollPane(this.table); this.add(this.scroll, BorderLayout.CENTER); this.validate(); } protected ArrayList<ArrayList<String>> getData() throws SQLException{ List<Integer> teams = this.commentTable.getTeams(); ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); for(Integer t:teams){ Map<Integer, String> comments = this.commentTable.getComments(t); for(Integer m:comments.keySet()){ ArrayList<String> row = new ArrayList<String>(); row.add(t.toString()); row.add(m.toString()); row.add(comments.get(m)); data.add(row); } } return data; } class Refresh implements ActionListener{ public void actionPerformed(ActionEvent e) { try { CommentPanel.this.refresh(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } class DeleteData implements ActionListener{ public void actionPerformed(ActionEvent e) { Object[] options = {"Continue", "Gancel"}; boolean contin = JOptionPane.showOptionDialog( CommentPanel.this, "Pressing \'Continue\' will permanently delete your data.", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[1])==0; if(contin){ try { CommentPanel.this.commentTable.reset(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } class CommentTableModel extends AbstractTableModel{ String columnNames[]={"Team #","Match #","Comment"}; ArrayList<ArrayList<String>> data; public CommentTableModel(ArrayList<ArrayList<String>> data) { this.data = data; } public int getRowCount() { return this.data.size(); } public int getColumnCount() { return this.columnNames.length; } public Object getValueAt(int rowIndex, int columnIndex) { return this.data.get(rowIndex).get(columnIndex); } @Override public boolean isCellEditable(int row, int col){ return false; } @Override public String getColumnName (int col) { return this.columnNames[col]; } } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/panels/CommentPanel.java
Java
gpl3
6,270
package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JToolBar; import com.team1160.scouting.frontend.elements.NextButton; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import java.awt.event.KeyEvent; import javax.swing.JMenu; import javax.swing.JMenuBar; /** * the splash panel of the app. * only has an image and a next button.<br><br><br> * * * * @author Saketh Kasibatla */ public class InitialPanel extends JPanel{ /** * the toolbar displayed at the top. */ JMenuBar toolbar; /** * the panel containing the pictures under the toolbar */ JPanel picturepanel; /** * the layout packet containing the cardlayout for the next button. */ CardLayoutPacket layout; JMenu go; /** * creates a new splash panel. * @param layout the layout packet to add to the button. */ public InitialPanel(CardLayoutPacket layout) { this.layout = layout; this.setLayout(new BorderLayout()); toolbar = new JMenuBar(); toolbar.setLayout(new BorderLayout()); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); // this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); toolbar.add(this.go,BorderLayout.WEST); this.add(toolbar,BorderLayout.NORTH); picturepanel=new JPanel(); ImageIcon image = new ImageIcon("image.png"); picturepanel.add(new JLabel(image/*"1160 Scouting App"*/)); picturepanel.setOpaque(true); this.add(picturepanel,BorderLayout.CENTER); this.setPreferredSize(new Dimension(800,600)); } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/panels/InitialPanel.java
Java
gpl3
2,083
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.sql.SQLException; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.GroupedStackedBarRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; /** * * @author saketh */ public class GraphPanel extends JPanel{ CardLayoutPacket layout; JMenuBar menubar; JToolBar toolbar; JMenu go; private final JButton refresh; private final JButton deleteData; MatchScoutingTable matchTable; WeightingTable weightingTable; DictTable dictTable; JFreeChart chart; ChartPanel chartPanel; JScrollPane scroll; private final GroupedStackedBarRenderer renderer; final int preferredHeight = 600; Dimension preferredSize; public GraphPanel(CardLayoutPacket layout, MatchScoutingTable match, WeightingTable weight, DictTable dict) throws SQLException{ this.matchTable = match; this.weightingTable = weight; this.dictTable = dict; this.menubar = new JMenuBar(); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Match Scouting","match")); //this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); this.toolbar = new JToolBar(); this.toolbar.setFloatable(false); this.deleteData = new JButton("Delete Data"); this.deleteData.setMnemonic(KeyEvent.VK_D); this.deleteData.addActionListener(this.new DeleteData()); this.deleteData.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.deleteData); this.refresh = new JButton("Refresh"); this.refresh.setMnemonic(KeyEvent.VK_R); this.refresh.addActionListener(this.new Refresh()); this.refresh.setSize(100, this.menubar.getHeight()); this.toolbar.add(this.refresh); JPanel top = new JPanel(); top.setLayout(new BorderLayout()); top.add(this.menubar); this.menubar.add(this.go, BorderLayout.NORTH); top.add(this.toolbar, BorderLayout.SOUTH); this.chart = ChartFactory.createStackedBarChart( "Team Rankings", "Team Number", "Score", this.createDataSet(), PlotOrientation.VERTICAL, true, true, false); this.renderer = new GroupedStackedBarRenderer(); this.chartPanel = new ChartPanel(this.chart); this.scroll = new JScrollPane(this.chartPanel); this.chartPanel.setPreferredSize(preferredSize); this.setLayout(new BorderLayout()); this.add(top, BorderLayout.NORTH); this.add(this.scroll, BorderLayout.CENTER); } protected CategoryDataset createDataSet() throws SQLException { DefaultCategoryDataset data = new DefaultCategoryDataset(); Map<String,Integer> dict; Map<Integer, String> reverseDict; List<Integer> teams; Map<Integer, Integer> weights; teams = this.matchTable.getTeams(); dict = this.dictTable.getValuesName(); reverseDict = this.dictTable.getValuesID(); weights = this.weightingTable.getValues(); if(weights.keySet().isEmpty()){ weights = new LinkedHashMap<Integer, Integer>(); for(Integer i:reverseDict.keySet()){ weights.put(i,50); } } Map<Integer, Double> teamToOverallScore = new HashMap<Integer, Double>(); Map<Integer, LinkedHashMap<String, Double>> teamToValues = new HashMap<Integer, LinkedHashMap<String, Double>>(); ValueComparator vc = new ValueComparator(teamToOverallScore); TreeMap<Integer, Double> teamSorted = new TreeMap(vc); for(Integer t:teams){ LinkedHashMap<String, Double> values = new LinkedHashMap<String, Double>(); for(String n:dict.keySet()){ int value = this.matchTable.getAverageValue(t, dict.get(n)); double weight = (weights.get(dict.get(n))); weight /=100; double weightedValue = value * weight; values.put(n, weightedValue); // } double overallScore = 0; for(String s:values.keySet()){ overallScore+=values.get(s); } teamToOverallScore.put(t, overallScore); teamToValues.put(t, values); } teamSorted.putAll(teamToOverallScore); for(Integer t:teamSorted.keySet()){ for(String s:teamToValues.get(t).keySet()){ // System.out.println(s); // System.out.println(t); // System.out.println(teamToValues.get(t).get(s)); data.addValue(teamToValues.get(t).get(s), s.substring(0, s.length()-1), t.toString()); } } this.preferredSize = new Dimension(this.getPreferredWidth(teams.size()), this.preferredHeight); return data; } public void refresh() throws SQLException{ this.remove(this.scroll); this.chart = null; this.chartPanel = null; this.scroll = null; this.chart = ChartFactory.createStackedBarChart( "Team Rankings", "Team Number", "Score", this.createDataSet(), PlotOrientation.VERTICAL, true, true, false); this.chartPanel = new ChartPanel(this.chart); this.chartPanel.setPreferredSize(preferredSize); this.scroll = new JScrollPane(this.chartPanel); this.add(this.scroll, BorderLayout.CENTER); this.validate(); this.scroll.validate(); } class ValueComparator implements Comparator { Map base; public ValueComparator(Map base) { this.base = base; } public int compare(Object a, Object b) { if((Double)base.get(a) < (Double)base.get(b)) { return 1; } else if((Double)base.get(a) == (Double)base.get(b)) { return 0; } else { return -1; } } } private int getPreferredWidth(int n){ if((n<=10)&&(n>0)){ return 805; }else{ return 69+74*n+12; } } class Refresh implements ActionListener{ public void actionPerformed(ActionEvent e) { try { GraphPanel.this.refresh(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } class DeleteData implements ActionListener{ public void actionPerformed(ActionEvent e) { Object[] options = {"Continue", "Gancel"}; boolean contin = JOptionPane.showOptionDialog( GraphPanel.this, "Pressing \'Continue\' will permanently delete your data.", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[1])==0; if(contin){ try { GraphPanel.this.matchTable.reset(); GraphPanel.this.weightingTable.reset(); // GraphPanel.this.dictTable.reset(); } catch (SQLException ex) { Logger.getLogger(GraphPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/panels/GraphPanel.java
Java
gpl3
8,951
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.frontend.panels; import com.team1160.scouting.frontend.elements.JumpMenuItem; import com.team1160.scouting.frontend.elements.MultiLineInputElement; import com.team1160.scouting.frontend.elements.NextMenuItem; import com.team1160.scouting.frontend.elements.NumberDropDownElement; import com.team1160.scouting.frontend.elements.ScoutingElement; import com.team1160.scouting.frontend.elements.SingleLineInputElement; import com.team1160.scouting.frontend.elements.WeightingSliderElement; import com.team1160.scouting.frontend.resourcePackets.CardLayoutPacket; import com.team1160.scouting.h2.CommentTable; import com.team1160.scouting.h2.DictTable; import com.team1160.scouting.h2.MatchScoutingTable; import com.team1160.scouting.h2.WeightingTable; import com.team1160.scouting.xml.XMLParser; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.Border; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author sakekasi */ public class MatchScoutingPanel extends JPanel{ protected JPanel bottomPanel; protected ArrayList<ScoutingElement> elements; protected JPanel elementPanel; protected JPanel elementInputPanel; protected JPanel elementButtonPanel; protected Border elementBorder; protected ArrayList<WeightingSliderElement> weightingElements; protected JPanel weightingPanel; protected JPanel weightingInputPanel; protected JPanel weightingButtonPanel; protected Border weightingBorder; protected JMenuBar menubar; protected JMenu go; protected CardLayoutPacket layout; protected MatchScoutingTable scoutingTable; protected WeightingTable weightingTable; protected DictTable dictTable; protected CommentTable commentTable; public MatchScoutingPanel(CardLayoutPacket layout, MatchScoutingTable scouting, WeightingTable weighting, DictTable dict, CommentTable comment) throws ParserConfigurationException, SAXException, IOException, Exception { this.layout = layout; this.elements = new ArrayList<ScoutingElement>(); this.weightingElements = new ArrayList<WeightingSliderElement>(); this.setLayout(new BorderLayout()); XML xml = this.new XML(); this.scoutingTable = scouting; this.weightingTable = weighting; this.dictTable = dict; this.commentTable = comment; this.menubar = new JMenuBar(); this.menubar.setLayout(new BorderLayout()); this.go = new JMenu("Go"); this.go.setMnemonic(KeyEvent.VK_G); this.go.add(new JumpMenuItem(layout,"Graph","graph")); this.go.add(new JumpMenuItem(layout,"Comments","comment")); // this.go.add(new JumpMenuItem(layout,"Pit Scouting","pit")); this.menubar.add(this.go, BorderLayout.WEST); // this.toolbar.add(this.graph, BorderLayout.EAST); this.bottomPanel = new JPanel(); this.bottomPanel.setLayout(new GridLayout(1,2,0,0)); xml.parse(); this.elementPanel = new JPanel(); this.elementInputPanel = new JPanel(); this.elementBorder = BorderFactory.createTitledBorder("Values"); this.elementInputPanel.setLayout(new GridLayout(this.elements.size(),1,0,0)); this.elementPanel.setBorder(this.elementBorder); this.elementPanel.setLayout(new BorderLayout()); this.weightingPanel = new JPanel(); this.weightingInputPanel = new JPanel(); this.weightingBorder = BorderFactory.createTitledBorder("Weighting"); this.weightingPanel.setBorder(this.weightingBorder); this.weightingInputPanel.setLayout(new GridLayout(this.weightingElements.size(),1,0,0)); this.weightingPanel.setLayout(new BorderLayout()); for(ScoutingElement se: this.elements){ this.elementInputPanel.add(se); } for(WeightingSliderElement w: this.weightingElements){ this.weightingInputPanel.add(w); } JButton elementSubmit=new JButton("submit"),elementClear = new JButton("reset"); elementSubmit.addActionListener(this.new ElementSubmit()); elementClear.addActionListener(this.new ElementClear()); JButton weightingSubmit = new JButton("submit"), weightingClear = new JButton("reset"); weightingSubmit.addActionListener(this.new WeightingSubmit()); weightingClear.addActionListener(this.new WeightingClear()); this.elementButtonPanel = new JPanel(); // this.elementButtonPanel.setBackground(Color.red); this.weightingButtonPanel = new JPanel(); // this.weightingButtonPanel.setLayout(new GridLayout(1,2)); // this.weightingButtonPanel.setBackground(Color.red); this.elementButtonPanel.add(elementSubmit); this.elementButtonPanel.add(elementClear); this.weightingButtonPanel.add(weightingSubmit); this.weightingButtonPanel.add(weightingClear); this.elementPanel.add(new JScrollPane(this.elementInputPanel), BorderLayout.CENTER); this.elementPanel.add(this.elementButtonPanel, BorderLayout.SOUTH); this.weightingPanel.add(new JScrollPane(this.weightingInputPanel), BorderLayout.CENTER); this.weightingPanel.add(this.weightingButtonPanel, BorderLayout.SOUTH); this.bottomPanel.add(this.elementPanel); this.bottomPanel.add(this.weightingPanel); this.add(this.menubar, BorderLayout.NORTH); this.add(this.bottomPanel, BorderLayout.CENTER); } class XML{ XMLParser xml; protected XML() throws ParserConfigurationException, SAXException, IOException{ xml = new XMLParser("config.xml"); } protected void parse() throws Exception{ Element e = xml.getMatch(); elements.add(new SingleLineInputElement("Team No:", SingleLineInputElement.INTEGER)); SingleLineInputElement match = new SingleLineInputElement("Match No:", SingleLineInputElement.INTEGER); match.setInComments(true); elements.add(match); NodeList element = e.getElementsByTagName("field"); MatchScoutingPanel.this.dictTable.reset(); for(int i=0;i<element.getLength();i++){ Element el = (Element) element.item(i); String type=el.getAttribute("type"); String name=el.getAttribute("name"); String inWeight = el.getAttribute("inWeight"); if(type.equalsIgnoreCase("sIntInput")){ SingleLineInputElement se; if( (el.hasAttribute("isNegative")) && el.getAttribute("isNegative").equals("true")){ se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER, true); } else if( ((el.hasAttribute("isTime"))) && el.getAttribute("isTime").equals("true")){ int maxTime = Integer.parseInt(el.getAttribute("maxTime")); se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER, false, true, maxTime); }else { se = new SingleLineInputElement(name, SingleLineInputElement.INTEGER); } if((!(el.hasAttribute("inWeight"))) || (el.getAttribute("inWeight")).equalsIgnoreCase("true")){ weightingElements.add(new WeightingSliderElement(name, se.hashCode())); weightingElements.get(weightingElements.size()-1).setValue( MatchScoutingPanel.this.weightingTable.getValue( weightingElements.get(weightingElements.size()-1).hashCode())); MatchScoutingPanel.this.dictTable.insert(se.hashCode(), se.getText()); } se.setAlignmentX(Component.LEFT_ALIGNMENT); elements.add(se); } else if(type.equalsIgnoreCase("numDropDown")){ NumberDropDownElement ne=new NumberDropDownElement(name, Integer.parseInt(el.getAttribute("bottom")), Integer.parseInt(el.getAttribute("top"))); if((!(el.hasAttribute("inWeight"))) || (el.getAttribute("inWeight")).equalsIgnoreCase("true")){ weightingElements.add(new WeightingSliderElement(name, ne.hashCode())); weightingElements.get(weightingElements.size()-1).setValue( MatchScoutingPanel.this.weightingTable.getValue( weightingElements.get(weightingElements.size()-1).hashCode())); MatchScoutingPanel.this.dictTable.insert(ne.hashCode(), ne.getText()); } ne.setAlignmentX(Component.LEFT_ALIGNMENT); elements.add(ne); } else { throw new Exception("wrong type"); } } MultiLineInputElement comments = new MultiLineInputElement("Comments:"); comments.setInComments(true); elements.add(comments); } } class ElementSubmit implements ActionListener{ public void actionPerformed(ActionEvent ae) { ArrayList<String> values = new ArrayList<String>(); boolean error=false; for(ScoutingElement e: MatchScoutingPanel.this.elements){ if(e.getClass()== SingleLineInputElement.class){ SingleLineInputElement slie = (SingleLineInputElement) e; if(!slie.isNegative()){ error = slie.getInput().startsWith("-"); } if(slie.isTime()){ try{ int i = Integer.parseInt(slie.getInput()); error = (i>slie.getMaxTime())||(i<=0); } catch(NumberFormatException nfe){ error = true; } } } values.add(e.getInput()); } for(String s:values){ if(!s.contains("\n")){ try{ Integer.parseInt(s); }catch(NumberFormatException nfe){ error = true; } } } if(error){ JOptionPane.showMessageDialog(MatchScoutingPanel.this, "Wrong Input", "Input Error", JOptionPane.ERROR_MESSAGE); } else { for(int i=2; i<(MatchScoutingPanel.this.elements.size()-1);i++){ try { MatchScoutingPanel.this.scoutingTable.insert(Integer.parseInt(values.get(0)), MatchScoutingPanel.this.elements.get(i).hashCode(), Integer.parseInt(values.get(i))); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } try { MatchScoutingPanel.this.commentTable.insert(Integer.parseInt(values.get(0)), Integer.parseInt(values.get(1)), values.get(values.size()-1)); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } for(ScoutingElement s: MatchScoutingPanel.this.elements){ s.clear(); } } } } class ElementClear implements ActionListener{ public void actionPerformed(ActionEvent ae) { for(ScoutingElement s: MatchScoutingPanel.this.elements){ s.clear(); } } } class WeightingSubmit implements ActionListener{ public void actionPerformed(ActionEvent ae) { try { MatchScoutingPanel.this.weightingTable.reset(); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } for(WeightingSliderElement e:MatchScoutingPanel.this.weightingElements){ try { MatchScoutingPanel.this.weightingTable.insert(e.hashCode(), Integer.parseInt(e.getInput())); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } class WeightingClear implements ActionListener{ public void actionPerformed(ActionEvent ae) { for(WeightingSliderElement e:MatchScoutingPanel.this.weightingElements){ try { e.setValue(MatchScoutingPanel.this.weightingTable.getValue(e.hashCode())); } catch (SQLException ex) { Logger.getLogger(MatchScoutingPanel.class.getName()).log(Level.SEVERE, null, ex); } } } } }
1160scoutingapp
trunk/Scouting1160Frontend/src/com/team1160/scouting/frontend/panels/MatchScoutingPanel.java
Java
gpl3
14,552
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import java.util.HashMap; import java.util.Map; /** * * @author Saketh Kasibatla */ public class WeightingTable extends H2Table{ public WeightingTable(String database) throws ClassNotFoundException, SQLException{ super(database); statement.executeUpdate("create table if not exists weight(ID int,value int);"); } public void insert(int ID, int value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into weight values(?,?);"); prep.setInt(1, ID); prep.setInt(2, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public int getValue(int ID) throws SQLException{ ResultSet rs; try { rs = statement.executeQuery("select * from weight where id=" + Integer.toString(ID)); rs.next(); return rs.getInt("value"); } catch (SQLException ex) { this.insert(ID, 100); return 100; } } public Map<Integer,Integer> getValues() throws SQLException{ ResultSet rs=statement.executeQuery("select * from weight"); Map<Integer,Integer> values=new HashMap<Integer,Integer>(); while(rs.next()){ Integer key; Integer value; key=rs.getInt("ID"); value=rs.getInt("value"); values.put(key, value); } return values; } public void reset() throws SQLException{ statement.executeUpdate("Drop table weight;"); statement.executeUpdate("create table if not exists weight(ID int,value int);"); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/h2/WeightingTable.java
Java
gpl3
1,895
package com.team1160.scouting.h2; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents the h2 table that takes match scouting data input. * * ____________________________________________ * | team # (int) | type (int) | value (int) | * -------------------------------------------- * | 1. ... | 2. ... | 3. ... | * -------------------------------------------- * * 1. the team number of the inputted data * 2. the type (the hashcode of the type input) i.e: # points scored * 3. the value of the input * * @author Saketh Kasibatla */ public class MatchScoutingTable extends H2Table{ public MatchScoutingTable(String database) throws ClassNotFoundException, SQLException{ super(database); statement.executeUpdate("create table if not exists match(team int,ID int,value int);"); } /** * inserts a row into the database. * @param team the team number of the data * @param ID the ID (hashcode) of the data * @param value the data */ public void insert(int team,int ID,int value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into match values(?,?,?);"); prep.setInt(1, team); prep.setInt(2, ID); prep.setInt(3, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } /** * gets the values in the table. * @param team the team name whose values will be retrieved * @return a map containing a type and value for each data entry under the team. */ public Map<Integer,Integer> getValues(int team) throws SQLException{ ResultSet rs=statement.executeQuery("select * from match where team="+Integer.toString(team)); Map<Integer,Integer> values=new HashMap<Integer,Integer>(); while(rs.next()){ Integer key,value; key=rs.getInt("value"); value=rs.getInt("ID"); values.put(key, value); } return values; } /** * gets all values with the inputted team and ID. * @param team the team number which the values are under. * @param ID the id (hashcode) which the values are under. * @return a list of all the values. */ public List<Integer> getValues(int team,int ID) throws SQLException{ ResultSet rs=statement.executeQuery("select * from match where team="+Integer.toString(team)+"and ID="+Integer.toString(ID)); List<Integer> values=new ArrayList<Integer>(); while(rs.next()){ Integer value; value=rs.getInt("value"); values.add(value); } return values; } public int getAverageValue(int team, int ID) throws SQLException{ List<Integer> values = this.getValues(team, ID); int sum = 0; for(Integer i:values){ sum += i; } // System.out.println(team); // System.out.println(values.size()); // System.out.println(sum/(values.size())); // System.out.println("\n"); int average = (values.size()==0)?0:sum/(values.size()); return average; } public List<Integer> getTeams() throws SQLException{ ResultSet rs = statement.executeQuery("select distinct team from match"); List<Integer> teams = new ArrayList<Integer>(); while(rs.next()){ Integer team; team=rs.getInt("team"); teams.add(team); } Collections.sort(teams); return teams; } public void reset() throws SQLException{ statement.executeUpdate("Drop table match;"); statement.executeUpdate("create table if not exists match(team int,ID int,value int);"); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/h2/MatchScoutingTable.java
Java
gpl3
3,936
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * * @author sakekasi */ public class CommentTable extends H2Table{ public CommentTable(String database) throws ClassNotFoundException, SQLException { super(database); statement.executeUpdate("create table if not exists comment(team int,match int,comment varchar);"); } public void insert(int team, int match, String comment) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into comment values(?,?,?);"); prep.setInt(1, team); prep.setInt(2, match); prep.setString(3, comment); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public String getComment(int team, int match) throws SQLException{ ResultSet rs; rs = statement.executeQuery("select * from comment where team=" + Integer.toString(team) +"and match="+Integer.toString(match)); rs.next(); return rs.getString("comment"); } public Map<Integer, String> getComments(int team) throws SQLException{ ResultSet rs; rs = statement.executeQuery("select * from comment where team="+ Integer.toString(team)); Map<Integer, String> comments = new LinkedHashMap<Integer, String>(); while(rs.next()){ Integer key; String value; key=rs.getInt("match"); value=rs.getString("comment"); System.out.println(value); comments.put(key, value); } return comments; } public List<Integer> getTeams() throws SQLException{ ResultSet rs = statement.executeQuery("select distinct team from match"); List<Integer> teams = new ArrayList<Integer>(); while(rs.next()){ Integer team; team=rs.getInt("team"); teams.add(team); } Collections.sort(teams); return teams; } public void reset() throws SQLException{ statement.executeUpdate("Drop table comment;"); statement.executeUpdate("create table if not exists comment(team int,match int,comment varchar);"); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/h2/CommentTable.java
Java
gpl3
2,570
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * * @author Saketh Kasibatla */ public class DictTable extends H2Table{ public DictTable(String database) throws SQLException, ClassNotFoundException{ super(database); statement.executeUpdate("create table if not exists dictweight(ID int,value varchar);"); } public void insert(int ID, String value) throws SQLException{ PreparedStatement prep= connection.prepareStatement( "insert into dictweight values(?,?);"); prep.setInt(1, ID); prep.setString(2, value); prep.addBatch(); connection.setAutoCommit(false); prep.executeBatch(); connection.setAutoCommit(true); } public String getString(int ID) throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight where id=" +Integer.toString(ID)); return rs.getString("value"); } public String getID(String value) throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight where value=" +value); return rs.getString("ID"); } public Map<Integer,String> getValuesID() throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight"); Map<Integer,String> values=new LinkedHashMap<Integer,String>(); while(rs.next()){ Integer key; String value; key=rs.getInt("ID"); value=rs.getString("value"); values.put(key, value); } return values; } public Map<String,Integer> getValuesName() throws SQLException{ ResultSet rs=statement.executeQuery("select * from dictweight"); Map<String,Integer> values=new LinkedHashMap<String,Integer>(); while(rs.next()){ Integer key; String value; key=rs.getInt("ID"); value=rs.getString("value"); values.put(value, key); } return values; } public void reset() throws SQLException{ statement.executeUpdate("Drop table dictweight;"); statement.executeUpdate("create table if not exists dictweight(ID int,value varchar);"); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/h2/DictTable.java
Java
gpl3
2,447
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team1160.scouting.h2; import java.sql.*; import org.h2.Driver; /** * * @author Saketh Kasibatla */ public abstract class H2Table { /** * the location of the database. */ protected String database; /** * the Connection object provided (java.sql) * created from the database string. */ protected Connection connection; /** * the Statement object used to send commands * to the database. */ protected Statement statement; public H2Table(String database) throws ClassNotFoundException, SQLException{ this.database = database; Class.forName("org.h2.Driver"); connection= DriverManager.getConnection("jdbc:h2:"+database); statement=connection.createStatement(); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/h2/H2Table.java
Java
gpl3
895
package com.team1160.scouting.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * This class parses the config.xml file and returns elements which are nodes of the xml tree. * @author Saketh Kasibatla */ public class XMLParser { /** * the name of the document to be parsed. */ String documentName; /** * the file at location documentName */ File documentFile; /** * the document which is parsed by the java parsers. */ Document document; /** * creates a new XMLParser from the document name * @param documentName the name of the document to be read */ public XMLParser(String documentName) throws ParserConfigurationException, SAXException, IOException { this.documentName = documentName; documentFile = new File(documentName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); document=db.parse(documentFile); document.getDocumentElement().normalize(); } /** * gets the match node of the xml document. * @return the match subnode in the xml document */ public Element getMatch() { NodeList nodes = document.getDocumentElement().getChildNodes(); for(int i=0;i<nodes.getLength();i++){ if(nodes.item(i).getNodeType()==Node.ELEMENT_NODE){ Element e=(Element) nodes.item(i); if(e.getTagName().equals("match")){ return e; } } } throw new NullPointerException("no tag named match"); } /** * * @return the pit subnode in the xml document */ public Element getPit() { NodeList nodes = document.getDocumentElement().getChildNodes(); for(int i=0;i<nodes.getLength();i++){ if(nodes.item(i).getNodeType()==Node.ELEMENT_NODE){ Element e=(Element) nodes.item(i); if(e.getTagName().equals("pit")){ return e; } } } throw new NullPointerException("no tag named pit"); } }
1160scoutingapp
trunk/Scouting1160Backend/src/com/team1160/scouting/xml/XMLParser.java
Java
gpl3
2,494
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QLLopHoc.DoiTuongDuLieu { public class DTSinhVien { string _mSSV; public string MSSV { get { return _mSSV; } set { _mSSV = value; } } string _hoten; public string Hoten { get { return _hoten; } set { _hoten = value; } } string email; public string Email { get { return email; } set { email = value; } } string _tel; public string Tel { get { return _tel; } set { _tel = value; } } string _tenLopHoc; public string TenLopHoc { get { return _tenLopHoc; } set { _tenLopHoc = value; } } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/DoiTuongDuLieu/DTSinhVien.cs
C#
asf20
934
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QLLopHoc.DoiTuongDuLieu { public class DTLopHoc { string _maGiangVien; public string MaGiangVien { get { return _maGiangVien; } set { _maGiangVien = value; } } string _tenLopHoc; public string TenLopHoc { get { return _tenLopHoc; } set { _tenLopHoc = value; } } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/DoiTuongDuLieu/DTLopHoc.cs
C#
asf20
517
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QLLopHoc.DoiTuongDuLieu { public class DTChiTietLH { string _tenLopHoc; public string TenLopHoc { get { return _tenLopHoc; } set { _tenLopHoc = value; } } string _mSSV; public string MSSV { get { return _mSSV; } set { _mSSV = value; } } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/DoiTuongDuLieu/DTChiTietLH.cs
C#
asf20
492
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QLLopHoc.DoiTuongDuLieu { public class DTGiangVien { string mSGV; public string MSGV { get { return mSGV; } set { mSGV = value; } } string _hoten; public string Hoten { get { return _hoten; } set { _hoten = value; } } string email; public string Email { get { return email; } set { email = value; } } string _tel; public string Tel { get { return _tel; } set { _tel = value; } } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/DoiTuongDuLieu/DTGiangVien.cs
C#
asf20
762
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace QLLopHoc { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/Program.cs
C#
asf20
502
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.XuLyDuLieu; namespace QLLopHoc { public partial class frmCapNhatGV : Form { public frmCapNhatGV(DTLopHoc lh) { InitializeComponent(); lb_TenLH.Text = lh.TenLopHoc; List<DTGiangVien> dsgv = XLGiangVien.LayDSGiangVien(); cmbGiangVien.Items.AddRange(dsgv.ToArray()); cmbGiangVien.DisplayMember = "HoTen"; for (int i = 0; i < dsgv.Count; ++i) { if (dsgv[i].MSGV == lh.MaGiangVien) { cmbGiangVien.SelectedIndex = i; break; } } } private void btnBo_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } public DTLopHoc LopHoc { get { DTLopHoc lh = new DTLopHoc(); lh.TenLopHoc = lb_TenLH.Text; int idx = cmbGiangVien.SelectedIndex; if(idx>-1) lh.MaGiangVien=((DTGiangVien)cmbGiangVien.Items[idx]).MSGV; return lh; } } private void btnCapNhat_Click(object sender, EventArgs e) { if (cmbGiangVien.SelectedIndex == -1) { MessageBox.Show("Chưa có đủ thông tin."); return; } this.DialogResult = DialogResult.OK; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/frmCapNhatGV.cs
C#
asf20
1,760
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using System.Data; namespace QLLopHoc.KetNoiDatabase { public class KNGiangVien { public static DTGiangVien LayGVTuMS(string msgv) { DTGiangVien kq = null; string sql = "select * from GiangVien where MSGV='" + msgv + "'"; DataTable dt = DataAccess.execquery(sql); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; kq = new DTGiangVien(); kq.MSGV = (string)dr["MSGV"]; kq.Hoten = (string)dr["HoTen"]; kq.Email = (string)dr["Email"]; kq.Tel = (string)dr["Tel"]; } return kq; } public static bool ThemGV(DTGiangVien gv) { string sql = "INSERT INTO GiangVien(MSGV,HoTen,Email,Tel) values('" + gv.MSGV + "','" + gv.Hoten + "','" + gv.Email + "','" + gv.Tel + "')"; //string sql = "INSERT INTO GiangVien(MSGV,HoTen,Email,Tel) VALUES('" + gv.MSGV + "','" + gv.HoTen + "','" + gv.Email + "','" + gv.Tel + "')"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phuong thuc xoa 1 giang vien public static bool XoaGV(string msgv) { string sql = "DELETE from GiangVien where MSGV='" + msgv + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } public static bool CapNhatGiangVien(DTGiangVien gv) { string sql = "update GiangVien set HoTen='" + gv.Hoten + "',Email='" + gv.Email + "',Tel='" + gv.Tel + "',where MSGV='" + gv.MSGV + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phương thức lấy danh sách giảng viên public static List<DTGiangVien> LayDSGV() { List<DTGiangVien> dsgv = new List<DTGiangVien>(); string sql = "SELECT * FROM GiangVien"; DataTable dt = DataAccess.execquery(sql); DTGiangVien gv = null; foreach (DataRow dr in dt.Rows) { gv = new DTGiangVien(); gv.MSGV = (string)dr["MSGV"]; gv.Hoten = (string)dr["HoTen"]; gv.Email = (string)dr["Email"]; gv.Tel = (string)dr["Tel"]; dsgv.Add(gv); } return dsgv; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/KetNoiDatabase/KNGiangVien.cs
C#
asf20
2,766
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using System.Data; namespace QLLopHoc.KetNoiDatabase { public class KNChiTietLH { public static List<string> LayDSMaSVCuaLH(string tenLH) { List<string> kq = new List<string>(); string sql = "select MSSV from ChiTietLopHoc where TenLopHoc='" + tenLH + "'"; DataTable dt = DataAccess.execquery(sql); foreach (DataRow dr in dt.Rows) { kq.Add((string)dr["MSSV"]); } return kq; } public static List<string> LayDSMaLHCuaSV(string mssv) { List<string> kq = new List<string>(); string sql = "select TenLopHoc from ChiTietLop where MSSV='" + mssv + "'"; DataTable dt = DataAccess.execquery(sql); foreach (DataRow dr in dt.Rows) { kq.Add((string)dr["TenLopHoc"]); } return kq; } public static bool ThemChiTietLH(DTChiTietLH ctlh) { string sql = "INSERT INTO ChiTietLop(TenLopHoc,MSSV) VALUES('" + ctlh.TenLopHoc + "','" + ctlh.MSSV + "')"; //string sql = "INSERT INTO ChiTietLop(TenLopHoc,MSSV) VALUES('" + ctlh.TenLopHoc + "','" + ctlh.MSSV + "')"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phuong thuc xoa mot chi tiet lop hoc public static bool XoaChiTietLH(DTChiTietLH ctlh) { string sql = "DELETE from ChiTietLop WHERE TenLopHoc='" + ctlh.TenLopHoc + "' and MSSV='" + ctlh.MSSV + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/KetNoiDatabase/KNChiTietLH.cs
C#
asf20
1,959
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using System.Data; namespace QLLopHoc.KetNoiDatabase { public class KNSinhVien { public static DTSinhVien LaySVTuMS(string mssv) { DTSinhVien kq = null; string sql = "select * from SinhVien where mssv='" + mssv + "'"; DataTable dt = DataAccess.execquery(sql); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; kq = new DTSinhVien(); kq.MSSV = (string)dr["MSSV"]; kq.Hoten = (string)dr["HoTen"]; kq.Email = (string)dr["Email"]; kq.Tel = (string)dr["Tel"]; } return kq; } public static bool ThemSV(DTSinhVien sv) { string sql = "INSERT INTO SinhVien(MSSV,HoTen,Email,Tel) VALUES('" + sv.MSSV + "','" + sv.Hoten + "','" + sv.Email + "','" + sv.Tel + "')"; //string sql = "INSERT INTO SinhVien(MSSV,HoTen,Email,Tel) VALUES('" + sv.MSSV + "','" + sv.HoTen + "','" + sv.Email + "','" + sv.Tel + "')"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phuong thuc xoa mot sinh vien public static bool XoaSV(string mssv) { string sql = "DELETE from SinhVien where MSSV='" + mssv + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } public static bool CapNhatSinhVien(DTSinhVien sv) { string sql = "update SinhVien set HoTen='" + sv.Hoten + "',Email='" + sv.Email + "',Tel='" + sv.Tel + "',where MSSV='" + sv.MSSV + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //phuong thuc lay danh sach sinh vien public static List<DTSinhVien> LayDSSV() { List<DTSinhVien> ds = new List<DTSinhVien>(); string sql = "SELECT * FROM SinhVien"; DataTable dt = DataAccess.execquery(sql); DTSinhVien sv = null; foreach (DataRow dr in dt.Rows) { sv = new DTSinhVien(); sv.MSSV = (string)dr["MSSV"]; sv.Hoten = (string)dr["HoTen"]; sv.Email = (string)dr["Email"]; sv.Tel = (string)dr["Tel"]; ds.Add(sv); } return ds; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/KetNoiDatabase/KNSinhVien.cs
C#
asf20
2,716
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using System.Data; namespace QLLopHoc.KetNoiDatabase { public class KNLopHoc { public static List<DTLopHoc> LayDSLopHoc() { List<DTLopHoc> kq = new List<DTLopHoc>(); string sql = "select * from LopHoc"; DataTable dt = DataAccess.execquery(sql); foreach (DataRow dr in dt.Rows) { DTLopHoc lh = new DTLopHoc(); lh.MaGiangVien = (string)dr["MaGiangVien"]; lh.TenLopHoc = (string)dr["TenLopHoc"]; kq.Add(lh); } return kq; } //Phuong thuc them mot lop hoc public static bool ThemLH(DTLopHoc lh) { string sql = "INSERT INTO LopHoc(TenLopHoc,MaGiangVien) VALUES('" + lh.TenLopHoc + "','" + lh.MaGiangVien + "')"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phuong thuc xoa mot lop hoc public static bool XoaLH(string tenLH) { string sql = "DELETE from LopHoc where TenLopHoc='" + tenLH + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } public static bool CapNhatLopHoc(DTLopHoc lh) { string sql = "update LopHoc set MaGiangVien='" + lh.MaGiangVien + "'"; if (DataAccess.ExecNonQuery(sql) > 0) { return true; } return false; } //Phương thức lấy 1 lớp học theo tên public static DTLopHoc LayLopHocTheoTen(string tenLH) { DTLopHoc kq = new DTLopHoc(); string sql = "SELECT * FROM LopHoc WHERE TenLopHoc='" + tenLH + "'"; DataTable dt = DataAccess.execquery(sql); if (dt.Rows.Count == 0) { return null; } DataRow dr = dt.Rows[0]; kq.TenLopHoc = (string)dr["TenLopHoc"]; kq.MaGiangVien = (string)dr["MaGiangVien"]; return kq; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/KetNoiDatabase/KNLopHoc.cs
C#
asf20
2,353
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; namespace QLLopHoc.KetNoiDatabase { public class DataAccess { protected static string _connectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = QLLopHoc.mdb"; static OleDbConnection connection; public static void OpenConnection() { try { if (connection == null) connection = new OleDbConnection(_connectionString); connection.Open(); } catch (Exception) { } } public static void CloseConnection() { if (connection != null) connection.Close(); } public static DataTable execquery(string sql) { OpenConnection(); DataTable dt = new DataTable(); OleDbCommand command = connection.CreateCommand(); command.CommandText = sql; OleDbDataAdapter adapter = new OleDbDataAdapter(); adapter.SelectCommand = command; adapter.Fill(dt); CloseConnection(); return dt; } public static int ExecNonQuery(string sql) { OpenConnection(); OleDbCommand command = connection.CreateCommand(); command.CommandText = sql; return command.ExecuteNonQuery(); } //public static DataTable execquery(string sql) //{ // //throw new NotImplementedException(); // DataTable dt = new DataTable(); // return dt; //} } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/KetNoiDatabase/DataAccess.cs
C#
asf20
1,792
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.KetNoiDatabase; namespace QLLopHoc.XuLyDuLieu { public class XLSinhVien { //phuong thuc lay danh sach sinh vien khong thuoc lop hoc public static List<DTSinhVien> LayDSSVKhongThuocLH(string tenLH) { List<DTSinhVien> ds = KNSinhVien.LayDSSV(); //List<DTSinhVien> dssv = new List<DTSinhVien>(); List<string> dsmssv = KNChiTietLH.LayDSMaSVCuaLH(tenLH); //List<string> dsmssv = KNChiTietLH.LayDSMaSVCuaLH(tenLH); for (int i = 0; i < ds.Count; ++i) { if (dsmssv.Contains(ds[i].MSSV)) { ds.RemoveAt(i); --i; } } return ds; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/XuLyDuLieu/XLSinhVien.cs
C#
asf20
940
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.KetNoiDatabase; namespace QLLopHoc.XuLyDuLieu { public class XLGiangVien { public static DTGiangVien LayGVTuMS(string msgv) { return KNGiangVien.LayGVTuMS(msgv); } //Phương thức lấy danh sách giảng viên public static List<DTGiangVien> LayDSGiangVien() { return KNGiangVien.LayDSGV(); } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/XuLyDuLieu/XLGiangVien.cs
C#
asf20
554
using System; using System.Collections.Generic; using System.Linq; using System.Text; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.KetNoiDatabase; namespace QLLopHoc.XuLyDuLieu { public class XLLopHoc { public static List<DTLopHoc> LayDSLopHoc() { return KNLopHoc.LayDSLopHoc(); } public static List<DTSinhVien> LayDSMaSVCuaLH(string tenLH) { List<DTSinhVien> dssv = new List<DTSinhVien>(); List<string> dsmssv = KNChiTietLH.LayDSMaSVCuaLH(tenLH); foreach (string mssv in dsmssv) { DTSinhVien sv = KNSinhVien.LaySVTuMS(mssv); dssv.Add(sv); } return dssv; } //phương thức thêm 1 lớp học public static string ThemLopHoc(DTLopHoc lh) { string errorStr = ""; if (KNLopHoc.LayLopHocTheoTen(lh.TenLopHoc) != null) { errorStr += "Lớp học đã tồn tại."; return errorStr; } if (lh.MaGiangVien == "" || lh.MaGiangVien == "") { errorStr += "Chưa đủ thông tin."; return errorStr; } if (KNGiangVien.LayGVTuMS(lh.MaGiangVien) == null) { errorStr += "Giảng viên không tồn tại."; return errorStr; } if (!KNLopHoc.ThemLH(lh)) { errorStr += "Không thêm được lớp học."; } return errorStr; } //phương thức cập nhật lớp học public static string CapNhatLH(DTLopHoc lh) { string errorStr = ""; if (KNLopHoc.LayLopHocTheoTen(lh.TenLopHoc) == null) { errorStr += "Lớp học không tồn tại."; return errorStr; } if (lh.MaGiangVien == "" || lh.MaGiangVien == "") { errorStr += "Chưa đủ thông tin."; return errorStr; } if (KNGiangVien.LayGVTuMS(lh.MaGiangVien) == null) { errorStr += "Giảng viên không tồn tại."; return errorStr; } if (!KNLopHoc.CapNhatLopHoc(lh)) { errorStr += "Không cập nhật được lớp học."; } return errorStr; } //phuong thuc xoa lop hoc public static string XoaLopHoc(string tenLH) { string errorStr = ""; if (KNLopHoc.LayLopHocTheoTen(tenLH) == null) { errorStr += "Lớp học không tồn tại."; return errorStr; } if (tenLH == "") { errorStr += "Chưa đủ thông tin."; return errorStr; } if (!KNLopHoc.XoaLH(tenLH)) { errorStr += "Không xóa được lớp học."; } return errorStr; } //phuong thuc them sinh vien vao lop hoc public static string ThemSVVaoLH(string mssv, string tenLH) { string errorStr = ""; if (mssv == "" || tenLH == "") { errorStr += "Chưa đủ thông tin."; return errorStr; } if (KNLopHoc.LayLopHocTheoTen(tenLH) == null) { errorStr += "Lớp học không tồn tại."; return errorStr; } if (KNSinhVien.LaySVTuMS(mssv) == null) { errorStr += "Sinh viên không tồn tại."; return errorStr; } DTChiTietLH ctlh = new DTChiTietLH(); ctlh.MSSV = mssv; ctlh.TenLopHoc = tenLH; if (!KNChiTietLH.ThemChiTietLH(ctlh)) { errorStr += "Không thêm được sinh viên vào lớp học."; } return errorStr; } //phuong thuc xoa sinh vien cua lop hoc public static string XoaSVCuaLH(string mssv, string tenLH) { string errorStr = ""; if (mssv == "" || tenLH == "") { errorStr += "Chưa đủ thông tin."; return errorStr; } if (KNLopHoc.LayLopHocTheoTen(tenLH) == null) { errorStr += "Lớp học không tồn tại."; return errorStr; } if (KNSinhVien.LaySVTuMS(mssv) == null) { errorStr += "Sinh viên không tồn tại."; return errorStr; } DTChiTietLH ctlh = new DTChiTietLH(); ctlh.MSSV = mssv; ctlh.TenLopHoc = tenLH; if (!KNChiTietLH.XoaChiTietLH(ctlh)) { errorStr += "Không xóa được sinh viên của lớp học."; } return errorStr; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/XuLyDuLieu/XLLopHoc.cs
C#
asf20
5,340
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.XuLyDuLieu; namespace QLLopHoc { public partial class frmThemSVChoLH : Form { public frmThemSVChoLH(string tenLH) { InitializeComponent(); lvDSSV.View = View.Details; lvDSSV.MultiSelect = true; lvDSSV.GridLines = true; lvDSSV.FullRowSelect = true; lvDSSV.HeaderStyle = ColumnHeaderStyle.Nonclickable; ColumnHeader ch = new ColumnHeader(); ch.Name = "cSTT"; ch.Text = "STT"; ch.Width = 40; ch.TextAlign = HorizontalAlignment.Center; lvDSSV.Columns.Add(ch); ch = new ColumnHeader(); ch.Name = "cMSSV"; ch.Text = "MSSV"; ch.Width = 100; ch.TextAlign = HorizontalAlignment.Left; lvDSSV.Columns.Add(ch); ch = new ColumnHeader(); ch.Name = "cHoTen"; ch.Text = "Họ tên"; ch.Width = 220; ch.TextAlign = HorizontalAlignment.Left; lvDSSV.Columns.Add(ch); List<DTSinhVien> dssv = XLSinhVien.LayDSSVKhongThuocLH(tenLH); ListViewItem lvi = null; int i = 1; foreach (DTSinhVien sv in dssv) { lvi = new ListViewItem(i.ToString()); ++i; lvi.Tag = sv; lvi.SubItems.Add(sv.MSSV); lvi.SubItems.Add(sv.Hoten); lvDSSV.Items.Add(lvi); } } private void btnBo_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } public List<DTSinhVien> DSSV { get { List<DTSinhVien> ds = new List<DTSinhVien>(); ListView.SelectedListViewItemCollection dsSelect = lvDSSV.SelectedItems; foreach (ListViewItem lvi in dsSelect) { ds.Add((DTSinhVien)lvi.Tag); } return ds; } } private void btnThem_Click(object sender, EventArgs e) { if (lvDSSV.SelectedItems.Count == 0) { MessageBox.Show("Chưa có sinh viên nào được chọn!", "Error"); return; } this.DialogResult = DialogResult.OK; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/frmThemSVChoLH.cs
C#
asf20
2,787
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.XuLyDuLieu; using QLLopHoc.KetNoiDatabase; namespace QLLopHoc { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private void frmMain_Load(object sender, EventArgs e) { List<DTLopHoc> dsLH = XLLopHoc.LayDSLopHoc(); cmbDSLop.Items.AddRange(dsLH.ToArray()); cmbDSLop.DisplayMember = "TenLopHoc"; if (dsLH.Count > 0) { cmbDSLop.SelectedIndex = 0; } } private void cmbDSLop_SelectedIndexChanged(object sender, EventArgs e) { int idx = cmbDSLop.SelectedIndex; if (idx == -1) { return; } DTLopHoc lh = (DTLopHoc)cmbDSLop.Items[idx]; DTGiangVien gv = XLGiangVien.LayGVTuMS(lh.MaGiangVien); lbGVLH.Text = gv.Hoten; List<DTSinhVien> dssv = XLLopHoc.LayDSMaSVCuaLH(lh.TenLopHoc); lvDSSinhVien.Items.Clear(); ListViewItem lvi = null; int stt = 0; foreach (DTSinhVien sv in dssv) { stt++; lvi = new ListViewItem(stt.ToString()); lvi.SubItems.Add(sv.MSSV); lvi.SubItems.Add(sv.Hoten); lvi.Tag = sv; lvDSSinhVien.Items.Add(lvi); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } //private void giớiThiệuToolStripMenuItem_Click(object sender, EventArgs e) //{ // frmGioiThieu f1 = new frmGioiThieu(); // f1.ShowDialog(); //} private void btnThemLH_Click(object sender, EventArgs e) { frmThemLH frm = new frmThemLH(); if (frm.ShowDialog() == DialogResult.OK) { DTLopHoc lh = frm.LopHoc; string strError = XLLopHoc.ThemLopHoc(lh); if (strError == "") { MessageBox.Show("Đã thêm lớp học thành công!"); cmbDSLop.Items.Add(lh); return; } MessageBox.Show("Error: " + Environment.NewLine + strError); } } private void btnCapNhatGVLH_Click(object sender, EventArgs e) { object obj = cmbDSLop.SelectedItem; if (obj == null) { MessageBox.Show("Chưa chọn lớp học!"); return; } frmCapNhatGV frm = new frmCapNhatGV((DTLopHoc)obj); if (frm.ShowDialog() == DialogResult.OK) { DTLopHoc lh = frm.LopHoc; string strError = XLLopHoc.CapNhatLH(lh); if (strError == "") { MessageBox.Show("Đã cập nhật lớp học thành công!"); DTGiangVien gv = XLGiangVien.LayGVTuMS(lh.MaGiangVien); lbGVLH.Text = gv.Hoten; return; } MessageBox.Show("Error: "+ Environment.NewLine + strError); } } private void btnXoaLH_Click(object sender, EventArgs e) { object obj = cmbDSLop.SelectedItem; if (obj == null) { MessageBox.Show("Chưa chọn lớp học!"); return; } if (MessageBox.Show("Bạn thật sự muốn xóa lớp học?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.No) { return; } string strError = XLLopHoc.XoaLopHoc(((DTLopHoc)obj).TenLopHoc); if (strError == "") { MessageBox.Show(".a xoa l.p h.c thanh cong!"); cmbDSLop.Items.Remove(obj); if (cmbDSLop.Items.Count > 0) { cmbDSLop.SelectedIndex = 0; } } else { MessageBox.Show(strError, "Error"); } } private void btnThemSVLH_Click(object sender, EventArgs e) { object obj = cmbDSLop.SelectedItem; if (obj == null) { MessageBox.Show("Chưa chọn lớp học!"); return; } DTLopHoc lh = (DTLopHoc)obj; frmThemSVChoLH frm = new frmThemSVChoLH(lh.TenLopHoc); if (frm.ShowDialog() == DialogResult.OK) { List<DTSinhVien> dssv = frm.DSSV; string kq = ""; int dem = 0; ListViewItem lvi = null; int stt = lvDSSinhVien.Items.Count; foreach (DTSinhVien sv in dssv) { if (XLLopHoc.ThemSVVaoLH(sv.MSSV, lh.TenLopHoc) == "") { kq += " +" + sv.MSSV + Environment.NewLine; ++dem; ++stt; lvi = new ListViewItem(stt.ToString()); lvi.SubItems.Add(sv.MSSV); lvi.SubItems.Add(sv.Hoten); lvi.Tag = sv; lvDSSinhVien.Items.Add(lvi); } } MessageBox.Show("Đã thêm thành công " + dem.ToString() + " sinh viên vào lớp học." + Environment.NewLine + kq, "Thông báo"); } } private void btnXoaSVLH_Click(object sender, EventArgs e) { ListView.SelectedListViewItemCollection dsSelect = lvDSSinhVien.SelectedItems; if (dsSelect.Count == 0) { MessageBox.Show("Chưa chọn sinh viên!"); return; } if (MessageBox.Show("Bạn thật sự muốn xóa các sinh viên đã chọn?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.No) { return; } string tenLH = ((DTLopHoc)cmbDSLop.SelectedItem).TenLopHoc; string kq = ""; int dem = 0; DTSinhVien sv = null; foreach (ListViewItem lvi in dsSelect) { sv = (DTSinhVien)lvi.Tag; if (XLLopHoc.XoaSVCuaLH(sv.MSSV, tenLH) == "") { dem++; kq += " +" + sv.MSSV + Environment.NewLine; lvDSSinhVien.Items.Remove(lvi); } } MessageBox.Show("Đã xóa thành công " + dem.ToString() + " sinh viên của lớp học." + Environment.NewLine + kq, "Thông báo"); ListViewItem lvitemp = null; for (int i = 0; i < lvDSSinhVien.Items.Count; ++i) { lvitemp = lvDSSinhVien.Items[i]; lvitemp.Text = (i + 1).ToString(); } } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/frmMain.cs
C#
asf20
7,492
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using QLLopHoc.DoiTuongDuLieu; using QLLopHoc.XuLyDuLieu; namespace QLLopHoc { public partial class frmThemLH : Form { public frmThemLH() { InitializeComponent(); } private void frmThemLH_Load(object sender, EventArgs e) { //lấy danh sách giảng viên List<DTGiangVien> dsgv = XLGiangVien.LayDSGiangVien(); //đưa dsgv vào combobox cmbGiangVien.Items.Clear(); cmbGiangVien.Items.AddRange(dsgv.ToArray()); cmbGiangVien.DisplayMember = "HoTen"; if (cmbGiangVien.Items.Count > 0) { cmbGiangVien.SelectedIndex = 0; } } public DTLopHoc LopHoc { get { DTLopHoc lh = new DTLopHoc(); lh.TenLopHoc = txtTenLH.Text; int idx = cmbGiangVien.SelectedIndex; if (idx > -1) lh.MaGiangVien = ((DTGiangVien)cmbGiangVien.Items[idx]).MSGV; return lh; } } private void btnThem_Click(object sender, EventArgs e) { if (txtTenLH.Text == "" || cmbGiangVien.SelectedIndex == -1) { MessageBox.Show("Chưa có đủ thông tin."); return; } this.DialogResult = DialogResult.OK; } private void btnBo_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } } }
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/frmThemLH.cs
C#
asf20
1,852
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("QLLopHoc")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("KHTN")] [assembly: AssemblyProduct("QLLopHoc")] [assembly: AssemblyCopyright("Copyright © KHTN 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("51d02531-9789-4f51-bb03-b0f5a9404206")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
09tc-nhom-01
trunk/source/QLLopHoc/QLLopHoc/Properties/AssemblyInfo.cs
C#
asf20
1,436
<?php return array( //'配置项'=>'配置值' ); ?>
02ff2617f642eb2c
trunk/core/jadmin/Conf/config.php
PHP
asf20
53
<?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends Action{ public function index(){ header("Content-Type:text/html; charset=utf-8"); echo "<div style='font-weight:normal;color:blue;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;font-size:14px;font-family:Tahoma'>^_^ Hello,欢迎使用<span style='font-weight:bold;color:red'>ThinkPHP</span></div>"; } } ?>
02ff2617f642eb2c
trunk/core/jadmin/Lib/Action/IndexAction.class.php
PHP
asf20
470
<?php $con=require 'config.php'; $fig=array( //分组配置 'DEFAULT_GROUP'=>'Index',//Home将用作用户中心 /** * Index:默认分组,即“信息分组” * Home:用户个人中心 * Help:帮助分组,即FAQ系统 * About:内容管理系统 * Agent:代理(?用拼音) * Public:公用操作----是不是可以不用分组? */ 'APP_GROUP_LIST'=>'Agent,Bank,Help,Home,Index,Info,Share,Shop,Wap,Show', //'URL_ROUTER_ON'=>true, 'URL_CASE_INSENSITIVE'=>true, 'URL_MODEL'=>2, 'URL_PATHINFO_DEPR'=>'/', 'URL_HTML_SUFFIX'=>'.html', //'THEME'=>'default', 'DEFAULT_THEME'=>'simple', //'DEFAULT_THEME'=>'default', 'DATA_CACHE_SUBDIR'=>true, 'DATA_PATH_LEVEL'=>2, ); return array_merge($con,$fig); ?>
02ff2617f642eb2c
trunk/core/jzg/Conf/config.php
PHP
asf20
827
<?php // 本类由系统自动生成,仅供测试用途 class IndexAction extends Action{ public function index(){ header("Content-Type:text/html; charset=utf-8"); echo "<div style='font-weight:normal;color:blue;float:left;width:345px;text-align:center;border:1px solid silver;background:#E8EFFF;padding:8px;font-size:14px;font-family:Tahoma'>^_^ Hello,欢迎使用<span style='font-weight:bold;color:red'>ThinkPHP</span></div>"; } } ?>
02ff2617f642eb2c
trunk/core/jzg/Lib/Action/IndexAction.class.php
PHP
asf20
470
/** Automatically generated file. DO NOT MODIFY */ package com.example.testgps; public final class BuildConfig { public final static boolean DEBUG = true; }
0v3r-sandbox
testGPS/gen/com/example/testgps/BuildConfig.java
Java
gpl3
161
package com.example.testgps; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; private LocationManager locationManager; private String provider; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); latituteField = (TextView) findViewById(R.id.TextView02); longitudeField = (TextView) findViewById(R.id.TextView04); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the locatioin provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); // Initialize the location fields if (location != null) { System.out.println("Provider " + provider + " has been selected."); double lat = (double) (location.getLatitude()); double lng = (double) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } else { latituteField.setText("Provider not available"); longitudeField.setText("Provider not available"); } } /* Request updates at startup */ @Override protected void onResume() { super.onResume(); locationManager.requestLocationUpdates(provider, 400, 1, this); } /* Remove the locationlistener updates when Activity is paused */ @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); } public void onLocationChanged(Location location) { double lat = (double) (location.getLatitude()); double lng = (double) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { Toast.makeText(this, "Enabled new provider " + provider, Toast.LENGTH_SHORT).show(); } public void onProviderDisabled(String provider) { Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show(); } }
0v3r-sandbox
testGPS/src/com/example/testgps/MainActivity.java
Java
gpl3
2,627
<?php echo'HELLO ====>'; echo "da chinh sua"; ?>
123456t
trunk/hello.php
PHP
asf20
53
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" "fmt" "os" ) // A Domain represents a Version 2 domain type Domain byte // Domain constants for DCE Security (Version 2) UUIDs. const ( Person = Domain(0) Group = Domain(1) Org = Domain(2) ) // NewDCESecurity returns a DCE Security (Version 2) UUID. // // The domain should be one of Person, Group or Org. // On a POSIX system the id should be the users UID for the Person // domain and the users GID for the Group. The meaning of id for // the domain Org or on non-POSIX systems is site defined. // // For a given domain/id pair the same token may be returned for up to // 7 minutes and 10 seconds. func NewDCESecurity(domain Domain, id uint32) UUID { uuid := NewUUID() if uuid != nil { uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 uuid[9] = byte(domain) binary.BigEndian.PutUint32(uuid[0:], id) } return uuid } // NewDCEPerson returns a DCE Security (Version 2) UUID in the person // domain with the id returned by os.Getuid. // // NewDCEPerson(Person, uint32(os.Getuid())) func NewDCEPerson() UUID { return NewDCESecurity(Person, uint32(os.Getuid())) } // NewDCEGroup returns a DCE Security (Version 2) UUID in the group // domain with the id returned by os.Getgid. // // NewDCEGroup(Group, uint32(os.Getgid())) func NewDCEGroup() UUID { return NewDCESecurity(Group, uint32(os.Getgid())) } // Domain returns the domain for a Version 2 UUID or false. func (uuid UUID) Domain() (Domain, bool) { if v, _ := uuid.Version(); v != 2 { return 0, false } return Domain(uuid[9]), true } // Id returns the id for a Version 2 UUID or false. func (uuid UUID) Id() (uint32, bool) { if v, _ := uuid.Version(); v != 2 { return 0, false } return binary.BigEndian.Uint32(uuid[0:4]), true } func (d Domain) String() string { switch d { case Person: return "Person" case Group: return "Group" case Org: return "Org" } return fmt.Sprintf("Domain%d", int(d)) }
05yohn-go-uuid
uuid/dce.go
Go
bsd
2,098
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "crypto/md5" "crypto/sha1" "hash" ) // Well known Name Space IDs and UUIDs var ( NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8") NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8") NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8") NIL = Parse("00000000-0000-0000-0000-000000000000") ) // NewHash returns a new UUID dervied from the hash of space concatenated with // data generated by h. The hash should be at least 16 byte in length. The // first 16 bytes of the hash are used to form the UUID. The version of the // UUID will be the lower 4 bits of version. NewHash is used to implement // NewMD5 and NewSHA1. func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { h.Reset() h.Write(space) h.Write([]byte(data)) s := h.Sum(nil) uuid := make([]byte, 16) copy(uuid, s) uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant return uuid } // NewMD5 returns a new MD5 (Version 3) UUID based on the // supplied name space and data. // // NewHash(md5.New(), space, data, 3) func NewMD5(space UUID, data []byte) UUID { return NewHash(md5.New(), space, data, 3) } // NewSHA1 returns a new SHA1 (Version 5) UUID based on the // supplied name space and data. // // NewHash(sha1.New(), space, data, 5) func NewSHA1(space UUID, data []byte) UUID { return NewHash(sha1.New(), space, data, 5) }
05yohn-go-uuid
uuid/hash.go
Go
bsd
1,673
// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" "sync" "time" ) // A Time represents a time as the number of 100's of nanoseconds since 15 Oct // 1582. type Time int64 const ( lillian = 2299160 // Julian day of 15 Oct 1582 unix = 2440587 // Julian day of 1 Jan 1970 epoch = unix - lillian // Days between epochs g1582 = epoch * 86400 // seconds between epochs g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs ) var ( mu sync.Mutex lasttime uint64 // last time we returned clock_seq uint16 // clock sequence for this run timeNow = time.Now // for testing ) // UnixTime converts t the number of seconds and nanoseconds using the Unix // epoch of 1 Jan 1970. func (t Time) UnixTime() (sec, nsec int64) { sec = int64(t - g1582ns100) nsec = (sec % 10000000) * 100 sec /= 10000000 return sec, nsec } // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and // adjusts the clock sequence as needed. An error is returned if the current // time cannot be determined. func GetTime() (Time, error) { defer mu.Unlock() mu.Lock() return getTime() } func getTime() (Time, error) { t := timeNow() // If we don't have a clock sequence already, set one. if clock_seq == 0 { setClockSequence(-1) } now := uint64(t.UnixNano()/100) + g1582ns100 // If time has gone backwards with this clock sequence then we // increment the clock sequence if now <= lasttime { clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000 } lasttime = now return Time(now), nil } // ClockSequence returns the current clock sequence, generating one if not // already set. The clock sequence is only used for Version 1 UUIDs. // // The uuid package does not use global static storage for the clock sequence or // the last time a UUID was generated. Unless SetClockSequence a new random // clock sequence is generated the first time a clock sequence is requested by // ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated // for func ClockSequence() int { defer mu.Unlock() mu.Lock() return clockSequence() } func clockSequence() int { if clock_seq == 0 { setClockSequence(-1) } return int(clock_seq & 0x3fff) } // SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to // -1 causes a new sequence to be generated. func SetClockSequence(seq int) { defer mu.Unlock() mu.Lock() setClockSequence(seq) } func setClockSequence(seq int) { if seq == -1 { var b [2]byte randomBits(b[:]) // clock sequence seq = int(b[0])<<8 | int(b[1]) } old_seq := clock_seq clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant if old_seq != clock_seq { lasttime = 0 } } // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in // uuid. It returns false if uuid is not valid. The time is only well defined // for version 1 and 2 UUIDs. func (uuid UUID) Time() (Time, bool) { if len(uuid) != 16 { return 0, false } time := int64(binary.BigEndian.Uint32(uuid[0:4])) time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 return Time(time), true } // ClockSequence returns the clock sequence encoded in uuid. It returns false // if uuid is not valid. The clock sequence is only well defined for version 1 // and 2 UUIDs. func (uuid UUID) ClockSequence() (int, bool) { if len(uuid) != 16 { return 0, false } return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true }
05yohn-go-uuid
uuid/time.go
Go
bsd
3,665
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "bytes" "crypto/rand" "fmt" "io" "strings" ) // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC // 4122. type UUID []byte // A Version represents a UUIDs version. type Version byte // A Variant represents a UUIDs variant. type Variant byte // Constants returned by Variant. const ( Invalid = Variant(iota) // Invalid UUID RFC4122 // The variant specified in RFC4122 Reserved // Reserved, NCS backward compatibility. Microsoft // Reserved, Microsoft Corporation backward compatibility. Future // Reserved for future definition. ) var rander = rand.Reader // random function // New returns a new random (version 4) UUID as a string. It is a convenience // function for NewRandom().String(). func New() string { return NewRandom().String() } // Parse decodes s into a UUID or returns nil. Both the UUID form of // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded. func Parse(s string) UUID { if len(s) == 36+9 { if strings.ToLower(s[:9]) != "urn:uuid:" { return nil } s = s[9:] } else if len(s) != 36 { return nil } if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return nil } uuid := make([]byte, 16) for i, x := range []int{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { if v, ok := xtob(s[x:]); !ok { return nil } else { uuid[i] = v } } return uuid } // Equal returns true if uuid1 and uuid2 are equal. func Equal(uuid1, uuid2 UUID) bool { return bytes.Equal(uuid1, uuid2) } // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // , or "" if uuid is invalid. func (uuid UUID) String() string { if uuid == nil || len(uuid) != 16 { return "" } b := []byte(uuid) return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } // URN returns the RFC 2141 URN form of uuid, // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. func (uuid UUID) URN() string { if uuid == nil || len(uuid) != 16 { return "" } b := []byte(uuid) return fmt.Sprintf("urn:uuid:%08x-%04x-%04x-%04x-%012x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } // Variant returns the variant encoded in uuid. It returns Invalid if // uuid is invalid. func (uuid UUID) Variant() Variant { if len(uuid) != 16 { return Invalid } switch { case (uuid[8] & 0xc0) == 0x80: return RFC4122 case (uuid[8] & 0xe0) == 0xc0: return Microsoft case (uuid[8] & 0xe0) == 0xe0: return Future default: return Reserved } panic("unreachable") } // Version returns the verison of uuid. It returns false if uuid is not // valid. func (uuid UUID) Version() (Version, bool) { if len(uuid) != 16 { return 0, false } return Version(uuid[6] >> 4), true } func (v Version) String() string { if v > 15 { return fmt.Sprintf("BAD_VERSION_%d", v) } return fmt.Sprintf("VERSION_%d", v) } func (v Variant) String() string { switch v { case RFC4122: return "RFC4122" case Reserved: return "Reserved" case Microsoft: return "Microsoft" case Future: return "Future" case Invalid: return "Invalid" } return fmt.Sprintf("BadVariant%d", int(v)) } // SetRand sets the random number generator to r, which implents io.Reader. // If r.Read returns an error when the package requests random data then // a panic will be issued. // // Calling SetRand with nil sets the random number generator to the default // generator. func SetRand(r io.Reader) { if r == nil { rander = rand.Reader return } rander = r }
05yohn-go-uuid
uuid/uuid.go
Go
bsd
3,806
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The uuid package generates and inspects UUIDs. // // UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services. package uuid
05yohn-go-uuid
uuid/doc.go
Go
bsd
305
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "encoding/binary" ) // NewUUID returns a Version 1 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil. func NewUUID() UUID { if nodeID == nil { SetNodeInterface("") } now, err := GetTime() if err != nil { return nil } uuid := make([]byte, 16) time_low := uint32(now & 0xffffffff) time_mid := uint16((now >> 32) & 0xffff) time_hi := uint16((now >> 48) & 0x0fff) time_hi |= 0x1000 // Version 1 binary.BigEndian.PutUint32(uuid[0:], time_low) binary.BigEndian.PutUint16(uuid[4:], time_mid) binary.BigEndian.PutUint16(uuid[6:], time_hi) binary.BigEndian.PutUint16(uuid[8:], clock_seq) copy(uuid[10:], nodeID) return uuid }
05yohn-go-uuid
uuid/version1.go
Go
bsd
1,165
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import ( "io" ) // randomBits completely fills slice b with random data. func randomBits(b []byte) { if _, err := io.ReadFull(rander, b); err != nil { panic(err.Error()) // rand should never fail } } // xvalues returns the value of a byte as a hexadecimal digit or 255. var xvalues = []byte{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, } // xtob converts the the first two hex bytes of x into a byte. func xtob(x string) (byte, bool) { b1 := xvalues[x[0]] b2 := xvalues[x[1]] return (b1 << 4) | b2, b1 != 255 && b2 != 255 }
05yohn-go-uuid
uuid/util.go
Go
bsd
1,926
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid // Random returns a Random (Version 4) UUID or panics. // // The strength of the UUIDs is based on the strength of the crypto/rand // package. // // A note about uniqueness derived from from the UUID Wikipedia entry: // // Randomly generated UUIDs have 122 random bits. One's annual risk of being // hit by a meteorite is estimated to be one chance in 17 billion, that // means the probability is about 0.00000000006 (6 × 10−11), // equivalent to the odds of creating a few tens of trillions of UUIDs in a // year and having one duplicate. func NewRandom() UUID { uuid := make([]byte, 16) randomBits([]byte(uuid)) uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 return uuid }
05yohn-go-uuid
uuid/version4.go
Go
bsd
911
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package uuid import "net" var ( interfaces []net.Interface // cached list of interfaces ifname string // name of interface being used nodeID []byte // hardware for version 1 UUIDs ) // NodeInterface returns the name of the interface from which the NodeID was // derived. The interface "user" is returned if the NodeID was set by // SetNodeID. func NodeInterface() string { return ifname } // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. // If name is "" then the first usable interface found will be used or a random // Node ID will be generated. If a named interface cannot be found then false // is returned. // // SetNodeInterface never fails when name is "". func SetNodeInterface(name string) bool { if interfaces == nil { var err error interfaces, err = net.Interfaces() if err != nil && name != "" { return false } } for _, ifs := range interfaces { if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { if setNodeID(ifs.HardwareAddr) { ifname = ifs.Name return true } } } // We found no interfaces with a valid hardware address. If name // does not specify a specific interface generate a random Node ID // (section 4.1.6) if name == "" { if nodeID == nil { nodeID = make([]byte, 6) } randomBits(nodeID) return true } return false } // NodeID returns a slice of a copy of the current Node ID, setting the Node ID // if not already set. func NodeID() []byte { if nodeID == nil { SetNodeInterface("") } nid := make([]byte, 6) copy(nid, nodeID) return nid } // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes // of id are used. If id is less than 6 bytes then false is returned and the // Node ID is not set. func SetNodeID(id []byte) bool { if setNodeID(id) { ifname = "user" return true } return false } func setNodeID(id []byte) bool { if len(id) < 6 { return false } if nodeID == nil { nodeID = make([]byte, 6) } copy(nodeID, id) return true } // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is // not valid. The NodeID is only well defined for version 1 and 2 UUIDs. func (uuid UUID) NodeID() []byte { if len(uuid) != 16 { return nil } node := make([]byte, 6) copy(node, uuid[10:]) return node }
05yohn-go-uuid
uuid/node.go
Go
bsd
2,496
# coding=utf-8 # (The line above is necessary so that I can use 世界 in the # *comment* below without Python getting all bent out of shape.) # Copyright 2007-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Mercurial interface to codereview.appspot.com. To configure, set the following options in your repository's .hg/hgrc file. [extensions] codereview = path/to/codereview.py [codereview] server = codereview.appspot.com The server should be running Rietveld; see http://code.google.com/p/rietveld/. In addition to the new commands, this extension introduces the file pattern syntax @nnnnnn, where nnnnnn is a change list number, to mean the files included in that change list, which must be associated with the current client. For example, if change 123456 contains the files x.go and y.go, "hg diff @123456" is equivalent to"hg diff x.go y.go". ''' from mercurial import cmdutil, commands, hg, util, error, match from mercurial.node import nullrev, hex, nullid, short import os, re, time import stat import subprocess import threading from HTMLParser import HTMLParser # The standard 'json' package is new in Python 2.6. # Before that it was an external package named simplejson. try: # Standard location in 2.6 and beyond. import json except Exception, e: try: # Conventional name for earlier package. import simplejson as json except: try: # Was also bundled with django, which is commonly installed. from django.utils import simplejson as json except: # We give up. raise e try: hgversion = util.version() except: from mercurial.version import version as v hgversion = v.get_version() try: from mercurial.discovery import findcommonincoming except: def findcommonincoming(repo, remote): return repo.findcommonincoming(remote) # in Mercurial 1.9 the cmdutil.match and cmdutil.revpair moved to scmutil if hgversion >= '1.9': from mercurial import scmutil else: scmutil = cmdutil oldMessage = """ The code review extension requires Mercurial 1.3 or newer. To install a new Mercurial, sudo easy_install mercurial works on most systems. """ linuxMessage = """ You may need to clear your current Mercurial installation by running: sudo apt-get remove mercurial mercurial-common sudo rm -rf /etc/mercurial """ if hgversion < '1.3': msg = oldMessage if os.access("/etc/mercurial", 0): msg += linuxMessage raise util.Abort(msg) def promptyesno(ui, msg): # Arguments to ui.prompt changed between 1.3 and 1.3.1. # Even so, some 1.3.1 distributions seem to have the old prompt!?!? # What a terrible way to maintain software. try: return ui.promptchoice(msg, ["&yes", "&no"], 0) == 0 except AttributeError: return ui.prompt(msg, ["&yes", "&no"], "y") != "n" # To experiment with Mercurial in the python interpreter: # >>> repo = hg.repository(ui.ui(), path = ".") ####################################################################### # Normally I would split this into multiple files, but it simplifies # import path headaches to keep it all in one file. Sorry. import sys if __name__ == "__main__": print >>sys.stderr, "This is a Mercurial extension and should not be invoked directly." sys.exit(2) server = "codereview.appspot.com" server_url_base = None defaultcc = None contributors = {} missing_codereview = None real_rollback = None releaseBranch = None ####################################################################### # RE: UNICODE STRING HANDLING # # Python distinguishes between the str (string of bytes) # and unicode (string of code points) types. Most operations # work on either one just fine, but some (like regexp matching) # require unicode, and others (like write) require str. # # As befits the language, Python hides the distinction between # unicode and str by converting between them silently, but # *only* if all the bytes/code points involved are 7-bit ASCII. # This means that if you're not careful, your program works # fine on "hello, world" and fails on "hello, 世界". And of course, # the obvious way to be careful - use static types - is unavailable. # So the only way is trial and error to find where to put explicit # conversions. # # Because more functions do implicit conversion to str (string of bytes) # than do implicit conversion to unicode (string of code points), # the convention in this module is to represent all text as str, # converting to unicode only when calling a unicode-only function # and then converting back to str as soon as possible. def typecheck(s, t): if type(s) != t: raise util.Abort("type check failed: %s has type %s != %s" % (repr(s), type(s), t)) # If we have to pass unicode instead of str, ustr does that conversion clearly. def ustr(s): typecheck(s, str) return s.decode("utf-8") # Even with those, Mercurial still sometimes turns unicode into str # and then tries to use it as ascii. Change Mercurial's default. def set_mercurial_encoding_to_utf8(): from mercurial import encoding encoding.encoding = 'utf-8' set_mercurial_encoding_to_utf8() # Even with those we still run into problems. # I tried to do things by the book but could not convince # Mercurial to let me check in a change with UTF-8 in the # CL description or author field, no matter how many conversions # between str and unicode I inserted and despite changing the # default encoding. I'm tired of this game, so set the default # encoding for all of Python to 'utf-8', not 'ascii'. def default_to_utf8(): import sys reload(sys) # site.py deleted setdefaultencoding; get it back sys.setdefaultencoding('utf-8') default_to_utf8() ####################################################################### # Change list parsing. # # Change lists are stored in .hg/codereview/cl.nnnnnn # where nnnnnn is the number assigned by the code review server. # Most data about a change list is stored on the code review server # too: the description, reviewer, and cc list are all stored there. # The only thing in the cl.nnnnnn file is the list of relevant files. # Also, the existence of the cl.nnnnnn file marks this repository # as the one where the change list lives. emptydiff = """Index: ~rietveld~placeholder~ =================================================================== diff --git a/~rietveld~placeholder~ b/~rietveld~placeholder~ new file mode 100644 """ class CL(object): def __init__(self, name): typecheck(name, str) self.name = name self.desc = '' self.files = [] self.reviewer = [] self.cc = [] self.url = '' self.local = False self.web = False self.copied_from = None # None means current user self.mailed = False self.private = False def DiskText(self): cl = self s = "" if cl.copied_from: s += "Author: " + cl.copied_from + "\n\n" if cl.private: s += "Private: " + str(self.private) + "\n" s += "Mailed: " + str(self.mailed) + "\n" s += "Description:\n" s += Indent(cl.desc, "\t") s += "Files:\n" for f in cl.files: s += "\t" + f + "\n" typecheck(s, str) return s def EditorText(self): cl = self s = _change_prolog s += "\n" if cl.copied_from: s += "Author: " + cl.copied_from + "\n" if cl.url != '': s += 'URL: ' + cl.url + ' # cannot edit\n\n' if cl.private: s += "Private: True\n" s += "Reviewer: " + JoinComma(cl.reviewer) + "\n" s += "CC: " + JoinComma(cl.cc) + "\n" s += "\n" s += "Description:\n" if cl.desc == '': s += "\t<enter description here>\n" else: s += Indent(cl.desc, "\t") s += "\n" if cl.local or cl.name == "new": s += "Files:\n" for f in cl.files: s += "\t" + f + "\n" s += "\n" typecheck(s, str) return s def PendingText(self): cl = self s = cl.name + ":" + "\n" s += Indent(cl.desc, "\t") s += "\n" if cl.copied_from: s += "\tAuthor: " + cl.copied_from + "\n" s += "\tReviewer: " + JoinComma(cl.reviewer) + "\n" s += "\tCC: " + JoinComma(cl.cc) + "\n" s += "\tFiles:\n" for f in cl.files: s += "\t\t" + f + "\n" typecheck(s, str) return s def Flush(self, ui, repo): if self.name == "new": self.Upload(ui, repo, gofmt_just_warn=True, creating=True) dir = CodeReviewDir(ui, repo) path = dir + '/cl.' + self.name f = open(path+'!', "w") f.write(self.DiskText()) f.close() if sys.platform == "win32" and os.path.isfile(path): os.remove(path) os.rename(path+'!', path) if self.web and not self.copied_from: EditDesc(self.name, desc=self.desc, reviewers=JoinComma(self.reviewer), cc=JoinComma(self.cc), private=self.private) def Delete(self, ui, repo): dir = CodeReviewDir(ui, repo) os.unlink(dir + "/cl." + self.name) def Subject(self): s = line1(self.desc) if len(s) > 60: s = s[0:55] + "..." if self.name != "new": s = "code review %s: %s" % (self.name, s) typecheck(s, str) return s def Upload(self, ui, repo, send_mail=False, gofmt=True, gofmt_just_warn=False, creating=False, quiet=False): if not self.files and not creating: ui.warn("no files in change list\n") if ui.configbool("codereview", "force_gofmt", True) and gofmt: CheckFormat(ui, repo, self.files, just_warn=gofmt_just_warn) set_status("uploading CL metadata + diffs") os.chdir(repo.root) form_fields = [ ("content_upload", "1"), ("reviewers", JoinComma(self.reviewer)), ("cc", JoinComma(self.cc)), ("description", self.desc), ("base_hashes", ""), ] if self.name != "new": form_fields.append(("issue", self.name)) vcs = None # We do not include files when creating the issue, # because we want the patch sets to record the repository # and base revision they are diffs against. We use the patch # set message for that purpose, but there is no message with # the first patch set. Instead the message gets used as the # new CL's overall subject. So omit the diffs when creating # and then we'll run an immediate upload. # This has the effect that every CL begins with an empty "Patch set 1". if self.files and not creating: vcs = MercurialVCS(upload_options, ui, repo) data = vcs.GenerateDiff(self.files) files = vcs.GetBaseFiles(data) if len(data) > MAX_UPLOAD_SIZE: uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] else: uploaded_diff_file = [("data", "data.diff", emptydiff)] if vcs and self.name != "new": form_fields.append(("subject", "diff -r " + vcs.base_rev + " " + getremote(ui, repo, {}).path)) else: # First upload sets the subject for the CL itself. form_fields.append(("subject", self.Subject())) ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = MySend("/upload", body, content_type=ctype) patchset = None msg = response_body lines = msg.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] if response_body.startswith("Issue updated.") and quiet: pass else: ui.status(msg + "\n") set_status("uploaded CL metadata + diffs") if not response_body.startswith("Issue created.") and not response_body.startswith("Issue updated."): raise util.Abort("failed to update issue: " + response_body) issue = msg[msg.rfind("/")+1:] self.name = issue if not self.url: self.url = server_url_base + self.name if not uploaded_diff_file: set_status("uploading patches") patches = UploadSeparatePatches(issue, rpc, patchset, data, upload_options) if vcs: set_status("uploading base files") vcs.UploadBaseFiles(issue, rpc, patches, patchset, upload_options, files) if send_mail: set_status("sending mail") MySend("/" + issue + "/mail", payload="") self.web = True set_status("flushing changes to disk") self.Flush(ui, repo) return def Mail(self, ui, repo): pmsg = "Hello " + JoinComma(self.reviewer) if self.cc: pmsg += " (cc: %s)" % (', '.join(self.cc),) pmsg += ",\n" pmsg += "\n" repourl = getremote(ui, repo, {}).path if not self.mailed: pmsg += "I'd like you to review this change to\n" + repourl + "\n" else: pmsg += "Please take another look.\n" typecheck(pmsg, str) PostMessage(ui, self.name, pmsg, subject=self.Subject()) self.mailed = True self.Flush(ui, repo) def GoodCLName(name): typecheck(name, str) return re.match("^[0-9]+$", name) def ParseCL(text, name): typecheck(text, str) typecheck(name, str) sname = None lineno = 0 sections = { 'Author': '', 'Description': '', 'Files': '', 'URL': '', 'Reviewer': '', 'CC': '', 'Mailed': '', 'Private': '', } for line in text.split('\n'): lineno += 1 line = line.rstrip() if line != '' and line[0] == '#': continue if line == '' or line[0] == ' ' or line[0] == '\t': if sname == None and line != '': return None, lineno, 'text outside section' if sname != None: sections[sname] += line + '\n' continue p = line.find(':') if p >= 0: s, val = line[:p].strip(), line[p+1:].strip() if s in sections: sname = s if val != '': sections[sname] += val + '\n' continue return None, lineno, 'malformed section header' for k in sections: sections[k] = StripCommon(sections[k]).rstrip() cl = CL(name) if sections['Author']: cl.copied_from = sections['Author'] cl.desc = sections['Description'] for line in sections['Files'].split('\n'): i = line.find('#') if i >= 0: line = line[0:i].rstrip() line = line.strip() if line == '': continue cl.files.append(line) cl.reviewer = SplitCommaSpace(sections['Reviewer']) cl.cc = SplitCommaSpace(sections['CC']) cl.url = sections['URL'] if sections['Mailed'] != 'False': # Odd default, but avoids spurious mailings when # reading old CLs that do not have a Mailed: line. # CLs created with this update will always have # Mailed: False on disk. cl.mailed = True if sections['Private'] in ('True', 'true', 'Yes', 'yes'): cl.private = True if cl.desc == '<enter description here>': cl.desc = '' return cl, 0, '' def SplitCommaSpace(s): typecheck(s, str) s = s.strip() if s == "": return [] return re.split(", *", s) def CutDomain(s): typecheck(s, str) i = s.find('@') if i >= 0: s = s[0:i] return s def JoinComma(l): for s in l: typecheck(s, str) return ", ".join(l) def ExceptionDetail(): s = str(sys.exc_info()[0]) if s.startswith("<type '") and s.endswith("'>"): s = s[7:-2] elif s.startswith("<class '") and s.endswith("'>"): s = s[8:-2] arg = str(sys.exc_info()[1]) if len(arg) > 0: s += ": " + arg return s def IsLocalCL(ui, repo, name): return GoodCLName(name) and os.access(CodeReviewDir(ui, repo) + "/cl." + name, 0) # Load CL from disk and/or the web. def LoadCL(ui, repo, name, web=True): typecheck(name, str) set_status("loading CL " + name) if not GoodCLName(name): return None, "invalid CL name" dir = CodeReviewDir(ui, repo) path = dir + "cl." + name if os.access(path, 0): ff = open(path) text = ff.read() ff.close() cl, lineno, err = ParseCL(text, name) if err != "": return None, "malformed CL data: "+err cl.local = True else: cl = CL(name) if web: set_status("getting issue metadata from web") d = JSONGet(ui, "/api/" + name + "?messages=true") set_status(None) if d is None: return None, "cannot load CL %s from server" % (name,) if 'owner_email' not in d or 'issue' not in d or str(d['issue']) != name: return None, "malformed response loading CL data from code review server" cl.dict = d cl.reviewer = d.get('reviewers', []) cl.cc = d.get('cc', []) if cl.local and cl.copied_from and cl.desc: # local copy of CL written by someone else # and we saved a description. use that one, # so that committers can edit the description # before doing hg submit. pass else: cl.desc = d.get('description', "") cl.url = server_url_base + name cl.web = True cl.private = d.get('private', False) != False set_status("loaded CL " + name) return cl, '' global_status = None def set_status(s): # print >>sys.stderr, "\t", time.asctime(), s global global_status global_status = s class StatusThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # pause a reasonable amount of time before # starting to display status messages, so that # most hg commands won't ever see them. time.sleep(30) # now show status every 15 seconds while True: time.sleep(15 - time.time() % 15) s = global_status if s is None: continue if s == "": s = "(unknown status)" print >>sys.stderr, time.asctime(), s def start_status_thread(): t = StatusThread() t.setDaemon(True) # allowed to exit if t is still running t.start() class LoadCLThread(threading.Thread): def __init__(self, ui, repo, dir, f, web): threading.Thread.__init__(self) self.ui = ui self.repo = repo self.dir = dir self.f = f self.web = web self.cl = None def run(self): cl, err = LoadCL(self.ui, self.repo, self.f[3:], web=self.web) if err != '': self.ui.warn("loading "+self.dir+self.f+": " + err + "\n") return self.cl = cl # Load all the CLs from this repository. def LoadAllCL(ui, repo, web=True): dir = CodeReviewDir(ui, repo) m = {} files = [f for f in os.listdir(dir) if f.startswith('cl.')] if not files: return m active = [] first = True for f in files: t = LoadCLThread(ui, repo, dir, f, web) t.start() if web and first: # first request: wait in case it needs to authenticate # otherwise we get lots of user/password prompts # running in parallel. t.join() if t.cl: m[t.cl.name] = t.cl first = False else: active.append(t) for t in active: t.join() if t.cl: m[t.cl.name] = t.cl return m # Find repository root. On error, ui.warn and return None def RepoDir(ui, repo): url = repo.url(); if not url.startswith('file:'): ui.warn("repository %s is not in local file system\n" % (url,)) return None url = url[5:] if url.endswith('/'): url = url[:-1] typecheck(url, str) return url # Find (or make) code review directory. On error, ui.warn and return None def CodeReviewDir(ui, repo): dir = RepoDir(ui, repo) if dir == None: return None dir += '/.hg/codereview/' if not os.path.isdir(dir): try: os.mkdir(dir, 0700) except: ui.warn('cannot mkdir %s: %s\n' % (dir, ExceptionDetail())) return None typecheck(dir, str) return dir # Turn leading tabs into spaces, so that the common white space # prefix doesn't get confused when people's editors write out # some lines with spaces, some with tabs. Only a heuristic # (some editors don't use 8 spaces either) but a useful one. def TabsToSpaces(line): i = 0 while i < len(line) and line[i] == '\t': i += 1 return ' '*(8*i) + line[i:] # Strip maximal common leading white space prefix from text def StripCommon(text): typecheck(text, str) ws = None for line in text.split('\n'): line = line.rstrip() if line == '': continue line = TabsToSpaces(line) white = line[:len(line)-len(line.lstrip())] if ws == None: ws = white else: common = '' for i in range(min(len(white), len(ws))+1): if white[0:i] == ws[0:i]: common = white[0:i] ws = common if ws == '': break if ws == None: return text t = '' for line in text.split('\n'): line = line.rstrip() line = TabsToSpaces(line) if line.startswith(ws): line = line[len(ws):] if line == '' and t == '': continue t += line + '\n' while len(t) >= 2 and t[-2:] == '\n\n': t = t[:-1] typecheck(t, str) return t # Indent text with indent. def Indent(text, indent): typecheck(text, str) typecheck(indent, str) t = '' for line in text.split('\n'): t += indent + line + '\n' typecheck(t, str) return t # Return the first line of l def line1(text): typecheck(text, str) return text.split('\n')[0] _change_prolog = """# Change list. # Lines beginning with # are ignored. # Multi-line values should be indented. """ ####################################################################### # Mercurial helper functions # Get effective change nodes taking into account applied MQ patches def effective_revpair(repo): try: return scmutil.revpair(repo, ['qparent']) except: return scmutil.revpair(repo, None) # Return list of changed files in repository that match pats. # Warn about patterns that did not match. def matchpats(ui, repo, pats, opts): matcher = scmutil.match(repo, pats, opts) node1, node2 = effective_revpair(repo) modified, added, removed, deleted, unknown, ignored, clean = repo.status(node1, node2, matcher, ignored=True, clean=True, unknown=True) return (modified, added, removed, deleted, unknown, ignored, clean) # Return list of changed files in repository that match pats. # The patterns came from the command line, so we warn # if they have no effect or cannot be understood. def ChangedFiles(ui, repo, pats, opts, taken=None): taken = taken or {} # Run each pattern separately so that we can warn about # patterns that didn't do anything useful. for p in pats: modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts) redo = False for f in unknown: promptadd(ui, repo, f) redo = True for f in deleted: promptremove(ui, repo, f) redo = True if redo: modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts) for f in modified + added + removed: if f in taken: ui.warn("warning: %s already in CL %s\n" % (f, taken[f].name)) if not modified and not added and not removed: ui.warn("warning: %s did not match any modified files\n" % (p,)) # Again, all at once (eliminates duplicates) modified, added, removed = matchpats(ui, repo, pats, opts)[:3] l = modified + added + removed l.sort() if taken: l = Sub(l, taken.keys()) return l # Return list of changed files in repository that match pats and still exist. def ChangedExistingFiles(ui, repo, pats, opts): modified, added = matchpats(ui, repo, pats, opts)[:2] l = modified + added l.sort() return l # Return list of files claimed by existing CLs def Taken(ui, repo): all = LoadAllCL(ui, repo, web=False) taken = {} for _, cl in all.items(): for f in cl.files: taken[f] = cl return taken # Return list of changed files that are not claimed by other CLs def DefaultFiles(ui, repo, pats, opts): return ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) def Sub(l1, l2): return [l for l in l1 if l not in l2] def Add(l1, l2): l = l1 + Sub(l2, l1) l.sort() return l def Intersect(l1, l2): return [l for l in l1 if l in l2] def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source = hg.parseurl(ui.expandpath("default"), None)[0] try: remoteui = hg.remoteui # hg 1.6 except: remoteui = cmdutil.remoteui other = hg.repository(remoteui(repo, opts), source) if proxy is not None: os.environ['http_proxy'] = proxy return other def Incoming(ui, repo, opts): _, incoming, _ = findcommonincoming(repo, getremote(ui, repo, opts)) return incoming desc_re = '^(.+: |(tag )?(release|weekly)\.|fix build|undo CL)' desc_msg = '''Your CL description appears not to use the standard form. The first line of your change description is conventionally a one-line summary of the change, prefixed by the primary affected package, and is used as the subject for code review mail; the rest of the description elaborates. Examples: encoding/rot13: new package math: add IsInf, IsNaN net: fix cname in LookupHost unicode: update to Unicode 5.0.2 ''' def promptremove(ui, repo, f): if promptyesno(ui, "hg remove %s (y/n)?" % (f,)): if commands.remove(ui, repo, 'path:'+f) != 0: ui.warn("error removing %s" % (f,)) def promptadd(ui, repo, f): if promptyesno(ui, "hg add %s (y/n)?" % (f,)): if commands.add(ui, repo, 'path:'+f) != 0: ui.warn("error adding %s" % (f,)) def EditCL(ui, repo, cl): set_status(None) # do not show status s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)): return "change list not modified" continue # Check description. if clx.desc == '': if promptyesno(ui, "change list should have a description\nre-edit (y/n)?"): continue elif re.search('<enter reason for undo>', clx.desc): if promptyesno(ui, "change list description omits reason for undo\nre-edit (y/n)?"): continue elif not re.match(desc_re, clx.desc.split('\n')[0]): if promptyesno(ui, desc_msg + "re-edit (y/n)?"): continue # Check file list for files that need to be hg added or hg removed # or simply aren't understood. pats = ['path:'+f for f in clx.files] modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, pats, {}) files = [] for f in clx.files: if f in modified or f in added or f in removed: files.append(f) continue if f in deleted: promptremove(ui, repo, f) files.append(f) continue if f in unknown: promptadd(ui, repo, f) files.append(f) continue if f in ignored: ui.warn("error: %s is excluded by .hgignore; omitting\n" % (f,)) continue if f in clean: ui.warn("warning: %s is listed in the CL but unchanged\n" % (f,)) files.append(f) continue p = repo.root + '/' + f if os.path.isfile(p): ui.warn("warning: %s is a file but not known to hg\n" % (f,)) files.append(f) continue if os.path.isdir(p): ui.warn("error: %s is a directory, not a file; omitting\n" % (f,)) continue ui.warn("error: %s does not exist; omitting\n" % (f,)) clx.files = files cl.desc = clx.desc cl.reviewer = clx.reviewer cl.cc = clx.cc cl.files = clx.files cl.private = clx.private break return "" # For use by submit, etc. (NOT by change) # Get change list number or list of files from command line. # If files are given, make a new change list. def CommandLineCL(ui, repo, pats, opts, defaultcc=None): if len(pats) > 0 and GoodCLName(pats[0]): if len(pats) != 1: return None, "cannot specify change number and file names" if opts.get('message'): return None, "cannot use -m with existing CL" cl, err = LoadCL(ui, repo, pats[0], web=True) if err != "": return None, err else: cl = CL("new") cl.local = True cl.files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) if not cl.files: return None, "no files changed" if opts.get('reviewer'): cl.reviewer = Add(cl.reviewer, SplitCommaSpace(opts.get('reviewer'))) if opts.get('cc'): cl.cc = Add(cl.cc, SplitCommaSpace(opts.get('cc'))) if defaultcc: cl.cc = Add(cl.cc, defaultcc) if cl.name == "new": if opts.get('message'): cl.desc = opts.get('message') else: err = EditCL(ui, repo, cl) if err != '': return None, err return cl, "" # reposetup replaces cmdutil.match with this wrapper, # which expands the syntax @clnumber to mean the files # in that CL. original_match = None def ReplacementForCmdutilMatch(repo, pats=None, opts=None, globbed=False, default='relpath'): taken = [] files = [] pats = pats or [] opts = opts or {} for p in pats: if p.startswith('@'): taken.append(p) clname = p[1:] if not GoodCLName(clname): raise util.Abort("invalid CL name " + clname) cl, err = LoadCL(repo.ui, repo, clname, web=False) if err != '': raise util.Abort("loading CL " + clname + ": " + err) if not cl.files: raise util.Abort("no files in CL " + clname) files = Add(files, cl.files) pats = Sub(pats, taken) + ['path:'+f for f in files] # work-around for http://selenic.com/hg/rev/785bbc8634f8 if hgversion >= '1.9' and not hasattr(repo, 'match'): repo = repo[None] return original_match(repo, pats=pats, opts=opts, globbed=globbed, default=default) def RelativePath(path, cwd): n = len(cwd) if path.startswith(cwd) and path[n] == '/': return path[n+1:] return path def CheckFormat(ui, repo, files, just_warn=False): set_status("running gofmt") CheckGofmt(ui, repo, files, just_warn) CheckTabfmt(ui, repo, files, just_warn) # Check that gofmt run on the list of files does not change them def CheckGofmt(ui, repo, files, just_warn): files = [f for f in files if (f.startswith('src/') or f.startswith('test/bench/')) and f.endswith('.go')] if not files: return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] files = [f for f in files if os.access(f, 0)] if not files: return try: cmd = subprocess.Popen(["gofmt", "-l"] + files, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=sys.platform != "win32") cmd.stdin.close() except: raise util.Abort("gofmt: " + ExceptionDetail()) data = cmd.stdout.read() errors = cmd.stderr.read() cmd.wait() set_status("done with gofmt") if len(errors) > 0: ui.warn("gofmt errors:\n" + errors.rstrip() + "\n") return if len(data) > 0: msg = "gofmt needs to format these files (run hg gofmt):\n" + Indent(data, "\t").rstrip() if just_warn: ui.warn("warning: " + msg + "\n") else: raise util.Abort(msg) return # Check that *.[chys] files indent using tabs. def CheckTabfmt(ui, repo, files, just_warn): files = [f for f in files if f.startswith('src/') and re.search(r"\.[chys]$", f)] if not files: return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] files = [f for f in files if os.access(f, 0)] badfiles = [] for f in files: try: for line in open(f, 'r'): # Four leading spaces is enough to complain about, # except that some Plan 9 code uses four spaces as the label indent, # so allow that. if line.startswith(' ') and not re.match(' [A-Za-z0-9_]+:', line): badfiles.append(f) break except: # ignore cannot open file, etc. pass if len(badfiles) > 0: msg = "these files use spaces for indentation (use tabs instead):\n\t" + "\n\t".join(badfiles) if just_warn: ui.warn("warning: " + msg + "\n") else: raise util.Abort(msg) return ####################################################################### # Mercurial commands # every command must take a ui and and repo as arguments. # opts is a dict where you can find other command line flags # # Other parameters are taken in order from items on the command line that # don't start with a dash. If no default value is given in the parameter list, # they are required. # def change(ui, repo, *pats, **opts): """create, edit or delete a change list Create, edit or delete a change list. A change list is a group of files to be reviewed and submitted together, plus a textual description of the change. Change lists are referred to by simple alphanumeric names. Changes must be reviewed before they can be submitted. In the absence of options, the change command opens the change list for editing in the default editor. Deleting a change with the -d or -D flag does not affect the contents of the files listed in that change. To revert the files listed in a change, use hg revert @123456 before running hg change -d 123456. """ if missing_codereview: return missing_codereview dirty = {} if len(pats) > 0 and GoodCLName(pats[0]): name = pats[0] if len(pats) != 1: return "cannot specify CL name and file patterns" pats = pats[1:] cl, err = LoadCL(ui, repo, name, web=True) if err != '': return err if not cl.local and (opts["stdin"] or not opts["stdout"]): return "cannot change non-local CL " + name else: if repo[None].branch() != "default": return "cannot run hg change outside default branch" name = "new" cl = CL("new") dirty[cl] = True files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) if opts["delete"] or opts["deletelocal"]: if opts["delete"] and opts["deletelocal"]: return "cannot use -d and -D together" flag = "-d" if opts["deletelocal"]: flag = "-D" if name == "new": return "cannot use "+flag+" with file patterns" if opts["stdin"] or opts["stdout"]: return "cannot use "+flag+" with -i or -o" if not cl.local: return "cannot change non-local CL " + name if opts["delete"]: if cl.copied_from: return "original author must delete CL; hg change -D will remove locally" PostMessage(ui, cl.name, "*** Abandoned ***", send_mail=cl.mailed) EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) return if opts["stdin"]: s = sys.stdin.read() clx, line, err = ParseCL(s, name) if err != '': return "error parsing change list: line %d: %s" % (line, err) if clx.desc is not None: cl.desc = clx.desc; dirty[cl] = True if clx.reviewer is not None: cl.reviewer = clx.reviewer dirty[cl] = True if clx.cc is not None: cl.cc = clx.cc dirty[cl] = True if clx.files is not None: cl.files = clx.files dirty[cl] = True if clx.private != cl.private: cl.private = clx.private dirty[cl] = True if not opts["stdin"] and not opts["stdout"]: if name == "new": cl.files = files err = EditCL(ui, repo, cl) if err != "": return err dirty[cl] = True for d, _ in dirty.items(): name = d.name d.Flush(ui, repo) if name == "new": d.Upload(ui, repo, quiet=True) if opts["stdout"]: ui.write(cl.EditorText()) elif opts["pending"]: ui.write(cl.PendingText()) elif name == "new": if ui.quiet: ui.write(cl.name) else: ui.write("CL created: " + cl.url + "\n") return def code_login(ui, repo, **opts): """log in to code review server Logs in to the code review server, saving a cookie in a file in your home directory. """ if missing_codereview: return missing_codereview MySend(None) def clpatch(ui, repo, clname, **opts): """import a patch from the code review server Imports a patch from the code review server into the local client. If the local client has already modified any of the files that the patch modifies, this command will refuse to apply the patch. Submitting an imported patch will keep the original author's name as the Author: line but add your own name to a Committer: line. """ if repo[None].branch() != "default": return "cannot run hg clpatch outside default branch" return clpatch_or_undo(ui, repo, clname, opts, mode="clpatch") def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": return "cannot run hg undo outside default branch" return clpatch_or_undo(ui, repo, clname, opts, mode="undo") def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly. """ c = repo[None] if not releaseBranch: return "no active release branches" if c.branch() != releaseBranch: if c.modified() or c.added() or c.removed(): raise util.Abort("uncommitted local changes - cannot switch branches") err = hg.clean(repo, releaseBranch) if err: return err try: err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") if err: raise util.Abort(err) except Exception, e: hg.clean(repo, "default") raise e return None def rev2clname(rev): # Extract CL name from revision description. # The last line in the description that is a codereview URL is the real one. # Earlier lines might be part of the user-written description. all = re.findall('(?m)^http://codereview.appspot.com/([0-9]+)$', rev.description()) if len(all) > 0: return all[-1] return "" undoHeader = """undo CL %s / %s <enter reason for undo> ««« original CL description """ undoFooter = """ »»» """ backportHeader = """[%s] %s ««« CL %s / %s """ backportFooter = """ »»» """ # Implementation of clpatch/undo. def clpatch_or_undo(ui, repo, clname, opts, mode): if missing_codereview: return missing_codereview if mode == "undo" or mode == "backport": if hgversion < '1.4': # Don't have cmdutil.match (see implementation of sync command). return "hg is too old to run hg %s - update to 1.4 or newer" % mode # Find revision in Mercurial repository. # Assume CL number is 7+ decimal digits. # Otherwise is either change log sequence number (fewer decimal digits), # hexadecimal hash, or tag name. # Mercurial will fall over long before the change log # sequence numbers get to be 7 digits long. if re.match('^[0-9]{7,}$', clname): found = False matchfn = scmutil.match(repo, [], {'rev': None}) def prep(ctx, fns): pass for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep): rev = repo[ctx.rev()] # Last line with a code review URL is the actual review URL. # Earlier ones might be part of the CL description. n = rev2clname(rev) if n == clname: found = True break if not found: return "cannot find CL %s in local repository" % clname else: rev = repo[clname] if not rev: return "unknown revision %s" % clname clname = rev2clname(rev) if clname == "": return "cannot find CL name in revision description" # Create fresh CL and start with patch that would reverse the change. vers = short(rev.node()) cl = CL("new") desc = str(rev.description()) if mode == "undo": cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter else: cl.desc = (backportHeader % (releaseBranch, line1(desc), clname, vers)) + desc + undoFooter v1 = vers v0 = short(rev.parents()[0].node()) if mode == "undo": arg = v1 + ":" + v0 else: vers = v0 arg = v0 + ":" + v1 patch = RunShell(["hg", "diff", "--git", "-r", arg]) else: # clpatch cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err if patch == emptydiff: return "codereview issue %s has no diff" % clname # find current hg version (hg identify) ctx = repo[None] parents = ctx.parents() id = '+'.join([short(p.node()) for p in parents]) # if version does not match the patch version, # try to update the patch line numbers. if vers != "" and id != vers: # "vers in repo" gives the wrong answer # on some versions of Mercurial. Instead, do the actual # lookup and catch the exception. try: repo[vers].description() except: return "local repository is out of date; sync to get %s" % (vers) patch1, err = portPatch(repo, patch, vers, id) if err != "": if not opts["ignore_hgpatch_failure"]: return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id) else: patch = patch1 argv = ["hgpatch"] if opts["no_incoming"] or mode == "backport": argv += ["--checksync=false"] try: cmd = subprocess.Popen(argv, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, close_fds=sys.platform != "win32") except: return "hgpatch: " + ExceptionDetail() out, err = cmd.communicate(patch) if cmd.returncode != 0 and not opts["ignore_hgpatch_failure"]: return "hgpatch failed" cl.local = True cl.files = out.strip().split() if not cl.files and not opts["ignore_hgpatch_failure"]: return "codereview issue %s has no changed files" % clname files = ChangedFiles(ui, repo, [], opts) extra = Sub(cl.files, files) if extra: ui.warn("warning: these files were listed in the patch but not changed:\n\t" + "\n\t".join(extra) + "\n") cl.Flush(ui, repo) if mode == "undo": err = EditCL(ui, repo, cl) if err != "": return "CL created, but error editing: " + err cl.Flush(ui, repo) else: ui.write(cl.PendingText() + "\n") # portPatch rewrites patch from being a patch against # oldver to being a patch against newver. def portPatch(repo, patch, oldver, newver): lines = patch.splitlines(True) # True = keep \n delta = None for i in range(len(lines)): line = lines[i] if line.startswith('--- a/'): file = line[6:-1] delta = fileDeltas(repo, file, oldver, newver) if not delta or not line.startswith('@@ '): continue # @@ -x,y +z,w @@ means the patch chunk replaces # the original file's line numbers x up to x+y with the # line numbers z up to z+w in the new file. # Find the delta from x in the original to the same # line in the current version and add that delta to both # x and z. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) if not m: return None, "error parsing patch line numbers" n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) d, err = lineDelta(delta, n1, len1) if err != "": return "", err n1 += d n2 += d lines[i] = "@@ -%d,%d +%d,%d @@\n" % (n1, len1, n2, len2) newpatch = ''.join(lines) return newpatch, "" # fileDelta returns the line number deltas for the given file's # changes from oldver to newver. # The deltas are a list of (n, len, newdelta) triples that say # lines [n, n+len) were modified, and after that range the # line numbers are +newdelta from what they were before. def fileDeltas(repo, file, oldver, newver): cmd = ["hg", "diff", "--git", "-r", oldver + ":" + newver, "path:" + file] data = RunShell(cmd, silent_ok=True) deltas = [] for line in data.splitlines(): m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) if not m: continue n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) deltas.append((n1, len1, n2+len2-(n1+len1))) return deltas # lineDelta finds the appropriate line number delta to apply to the lines [n, n+len). # It returns an error if those lines were rewritten by the patch. def lineDelta(deltas, n, len): d = 0 for (old, oldlen, newdelta) in deltas: if old >= n+len: break if old+len > n: return 0, "patch and recent changes conflict" d = newdelta return d, "" def download(ui, repo, clname, **opts): """download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server. """ if missing_codereview: return missing_codereview cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err ui.write(cl.EditorText() + "\n") ui.write(patch + "\n") return def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if missing_codereview: return missing_codereview pats = tuple([pat] + list(pats)) if not GoodCLName(clname): return "invalid CL name " + clname dirty = {} cl, err = LoadCL(ui, repo, clname, web=False) if err != '': return err if not cl.local: return "cannot change non-local CL " + clname files = ChangedFiles(ui, repo, pats, opts) if opts["delete"]: oldfiles = Intersect(files, cl.files) if oldfiles: if not ui.quiet: ui.status("# Removing files from CL. To undo:\n") ui.status("# cd %s\n" % (repo.root)) for f in oldfiles: ui.status("# hg file %s %s\n" % (cl.name, f)) cl.files = Sub(cl.files, oldfiles) cl.Flush(ui, repo) else: ui.status("no such files in CL") return if not files: return "no such modified files" files = Sub(files, cl.files) taken = Taken(ui, repo) warned = False for f in files: if f in taken: if not warned and not ui.quiet: ui.status("# Taking files from other CLs. To undo:\n") ui.status("# cd %s\n" % (repo.root)) warned = True ocl = taken[f] if not ui.quiet: ui.status("# hg file %s %s\n" % (ocl.name, f)) if ocl not in dirty: ocl.files = Sub(ocl.files, files) dirty[ocl] = True cl.files = Add(cl.files, files) dirty[cl] = True for d, _ in dirty.items(): d.Flush(ui, repo) return def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if missing_codereview: return missing_codereview files = ChangedExistingFiles(ui, repo, pats, opts) files = [f for f in files if f.endswith(".go")] if not files: return "no modified go files" cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] try: cmd = ["gofmt", "-l"] if not opts["list"]: cmd += ["-w"] if os.spawnvp(os.P_WAIT, "gofmt", cmd + files) != 0: raise util.Abort("gofmt did not exit cleanly") except error.Abort, e: raise except: raise util.Abort("gofmt: " + ExceptionDetail()) return def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. """ if missing_codereview: return missing_codereview cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc) if err != "": return err cl.Upload(ui, repo, gofmt_just_warn=True) if not cl.reviewer: # If no reviewer is listed, assign the review to defaultcc. # This makes sure that it appears in the # codereview.appspot.com/user/defaultcc # page, so that it doesn't get dropped on the floor. if not defaultcc: return "no reviewers listed in CL" cl.cc = Sub(cl.cc, defaultcc) cl.reviewer = defaultcc cl.Flush(ui, repo) if cl.files == []: return "no changed files, not sending mail" cl.Mail(ui, repo) def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ if missing_codereview: return missing_codereview m = LoadAllCL(ui, repo, web=True) names = m.keys() names.sort() for name in names: cl = m[name] ui.write(cl.PendingText() + "\n") files = DefaultFiles(ui, repo, [], opts) if len(files) > 0: s = "Changed files not in any CL:\n" for f in files: s += "\t" + f + "\n" ui.write(s) def reposetup(ui, repo): global original_match if original_match is None: start_status_thread() original_match = scmutil.match scmutil.match = ReplacementForCmdutilMatch RietveldSetup(ui, repo) def CheckContributor(ui, repo, user=None): set_status("checking CONTRIBUTORS file") user, userline = FindContributor(ui, repo, user, warn=False) if not userline: raise util.Abort("cannot find %s in CONTRIBUTORS" % (user,)) return userline def FindContributor(ui, repo, user=None, warn=True): if not user: user = ui.config("ui", "username") if not user: raise util.Abort("[ui] username is not configured in .hgrc") user = user.lower() m = re.match(r".*<(.*)>", user) if m: user = m.group(1) if user not in contributors: if warn: ui.warn("warning: cannot find %s in CONTRIBUTORS\n" % (user,)) return user, None user, email = contributors[user] return email, "%s <%s>" % (user, email) def submit(ui, repo, *pats, **opts): """submit change to remote repository Submits change to remote repository. Bails out if the local repository is not in sync with the remote one. """ if missing_codereview: return missing_codereview # We already called this on startup but sometimes Mercurial forgets. set_mercurial_encoding_to_utf8() repo.ui.quiet = True if not opts["no_incoming"] and Incoming(ui, repo, opts): return "local repository out of date; must sync before submit" cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc) if err != "": return err user = None if cl.copied_from: user = cl.copied_from userline = CheckContributor(ui, repo, user) typecheck(userline, str) about = "" if cl.reviewer: about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n" if opts.get('tbr'): tbr = SplitCommaSpace(opts.get('tbr')) cl.reviewer = Add(cl.reviewer, tbr) about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n" if cl.cc: about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n" if not cl.reviewer: return "no reviewers listed in CL" if not cl.local: return "cannot submit non-local CL" # upload, to sync current patch and also get change number if CL is new. if not cl.copied_from: cl.Upload(ui, repo, gofmt_just_warn=True) # check gofmt for real; allowed upload to warn in order to save CL. cl.Flush(ui, repo) CheckFormat(ui, repo, cl.files) about += "%s%s\n" % (server_url_base, cl.name) if cl.copied_from: about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n" typecheck(about, str) if not cl.mailed and not cl.copied_from: # in case this is TBR cl.Mail(ui, repo) # submit changes locally date = opts.get('date') if date: opts['date'] = util.parsedate(date) typecheck(opts['date'], str) opts['message'] = cl.desc.rstrip() + "\n\n" + about typecheck(opts['message'], str) if opts['dryrun']: print "NOT SUBMITTING:" print "User: ", userline print "Message:" print Indent(opts['message'], "\t") print "Files:" print Indent('\n'.join(cl.files), "\t") return "dry run; not submitted" m = match.exact(repo.root, repo.getcwd(), cl.files) node = repo.commit(ustr(opts['message']), ustr(userline), opts.get('date'), m) if not node: return "nothing changed" # push to remote; if it fails for any reason, roll back try: log = repo.changelog rev = log.rev(node) parents = log.parentrevs(rev) if (rev-1 not in parents and (parents == (nullrev, nullrev) or len(log.heads(log.node(parents[0]))) > 1 and (parents[1] == nullrev or len(log.heads(log.node(parents[1]))) > 1))): # created new head raise util.Abort("local repository out of date; must sync before submit") # push changes to remote. # if it works, we're committed. # if not, roll back other = getremote(ui, repo, opts) r = repo.push(other, False, None) if r == 0: raise util.Abort("local repository out of date; must sync before submit") except: real_rollback() raise # we're committed. upload final patch, close review, add commit message changeURL = short(node) url = other.url() m = re.match("^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?", url) if m: changeURL = "http://code.google.com/p/%s/source/detail?r=%s" % (m.group(2), changeURL) else: print >>sys.stderr, "URL: ", url pmsg = "*** Submitted as " + changeURL + " ***\n\n" + opts['message'] # When posting, move reviewers to CC line, # so that the issue stops showing up in their "My Issues" page. PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc)) if not cl.copied_from: EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) c = repo[None] if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed(): ui.write("switching from %s to default branch.\n" % releaseBranch) err = hg.clean(repo, "default") if err: return err return None def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if missing_codereview: return missing_codereview if not opts["local"]: ui.status = sync_note ui.note = sync_note other = getremote(ui, repo, opts) modheads = repo.pull(other) err = commands.postincoming(ui, repo, modheads, True, "tip") if err: return err commands.update(ui, repo, rev="default") sync_changes(ui, repo) def sync_note(msg): # we run sync (pull -u) in verbose mode to get the # list of files being updated, but that drags along # a bunch of messages we don't care about. # omit them. if msg == 'resolving manifests\n': return if msg == 'searching for changes\n': return if msg == "couldn't find merge tool hgmerge\n": return sys.stdout.write(msg) def sync_changes(ui, repo): # Look through recent change log descriptions to find # potential references to http://.*/our-CL-number. # Double-check them by looking at the Rietveld log. def Rev(rev): desc = repo[rev].description().strip() for clname in re.findall('(?m)^http://(?:[^\n]+)/([0-9]+)$', desc): if IsLocalCL(ui, repo, clname) and IsRietveldSubmitted(ui, clname, repo[rev].hex()): ui.warn("CL %s submitted as %s; closing\n" % (clname, repo[rev])) cl, err = LoadCL(ui, repo, clname, web=False) if err != "": ui.warn("loading CL %s: %s\n" % (clname, err)) continue if not cl.copied_from: EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) if hgversion < '1.4': get = util.cachefunc(lambda r: repo[r].changeset()) changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, [], get, {'rev': None}) n = 0 for st, rev, fns in changeiter: if st != 'iter': continue n += 1 if n > 100: break Rev(rev) else: matchfn = scmutil.match(repo, [], {'rev': None}) def prep(ctx, fns): pass for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep): Rev(ctx.rev()) # Remove files that are not modified from the CLs in which they appear. all = LoadAllCL(ui, repo, web=False) changed = ChangedFiles(ui, repo, [], {}) for _, cl in all.items(): extra = Sub(cl.files, changed) if extra: ui.warn("Removing unmodified files from CL %s:\n" % (cl.name,)) for f in extra: ui.warn("\t%s\n" % (f,)) cl.files = Sub(cl.files, extra) cl.Flush(ui, repo) if not cl.files: if not cl.copied_from: ui.warn("CL %s has no files; delete (abandon) with hg change -d %s\n" % (cl.name, cl.name)) else: ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name)) return def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if missing_codereview: return missing_codereview repo.ui.quiet = True cl, err = LoadCL(ui, repo, name, web=True) if err != "": return err if not cl.local: return "cannot upload non-local change" cl.Upload(ui, repo) print "%s%s\n" % (server_url_base, cl.name) return review_opts = [ ('r', 'reviewer', '', 'add reviewer'), ('', 'cc', '', 'add cc'), ('', 'tbr', '', 'add future reviewer'), ('m', 'message', '', 'change description (for new change)'), ] cmdtable = { # The ^ means to show this command in the help text that # is printed when running hg with no arguments. "^change": ( change, [ ('d', 'delete', None, 'delete existing change list'), ('D', 'deletelocal', None, 'delete locally, but do not change CL on server'), ('i', 'stdin', None, 'read change list from standard input'), ('o', 'stdout', None, 'print change list to standard output'), ('p', 'pending', None, 'print pending summary to standard output'), ], "[-d | -D] [-i] [-o] change# or FILE ..." ), "^clpatch": ( clpatch, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), # Would prefer to call this codereview-login, but then # hg help codereview prints the help for this command # instead of the help for the extension. "code-login": ( code_login, [], "", ), "^download": ( download, [], "change#" ), "^file": ( file, [ ('d', 'delete', None, 'delete files from change list (but not repository)'), ], "[-d] change# FILE ..." ), "^gofmt": ( gofmt, [ ('l', 'list', None, 'list files that would change, but do not edit them'), ], "FILE ..." ), "^pending|p": ( pending, [], "[FILE ...]" ), "^mail": ( mail, review_opts + [ ] + commands.walkopts, "[-r reviewer] [--cc cc] [change# | file ...]" ), "^release-apply": ( release_apply, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), # TODO: release-start, release-tag, weekly-tag "^submit": ( submit, review_opts + [ ('', 'no_incoming', None, 'disable initial incoming check (for testing)'), ('n', 'dryrun', None, 'make change only locally (for testing)'), ] + commands.walkopts + commands.commitopts + commands.commitopts2, "[-r reviewer] [--cc cc] [change# | file ...]" ), "^sync": ( sync, [ ('', 'local', None, 'do not pull changes from remote repository') ], "[--local]", ), "^undo": ( undo, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), "^upload": ( upload, [], "change#" ), } ####################################################################### # Wrappers around upload.py for interacting with Rietveld # HTML form parser class FormParser(HTMLParser): def __init__(self): self.map = {} self.curtag = None self.curdata = None HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if tag == "input": key = None value = '' for a in attrs: if a[0] == 'name': key = a[1] if a[0] == 'value': value = a[1] if key is not None: self.map[key] = value if tag == "textarea": key = None for a in attrs: if a[0] == 'name': key = a[1] if key is not None: self.curtag = key self.curdata = '' def handle_endtag(self, tag): if tag == "textarea" and self.curtag is not None: self.map[self.curtag] = self.curdata self.curtag = None self.curdata = None def handle_charref(self, name): self.handle_data(unichr(int(name))) def handle_entityref(self, name): import htmlentitydefs if name in htmlentitydefs.entitydefs: self.handle_data(htmlentitydefs.entitydefs[name]) else: self.handle_data("&" + name + ";") def handle_data(self, data): if self.curdata is not None: self.curdata += data def JSONGet(ui, path): try: data = MySend(path, force_auth=False) typecheck(data, str) d = fix_json(json.loads(data)) except: ui.warn("JSONGet %s: %s\n" % (path, ExceptionDetail())) return None return d # Clean up json parser output to match our expectations: # * all strings are UTF-8-encoded str, not unicode. # * missing fields are missing, not None, # so that d.get("foo", defaultvalue) works. def fix_json(x): if type(x) in [str, int, float, bool, type(None)]: pass elif type(x) is unicode: x = x.encode("utf-8") elif type(x) is list: for i in range(len(x)): x[i] = fix_json(x[i]) elif type(x) is dict: todel = [] for k in x: if x[k] is None: todel.append(k) else: x[k] = fix_json(x[k]) for k in todel: del x[k] else: raise util.Abort("unknown type " + str(type(x)) + " in fix_json") if type(x) is str: x = x.replace('\r\n', '\n') return x def IsRietveldSubmitted(ui, clname, hex): dict = JSONGet(ui, "/api/" + clname + "?messages=true") if dict is None: return False for msg in dict.get("messages", []): text = msg.get("text", "") m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text) if m is not None and len(m.group(1)) >= 8 and hex.startswith(m.group(1)): return True return False def IsRietveldMailed(cl): for msg in cl.dict.get("messages", []): if msg.get("text", "").find("I'd like you to review this change") >= 0: return True return False def DownloadCL(ui, repo, clname): set_status("downloading CL " + clname) cl, err = LoadCL(ui, repo, clname, web=True) if err != "": return None, None, None, "error loading CL %s: %s" % (clname, err) # Find most recent diff diffs = cl.dict.get("patchsets", []) if not diffs: return None, None, None, "CL has no patch sets" patchid = diffs[-1] patchset = JSONGet(ui, "/api/" + clname + "/" + str(patchid)) if patchset is None: return None, None, None, "error loading CL patchset %s/%d" % (clname, patchid) if patchset.get("patchset", 0) != patchid: return None, None, None, "malformed patchset information" vers = "" msg = patchset.get("message", "").split() if len(msg) >= 3 and msg[0] == "diff" and msg[1] == "-r": vers = msg[2] diff = "/download/issue" + clname + "_" + str(patchid) + ".diff" diffdata = MySend(diff, force_auth=False) # Print warning if email is not in CONTRIBUTORS file. email = cl.dict.get("owner_email", "") if not email: return None, None, None, "cannot find owner for %s" % (clname) him = FindContributor(ui, repo, email) me = FindContributor(ui, repo, None) if him == me: cl.mailed = IsRietveldMailed(cl) else: cl.copied_from = email return cl, vers, diffdata, "" def MySend(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Run MySend1 maybe twice, because Rietveld is unreliable.""" try: return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) except Exception, e: if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error raise print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds." time.sleep(2) return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) # Like upload.py Send but only authenticates when the # redirect is to www.google.com/accounts. This keeps # unnecessary redirects from happening during testing. def MySend1(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. global rpc if rpc == None: rpc = GetRpcServer(upload_options) self = rpc if not self.authenticated and force_auth: self._Authenticate() if request_path is None: return old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() # Translate \r\n into \n, because Rietveld doesn't. response = response.replace('\r\n', '\n') # who knows what urllib will give us if type(response) == unicode: response = response.encode("utf-8") typecheck(response, str) return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401: self._Authenticate() elif e.code == 302: loc = e.info()["location"] if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0: return '' self._Authenticate() else: raise finally: socket.setdefaulttimeout(old_timeout) def GetForm(url): f = FormParser() f.feed(ustr(MySend(url))) # f.feed wants unicode f.close() # convert back to utf-8 to restore sanity m = {} for k,v in f.map.items(): m[k.encode("utf-8")] = v.replace("\r\n", "\n").encode("utf-8") return m def EditDesc(issue, subject=None, desc=None, reviewers=None, cc=None, closed=False, private=False): set_status("uploading change to description") form_fields = GetForm("/" + issue + "/edit") if subject is not None: form_fields['subject'] = subject if desc is not None: form_fields['description'] = desc if reviewers is not None: form_fields['reviewers'] = reviewers if cc is not None: form_fields['cc'] = cc if closed: form_fields['closed'] = "checked" if private: form_fields['private'] = "checked" ctype, body = EncodeMultipartFormData(form_fields.items(), []) response = MySend("/" + issue + "/edit", body, content_type=ctype) if response != "": print >>sys.stderr, "Error editing description:\n" + "Sent form: \n", form_fields, "\n", response sys.exit(2) def PostMessage(ui, issue, message, reviewers=None, cc=None, send_mail=True, subject=None): set_status("uploading message") form_fields = GetForm("/" + issue + "/publish") if reviewers is not None: form_fields['reviewers'] = reviewers if cc is not None: form_fields['cc'] = cc if send_mail: form_fields['send_mail'] = "checked" else: del form_fields['send_mail'] if subject is not None: form_fields['subject'] = subject form_fields['message'] = message form_fields['message_only'] = '1' # Don't include draft comments if reviewers is not None or cc is not None: form_fields['message_only'] = '' # Must set '' in order to override cc/reviewer ctype = "applications/x-www-form-urlencoded" body = urllib.urlencode(form_fields) response = MySend("/" + issue + "/publish", body, content_type=ctype) if response != "": print response sys.exit(2) class opt(object): pass def nocommit(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use mail, upload, or submit instead of commit") def nobackout(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use undo instead of backout") def norollback(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use undo instead of rollback") def RietveldSetup(ui, repo): global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors global missing_codereview repo_config_path = '' # Read repository-specific options from lib/codereview/codereview.cfg try: repo_config_path = repo.root + '/lib/codereview/codereview.cfg' f = open(repo_config_path) for line in f: if line.startswith('defaultcc: '): defaultcc = SplitCommaSpace(line[10:]) except: # If there are no options, chances are good this is not # a code review repository; stop now before we foul # things up even worse. Might also be that repo doesn't # even have a root. See issue 959. if repo_config_path == '': missing_codereview = 'codereview disabled: repository has no root' else: missing_codereview = 'codereview disabled: cannot open ' + repo_config_path return # Should only modify repository with hg submit. # Disable the built-in Mercurial commands that might # trip things up. cmdutil.commit = nocommit global real_rollback real_rollback = repo.rollback repo.rollback = norollback # would install nobackout if we could; oh well try: f = open(repo.root + '/CONTRIBUTORS', 'r') except: raise util.Abort("cannot open %s: %s" % (repo.root+'/CONTRIBUTORS', ExceptionDetail())) for line in f: # CONTRIBUTORS is a list of lines like: # Person <email> # Person <email> <alt-email> # The first email address is the one used in commit logs. if line.startswith('#'): continue m = re.match(r"([^<>]+\S)\s+(<[^<>\s]+>)((\s+<[^<>\s]+>)*)\s*$", line) if m: name = m.group(1) email = m.group(2)[1:-1] contributors[email.lower()] = (name, email) for extra in m.group(3).split(): contributors[extra[1:-1].lower()] = (name, email) if not ui.verbose: verbosity = 0 # Config options. x = ui.config("codereview", "server") if x is not None: server = x # TODO(rsc): Take from ui.username? email = None x = ui.config("codereview", "email") if x is not None: email = x server_url_base = "http://" + server + "/" testing = ui.config("codereview", "testing") force_google_account = ui.configbool("codereview", "force_google_account", False) upload_options = opt() upload_options.email = email upload_options.host = None upload_options.verbose = 0 upload_options.description = None upload_options.description_file = None upload_options.reviewers = None upload_options.cc = None upload_options.message = None upload_options.issue = None upload_options.download_base = False upload_options.revision = None upload_options.send_mail = False upload_options.vcs = None upload_options.server = server upload_options.save_cookies = True if testing: upload_options.save_cookies = False upload_options.email = "test@example.com" rpc = None global releaseBranch tags = repo.branchtags().keys() if 'release-branch.r100' in tags: # NOTE(rsc): This tags.sort is going to get the wrong # answer when comparing release-branch.r99 with # release-branch.r100. If we do ten releases a year # that gives us 4 years before we have to worry about this. raise util.Abort('tags.sort needs to be fixed for release-branch.r100') tags.sort() for t in tags: if t.startswith('release-branch.'): releaseBranch = t ####################################################################### # http://codereview.appspot.com/static/upload.py, heavily edited. #!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import cookielib import getpass import logging import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse # The md5 module was deprecated in Python 2.5. try: from hashlib import md5 except ImportError: from md5 import md5 try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 # whitelist for non-binary filetypes which do not start with "text/" # .mm (Objective-C) shows up as application/x-freemind on my Linux box. TEXT_MIMETYPES = [ 'application/javascript', 'application/x-javascript', 'application/x-freemind' ] def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com") and not force_google_account: # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, "The user's access to the service has been disabled." break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401 or e.code == 302: self._Authenticate() else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server) self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the password prompt. global global_status st = global_status global_status = None email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) # Put status back. global_status = st return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: typecheck(key, str) typecheck(value, str) lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: typecheck(key, str) typecheck(filename, str) typecheck(value, str) lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True, env=os.environ): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines, env=env) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False, env=os.environ): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" set_status("uploading " + filename) file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [ ("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) # Don't want to spawn too many threads, nor do we want to # hit Rietveld too hard, or it will start serving 500 errors. # When 8 works, it's no better than 4, and sometimes 8 is # too many for Rietveld to handle. MAX_PARALLEL_UPLOADS = 4 sema = threading.BoundedSemaphore(MAX_PARALLEL_UPLOADS) upload_threads = [] finished_upload_threads = [] class UploadFileThread(threading.Thread): def __init__(self, args): threading.Thread.__init__(self) self.args = args def run(self): UploadFile(*self.args) finished_upload_threads.append(self) sema.release() def StartUploadFile(*args): sema.acquire() while len(finished_upload_threads) > 0: t = finished_upload_threads.pop() upload_threads.remove(t) t.join() t = UploadFileThread(args) upload_threads.append(t) t.start() def WaitForUploads(): for t in upload_threads: t.join() patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: StartUploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: StartUploadFile(filename, file_id, new_content, is_binary, status, False) WaitForUploads() def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES: return False return not mimetype.startswith("text/") class FakeMercurialUI(object): def __init__(self): self.quiet = True self.output = '' def write(self, *args, **opts): self.output += ' '.join(args) use_hg_shell = False # set to True to shell out to hg always; slower class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, ui, repo): super(MercurialVCS, self).__init__(options) self.ui = ui self.repo = repo # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo.root) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: mqparent, err = RunShellWithReturnCode(['hg', 'log', '--rev', 'qparent', '--template={node}']) if not err and mqparent != "": self.base_rev = mqparent else: self.base_rev = RunShell(["hg", "parents", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): set_status("inspecting " + filename) # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise if use_hg_shell: out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) else: fui = FakeMercurialUI() ret = commands.status(fui, self.repo, *[relpath], **{'rev': [self.base_rev], 'copies': True}) if ret: raise util.Abort(ret) out = fui.output out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] status, what = out[0].split(' ', 1) if len(out) > 1 and status == "A" and what == relpath: oldrelpath = out[1].strip() status = "M" if ":" in self.base_rev: base_rev = self.base_rev.split(":", 1)[0] else: base_rev = self.base_rev if status != "A": if use_hg_shell: base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True) else: base_content = str(self.repo[base_rev][oldrelpath].data()) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content and use_hg_shell: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: set_status("uploading patch for " + patch[0]) if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv
05yohn-go-uuid
lib/codereview/codereview.py
Python
bsd
99,502
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
07tc013
trunk/support/scripts/.svn/text-base/googlecode_upload.py.svn-base
Python
art
8,912
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
07tc013
trunk/support/scripts/googlecode_upload.py
Python
art
8,912
#!/bin/sh # START-COMMIT HOOK # # The start-commit hook is invoked before a Subversion txn is created # in the process of doing a commit. Subversion runs this hook # by invoking a program (script, executable, binary, etc.) named # 'start-commit' (for which this file is a template) # with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the authenticated user attempting to commit) # [3] CAPABILITIES (a colon-separated list of capabilities reported # by the client; see note below) # # Note: The CAPABILITIES parameter is new in Subversion 1.5, and 1.5 # clients will typically report at least the "mergeinfo" capability. # If there are other capabilities, then the list is colon-separated, # e.g.: "mergeinfo:some-other-capability" (the order is undefined). # # The list is self-reported by the client. Therefore, you should not # make security assumptions based on the capabilities list, nor should # you assume that clients reliably report every capability they have. # # The working directory for this hook program's invocation is undefined, # so the program should set one explicitly if it cares. # # If the hook program exits with success, the commit continues; but # if it exits with failure (non-zero), the commit is stopped before # a Subversion txn is created, and STDERR is returned to the client. # # On a Unix system, the normal procedure is to have 'start-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'start-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'start-commit.bat' or 'start-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" USER="$2" commit-allower.pl --repository "$REPOS" --user "$USER" || exit 1 special-auth-check.py --user "$USER" --auth-level 3 || exit 1 # All checks passed, so allow the commit. exit 0
07tc013
trunk/hooks/start-commit.tmpl
Shell
art
2,845
#!/bin/sh # PRE-COMMIT HOOK # # The pre-commit hook is invoked before a Subversion txn is # committed. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-commit' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] TXN-NAME (the name of the txn about to be committed) # # [STDIN] LOCK-TOKENS ** the lock tokens are passed via STDIN. # # If STDIN contains the line "LOCK-TOKENS:\n" (the "\n" denotes a # single newline), the lines following it are the lock tokens for # this commit. The end of the list is marked by a line containing # only a newline character. # # Each lock token line consists of a URI-escaped path, followed # by the separator character '|', followed by the lock token string, # followed by a newline. # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the txn is committed; but # if it exits with failure (non-zero), the txn is aborted, no commit # takes place, and STDERR is returned to the client. The hook # program can use the 'svnlook' utility to help it examine the txn. # # On a Unix system, the normal procedure is to have 'pre-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # *** NOTE: THE HOOK PROGRAM MUST NOT MODIFY THE TXN, EXCEPT *** # *** FOR REVISION PROPERTIES (like svn:log or svn:author). *** # # This is why we recommend using the read-only 'svnlook' utility. # In the future, Subversion may enforce the rule that pre-commit # hooks should not modify the versioned data in txns, or else come # up with a mechanism to make it safe to do so (by informing the # committing client of the changes). However, right now neither # mechanism is implemented, so hook writers just have to be careful. # # Note that 'pre-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-commit.bat' or 'pre-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" TXN="$2" # Make sure that the log message contains some text. SVNLOOK=/usr/local/bin/svnlook $SVNLOOK log -t "$TXN" "$REPOS" | \ grep "[a-zA-Z0-9]" > /dev/null || exit 1 # Check that the author of this commit has the rights to perform # the commit on the files and directories being modified. commit-access-control.pl "$REPOS" "$TXN" commit-access-control.cfg || exit 1 # All checks passed, so allow the commit. exit 0
07tc013
trunk/hooks/pre-commit.tmpl
Shell
art
3,513
#!/bin/sh # PRE-LOCK HOOK # # The pre-lock hook is invoked before an exclusive lock is # created. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-lock' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] PATH (the path in the repository about to be locked) # [3] USER (the user creating the lock) # [4] COMMENT (the comment of the lock) # [5] STEAL-LOCK (1 if the user is trying to steal the lock, else 0) # # If the hook program outputs anything on stdout, the output string will # be used as the lock token for this lock operation. If you choose to use # this feature, you must guarantee the tokens generated are unique across # the repository each time. # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the lock is created; but # if it exits with failure (non-zero), the lock action is aborted # and STDERR is returned to the client. # On a Unix system, the normal procedure is to have 'pre-lock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-lock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-lock.bat' or 'pre-lock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" PATH="$2" USER="$3" # If a lock exists and is owned by a different person, don't allow it # to be stolen (e.g., with 'svn lock --force ...'). # (Maybe this script could send email to the lock owner?) SVNLOOK=/usr/local/bin/svnlook GREP=/bin/grep SED=/bin/sed LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \ $GREP '^Owner: ' | $SED 's/Owner: //'` # If we get no result from svnlook, there's no lock, allow the lock to # happen: if [ "$LOCK_OWNER" = "" ]; then exit 0 fi # If the person locking matches the lock's owner, allow the lock to # happen: if [ "$LOCK_OWNER" = "$USER" ]; then exit 0 fi # Otherwise, we've got an owner mismatch, so return failure: echo "Error: $PATH already locked by ${LOCK_OWNER}." 1>&2 exit 1
07tc013
trunk/hooks/pre-lock.tmpl
Shell
art
2,487
#!/bin/sh # POST-COMMIT HOOK # # The post-commit hook is invoked after a commit. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-commit' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REV (the number of the revision just committed) # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the commit has already completed and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # newly-committed tree. # # On a Unix system, the normal procedure is to have 'post-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-commit.bat' or 'post-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf
07tc013
trunk/hooks/post-commit.tmpl
Shell
art
2,027
#!/bin/sh # PRE-COMMIT HOOK # # The pre-commit hook is invoked before a Subversion txn is # committed. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-commit' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] TXN-NAME (the name of the txn about to be committed) # # [STDIN] LOCK-TOKENS ** the lock tokens are passed via STDIN. # # If STDIN contains the line "LOCK-TOKENS:\n" (the "\n" denotes a # single newline), the lines following it are the lock tokens for # this commit. The end of the list is marked by a line containing # only a newline character. # # Each lock token line consists of a URI-escaped path, followed # by the separator character '|', followed by the lock token string, # followed by a newline. # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the txn is committed; but # if it exits with failure (non-zero), the txn is aborted, no commit # takes place, and STDERR is returned to the client. The hook # program can use the 'svnlook' utility to help it examine the txn. # # On a Unix system, the normal procedure is to have 'pre-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # *** NOTE: THE HOOK PROGRAM MUST NOT MODIFY THE TXN, EXCEPT *** # *** FOR REVISION PROPERTIES (like svn:log or svn:author). *** # # This is why we recommend using the read-only 'svnlook' utility. # In the future, Subversion may enforce the rule that pre-commit # hooks should not modify the versioned data in txns, or else come # up with a mechanism to make it safe to do so (by informing the # committing client of the changes). However, right now neither # mechanism is implemented, so hook writers just have to be careful. # # Note that 'pre-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-commit.bat' or 'pre-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" TXN="$2" # Make sure that the log message contains some text. SVNLOOK=/usr/local/bin/svnlook $SVNLOOK log -t "$TXN" "$REPOS" | \ grep "[a-zA-Z0-9]" > /dev/null || exit 1 # Check that the author of this commit has the rights to perform # the commit on the files and directories being modified. commit-access-control.pl "$REPOS" "$TXN" commit-access-control.cfg || exit 1 # All checks passed, so allow the commit. exit 0
07tc013
trunk/hooks/.svn/text-base/pre-commit.tmpl.svn-base
Shell
art
3,513
#!/bin/sh # PRE-REVPROP-CHANGE HOOK # # The pre-revprop-change hook is invoked before a revision property # is added, modified or deleted. Subversion runs this hook by invoking # a program (script, executable, binary, etc.) named 'pre-revprop-change' # (for which this file is a template), with the following ordered # arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REVISION (the revision being tweaked) # [3] USER (the username of the person tweaking the property) # [4] PROPNAME (the property being set on the revision) # [5] ACTION (the property is being 'A'dded, 'M'odified, or 'D'eleted) # # [STDIN] PROPVAL ** the new property value is passed via STDIN. # # If the hook program exits with success, the propchange happens; but # if it exits with failure (non-zero), the propchange doesn't happen. # The hook program can use the 'svnlook' utility to examine the # existing value of the revision property. # # WARNING: unlike other hooks, this hook MUST exist for revision # properties to be changed. If the hook does not exist, Subversion # will behave as if the hook were present, but failed. The reason # for this is that revision properties are UNVERSIONED, meaning that # a successful propchange is destructive; the old value is gone # forever. We recommend the hook back up the old value somewhere. # # On a Unix system, the normal procedure is to have 'pre-revprop-change' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-revprop-change' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-revprop-change.bat' or 'pre-revprop-change.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" USER="$3" PROPNAME="$4" ACTION="$5" if [ "$ACTION" = "M" -a "$PROPNAME" = "svn:log" ]; then exit 0; fi echo "Changing revision properties other than svn:log is prohibited" >&2 exit 1
07tc013
trunk/hooks/.svn/text-base/pre-revprop-change.tmpl.svn-base
Shell
art
2,852
#!/bin/sh # PRE-LOCK HOOK # # The pre-lock hook is invoked before an exclusive lock is # created. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-lock' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] PATH (the path in the repository about to be locked) # [3] USER (the user creating the lock) # [4] COMMENT (the comment of the lock) # [5] STEAL-LOCK (1 if the user is trying to steal the lock, else 0) # # If the hook program outputs anything on stdout, the output string will # be used as the lock token for this lock operation. If you choose to use # this feature, you must guarantee the tokens generated are unique across # the repository each time. # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the lock is created; but # if it exits with failure (non-zero), the lock action is aborted # and STDERR is returned to the client. # On a Unix system, the normal procedure is to have 'pre-lock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-lock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-lock.bat' or 'pre-lock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" PATH="$2" USER="$3" # If a lock exists and is owned by a different person, don't allow it # to be stolen (e.g., with 'svn lock --force ...'). # (Maybe this script could send email to the lock owner?) SVNLOOK=/usr/local/bin/svnlook GREP=/bin/grep SED=/bin/sed LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \ $GREP '^Owner: ' | $SED 's/Owner: //'` # If we get no result from svnlook, there's no lock, allow the lock to # happen: if [ "$LOCK_OWNER" = "" ]; then exit 0 fi # If the person locking matches the lock's owner, allow the lock to # happen: if [ "$LOCK_OWNER" = "$USER" ]; then exit 0 fi # Otherwise, we've got an owner mismatch, so return failure: echo "Error: $PATH already locked by ${LOCK_OWNER}." 1>&2 exit 1
07tc013
trunk/hooks/.svn/text-base/pre-lock.tmpl.svn-base
Shell
art
2,487
#!/bin/sh # POST-REVPROP-CHANGE HOOK # # The post-revprop-change hook is invoked after a revision property # has been added, modified or deleted. Subversion runs this hook by # invoking a program (script, executable, binary, etc.) named # 'post-revprop-change' (for which this file is a template), with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REV (the revision that was tweaked) # [3] USER (the username of the person tweaking the property) # [4] PROPNAME (the property that was changed) # [5] ACTION (the property was 'A'dded, 'M'odified, or 'D'eleted) # # [STDIN] PROPVAL ** the old property value is passed via STDIN. # # Because the propchange has already completed and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # new property value. # # On a Unix system, the normal procedure is to have 'post-revprop-change' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-revprop-change' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-revprop-change.bat' or 'post-revprop-change.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" USER="$3" PROPNAME="$4" ACTION="$5" mailer.py propchange2 "$REPOS" "$REV" "$USER" "$PROPNAME" "$ACTION" /path/to/mailer.conf
07tc013
trunk/hooks/.svn/text-base/post-revprop-change.tmpl.svn-base
Shell
art
2,345
#!/bin/sh # POST-LOCK HOOK # # The post-lock hook is run after a path is locked. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-lock' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the user who created the lock) # # The paths that were just locked are passed to the hook via STDIN (as # of Subversion 1.2, only one path is passed per invocation, but the # plan is to pass all locked paths at once, so the hook program # should be written accordingly). # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the lock has already been created and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # newly-created lock. # # On a Unix system, the normal procedure is to have 'post-lock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-lock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-lock.bat' or 'post-lock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" USER="$2" # Send email to interested parties, let them know a lock was created: mailer.py lock "$REPOS" "$USER" /path/to/mailer.conf
07tc013
trunk/hooks/.svn/text-base/post-lock.tmpl.svn-base
Shell
art
1,682
#!/bin/sh # PRE-UNLOCK HOOK # # The pre-unlock hook is invoked before an exclusive lock is # destroyed. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-unlock' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] PATH (the path in the repository about to be unlocked) # [3] USER (the user destroying the lock) # [4] TOKEN (the lock token to be destroyed) # [5] BREAK-UNLOCK (1 if the user is breaking the lock, else 0) # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the lock is destroyed; but # if it exits with failure (non-zero), the unlock action is aborted # and STDERR is returned to the client. # On a Unix system, the normal procedure is to have 'pre-unlock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-unlock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-unlock.bat' or 'pre-unlock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" PATH="$2" USER="$3" # If a lock is owned by a different person, don't allow it be broken. # (Maybe this script could send email to the lock owner?) SVNLOOK=/usr/local/bin/svnlook GREP=/bin/grep SED=/bin/sed LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \ $GREP '^Owner: ' | $SED 's/Owner: //'` # If we get no result from svnlook, there's no lock, return success: if [ "$LOCK_OWNER" = "" ]; then exit 0 fi # If the person unlocking matches the lock's owner, return success: if [ "$LOCK_OWNER" = "$USER" ]; then exit 0 fi # Otherwise, we've got an owner mismatch, so return failure: echo "Error: $PATH locked by ${LOCK_OWNER}." 1>&2 exit 1
07tc013
trunk/hooks/.svn/text-base/pre-unlock.tmpl.svn-base
Shell
art
2,169
#!/bin/sh # START-COMMIT HOOK # # The start-commit hook is invoked before a Subversion txn is created # in the process of doing a commit. Subversion runs this hook # by invoking a program (script, executable, binary, etc.) named # 'start-commit' (for which this file is a template) # with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the authenticated user attempting to commit) # [3] CAPABILITIES (a colon-separated list of capabilities reported # by the client; see note below) # # Note: The CAPABILITIES parameter is new in Subversion 1.5, and 1.5 # clients will typically report at least the "mergeinfo" capability. # If there are other capabilities, then the list is colon-separated, # e.g.: "mergeinfo:some-other-capability" (the order is undefined). # # The list is self-reported by the client. Therefore, you should not # make security assumptions based on the capabilities list, nor should # you assume that clients reliably report every capability they have. # # The working directory for this hook program's invocation is undefined, # so the program should set one explicitly if it cares. # # If the hook program exits with success, the commit continues; but # if it exits with failure (non-zero), the commit is stopped before # a Subversion txn is created, and STDERR is returned to the client. # # On a Unix system, the normal procedure is to have 'start-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'start-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'start-commit.bat' or 'start-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" USER="$2" commit-allower.pl --repository "$REPOS" --user "$USER" || exit 1 special-auth-check.py --user "$USER" --auth-level 3 || exit 1 # All checks passed, so allow the commit. exit 0
07tc013
trunk/hooks/.svn/text-base/start-commit.tmpl.svn-base
Shell
art
2,845
#!/bin/sh # POST-COMMIT HOOK # # The post-commit hook is invoked after a commit. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-commit' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REV (the number of the revision just committed) # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the commit has already completed and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # newly-committed tree. # # On a Unix system, the normal procedure is to have 'post-commit' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-commit' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-commit.bat' or 'post-commit.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" mailer.py commit "$REPOS" "$REV" /path/to/mailer.conf
07tc013
trunk/hooks/.svn/text-base/post-commit.tmpl.svn-base
Shell
art
2,027
#!/bin/sh # POST-UNLOCK HOOK # # The post-unlock hook runs after a path is unlocked. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-unlock' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the user who destroyed the lock) # # The paths that were just unlocked are passed to the hook via STDIN # (as of Subversion 1.2, only one path is passed per invocation, but # the plan is to pass all unlocked paths at once, so the hook program # should be written accordingly). # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the lock has already been destroyed and cannot be undone, # the exit code of the hook program is ignored. # # On a Unix system, the normal procedure is to have 'post-unlock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-unlock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-unlock.bat' or 'post-unlock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" USER="$2" # Send email to interested parties, let them know a lock was removed: mailer.py unlock "$REPOS" "$USER" /path/to/mailer.conf
07tc013
trunk/hooks/.svn/text-base/post-unlock.tmpl.svn-base
Shell
art
1,609
#!/bin/sh # POST-UNLOCK HOOK # # The post-unlock hook runs after a path is unlocked. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-unlock' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the user who destroyed the lock) # # The paths that were just unlocked are passed to the hook via STDIN # (as of Subversion 1.2, only one path is passed per invocation, but # the plan is to pass all unlocked paths at once, so the hook program # should be written accordingly). # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the lock has already been destroyed and cannot be undone, # the exit code of the hook program is ignored. # # On a Unix system, the normal procedure is to have 'post-unlock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-unlock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-unlock.bat' or 'post-unlock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" USER="$2" # Send email to interested parties, let them know a lock was removed: mailer.py unlock "$REPOS" "$USER" /path/to/mailer.conf
07tc013
trunk/hooks/post-unlock.tmpl
Shell
art
1,609
#!/bin/sh # PRE-REVPROP-CHANGE HOOK # # The pre-revprop-change hook is invoked before a revision property # is added, modified or deleted. Subversion runs this hook by invoking # a program (script, executable, binary, etc.) named 'pre-revprop-change' # (for which this file is a template), with the following ordered # arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REVISION (the revision being tweaked) # [3] USER (the username of the person tweaking the property) # [4] PROPNAME (the property being set on the revision) # [5] ACTION (the property is being 'A'dded, 'M'odified, or 'D'eleted) # # [STDIN] PROPVAL ** the new property value is passed via STDIN. # # If the hook program exits with success, the propchange happens; but # if it exits with failure (non-zero), the propchange doesn't happen. # The hook program can use the 'svnlook' utility to examine the # existing value of the revision property. # # WARNING: unlike other hooks, this hook MUST exist for revision # properties to be changed. If the hook does not exist, Subversion # will behave as if the hook were present, but failed. The reason # for this is that revision properties are UNVERSIONED, meaning that # a successful propchange is destructive; the old value is gone # forever. We recommend the hook back up the old value somewhere. # # On a Unix system, the normal procedure is to have 'pre-revprop-change' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-revprop-change' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-revprop-change.bat' or 'pre-revprop-change.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" USER="$3" PROPNAME="$4" ACTION="$5" if [ "$ACTION" = "M" -a "$PROPNAME" = "svn:log" ]; then exit 0; fi echo "Changing revision properties other than svn:log is prohibited" >&2 exit 1
07tc013
trunk/hooks/pre-revprop-change.tmpl
Shell
art
2,852
#!/bin/sh # POST-LOCK HOOK # # The post-lock hook is run after a path is locked. Subversion runs # this hook by invoking a program (script, executable, binary, etc.) # named 'post-lock' (for which this file is a template) with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] USER (the user who created the lock) # # The paths that were just locked are passed to the hook via STDIN (as # of Subversion 1.2, only one path is passed per invocation, but the # plan is to pass all locked paths at once, so the hook program # should be written accordingly). # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # Because the lock has already been created and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # newly-created lock. # # On a Unix system, the normal procedure is to have 'post-lock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-lock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-lock.bat' or 'post-lock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" USER="$2" # Send email to interested parties, let them know a lock was created: mailer.py lock "$REPOS" "$USER" /path/to/mailer.conf
07tc013
trunk/hooks/post-lock.tmpl
Shell
art
1,682
#!/bin/sh # POST-REVPROP-CHANGE HOOK # # The post-revprop-change hook is invoked after a revision property # has been added, modified or deleted. Subversion runs this hook by # invoking a program (script, executable, binary, etc.) named # 'post-revprop-change' (for which this file is a template), with the # following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] REV (the revision that was tweaked) # [3] USER (the username of the person tweaking the property) # [4] PROPNAME (the property that was changed) # [5] ACTION (the property was 'A'dded, 'M'odified, or 'D'eleted) # # [STDIN] PROPVAL ** the old property value is passed via STDIN. # # Because the propchange has already completed and cannot be undone, # the exit code of the hook program is ignored. The hook program # can use the 'svnlook' utility to help it examine the # new property value. # # On a Unix system, the normal procedure is to have 'post-revprop-change' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'post-revprop-change' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'post-revprop-change.bat' or 'post-revprop-change.exe', # but the basic idea is the same. # # The hook program typically does not inherit the environment of # its parent process. For example, a common problem is for the # PATH environment variable to not be set to its usual value, so # that subprograms fail to launch unless invoked via absolute path. # If you're having unexpected problems with a hook program, the # culprit may be unusual (or missing) environment variables. # # Here is an example hook script, for a Unix /bin/sh interpreter. # For more examples and pre-written hooks, see those in # the Subversion repository at # http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/ REPOS="$1" REV="$2" USER="$3" PROPNAME="$4" ACTION="$5" mailer.py propchange2 "$REPOS" "$REV" "$USER" "$PROPNAME" "$ACTION" /path/to/mailer.conf
07tc013
trunk/hooks/post-revprop-change.tmpl
Shell
art
2,345
#!/bin/sh # PRE-UNLOCK HOOK # # The pre-unlock hook is invoked before an exclusive lock is # destroyed. Subversion runs this hook by invoking a program # (script, executable, binary, etc.) named 'pre-unlock' (for which # this file is a template), with the following ordered arguments: # # [1] REPOS-PATH (the path to this repository) # [2] PATH (the path in the repository about to be unlocked) # [3] USER (the user destroying the lock) # [4] TOKEN (the lock token to be destroyed) # [5] BREAK-UNLOCK (1 if the user is breaking the lock, else 0) # # The default working directory for the invocation is undefined, so # the program should set one explicitly if it cares. # # If the hook program exits with success, the lock is destroyed; but # if it exits with failure (non-zero), the unlock action is aborted # and STDERR is returned to the client. # On a Unix system, the normal procedure is to have 'pre-unlock' # invoke other programs to do the real work, though it may do the # work itself too. # # Note that 'pre-unlock' must be executable by the user(s) who will # invoke it (typically the user httpd runs as), and that user must # have filesystem-level permission to access the repository. # # On a Windows system, you should name the hook program # 'pre-unlock.bat' or 'pre-unlock.exe', # but the basic idea is the same. # # Here is an example hook script, for a Unix /bin/sh interpreter: REPOS="$1" PATH="$2" USER="$3" # If a lock is owned by a different person, don't allow it be broken. # (Maybe this script could send email to the lock owner?) SVNLOOK=/usr/local/bin/svnlook GREP=/bin/grep SED=/bin/sed LOCK_OWNER=`$SVNLOOK lock "$REPOS" "$PATH" | \ $GREP '^Owner: ' | $SED 's/Owner: //'` # If we get no result from svnlook, there's no lock, return success: if [ "$LOCK_OWNER" = "" ]; then exit 0 fi # If the person unlocking matches the lock's owner, return success: if [ "$LOCK_OWNER" = "$USER" ]; then exit 0 fi # Otherwise, we've got an owner mismatch, so return failure: echo "Error: $PATH locked by ${LOCK_OWNER}." 1>&2 exit 1
07tc013
trunk/hooks/pre-unlock.tmpl
Shell
art
2,169
#! /bin/bash # Binary of the Texturepacker: TEXTUREPACKER_BINARY=/usr/local/bin/TexturePacker # Shared Spritesheet-Output-Definitions: SPRITESHEET_OUTPUT_DIRECTORY="../assets/gfx/spritesheets/" SPRITESHEET_OUTPUT_JAVAIDS_PACKAGE="org.anddev.andengine.examples.spritesheets" SPRITESHEET_OUTPUT_JAVAIDS_DIRECTORY="../src/org/anddev/andengine/examples/spritesheets/" # Shared Spritesheet-Input-Definitions: SPRITESHEET_INPUT_BASEDIRECTORY="../ext/gfx/spritesheets/" # Individual Spritesheet-Definitions (separated by ';'): # Fragment #1: The input for the spritesheet, relative to ${SPRITESHEET_INPUT_BASEDIRECTORY} # Fragment #2: The name of the generated spritesheet, relative to ${SPRITESHEET_OUTPUT_DIRECTORY} # Fragment #3: The filename of the generated java interface that contains the IDs of the textureregions in the generated spritesheet. SPRITESHEET_INPUT_DATA=( "texturepackerexample/;texturepackerexample;TexturePackerExampleSpritesheet.java" ) ########################### # Clean old Spritesheets: # ########################### echo echo "#########################################" echo -n "# Cleaning old spritesheets..." # TODO rm -f ${SPRITESHEET_OUTPUT_JAVAIDS_DIRECTORY}*.java rm -f ${SPRITESHEET_OUTPUT_DIRECTORY}*.pvr.ccz rm -f ${SPRITESHEET_OUTPUT_DIRECTORY}*.xml echo " done." echo "#########################################" echo ############################## # Generate new Spritesheets: # ############################## echo "#########################################" echo "# Generating ${#SPRITESHEET_INPUT_DATA[@]} spritesheets..." echo "#########################################" echo # Loop over all entries ${SPRITESHEET_INPUT_DATA} to generate one spritesheet for each entry: i=0 for SPRITESHEET_INPUT_DATA_ENTRY in "${SPRITESHEET_INPUT_DATA[@]}" do echo "#########################################" i=`expr $i + 1` echo "# Generating spritesheet $i of ${#SPRITESHEET_INPUT_DATA[@]} ..." echo "#" # Split fragments of ${SPRITESHEET_INPUT_DATA_ENTRY} into ${SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT} IFS=\; read -a SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT <<< "$SPRITESHEET_INPUT_DATA_ENTRY" # Generate spritesheets ${TEXTUREPACKER_BINARY} ${SPRITESHEET_INPUT_BASEDIRECTORY}${SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT[0]}*.png \ --format andengine \ --opt RGBA4444 \ --border-padding 0 \ --shape-padding 1 \ --disable-rotation \ --no-trim \ --max-width 1024 \ --max-height 1024 \ --andengine-wraps clamp \ --andengine-wrapt clamp \ --andengine-minfilter linear \ --andengine-magfilter linear \ --data ${SPRITESHEET_OUTPUT_DIRECTORY}${SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT[1]}.xml \ --sheet ${SPRITESHEET_OUTPUT_DIRECTORY}${SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT[1]}.pvr.ccz \ --andengine-java ${SPRITESHEET_OUTPUT_JAVAIDS_DIRECTORY}${SPRITESHEET_INPUT_DATA_ENTRY_FRAGMENT[2]} \ --andengine-packagename ${SPRITESHEET_OUTPUT_JAVAIDS_PACKAGE} echo "#" echo "# done." echo "#########################################" echo done echo "#########################################" echo "# done." echo "#########################################" echo exit 0
0bigdream10-tungclone
scripts/build_spritesheets.sh
Shell
lgpl
3,124
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.ui.activity.LayoutGameActivity; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class XMLLayoutExample extends LayoutGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getLayoutID() { return R.layout.xmllayoutexample; } @Override protected int getRenderSurfaceViewID() { return R.id.xmllayoutexample_rendersurfaceview; } @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/XMLLayoutExample.java
Java
lgpl
5,888
package org.anddev.andengine.examples; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.animator.SlideMenuAnimator; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:33:33 - 01.04.2010 */ public class SubMenuExample extends MenuExample { // =========================================================== // Constants // =========================================================== private static final int MENU_QUIT_OK = MenuExample.MENU_QUIT + 1; private static final int MENU_QUIT_BACK = MENU_QUIT_OK + 1; // =========================================================== // Fields // =========================================================== private MenuScene mSubMenuScene; private BitmapTextureAtlas mSubMenuTexture; private TextureRegion mMenuOkTextureRegion; private TextureRegion mMenuBackTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onLoadResources() { super.onLoadResources(); this.mSubMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mMenuOkTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_ok.png", 0, 0); this.mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mSubMenuTexture, this, "menu_back.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mSubMenuTexture); } @Override protected void createMenuScene() { super.createMenuScene(); this.mSubMenuScene = new MenuScene(this.mCamera); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_OK, this.mMenuOkTextureRegion)); this.mSubMenuScene.addMenuItem(new SpriteMenuItem(MENU_QUIT_BACK, this.mMenuBackTextureRegion)); this.mSubMenuScene.setMenuAnimator(new SlideMenuAnimator()); this.mSubMenuScene.buildAnimations(); this.mSubMenuScene.setBackgroundEnabled(false); this.mSubMenuScene.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: this.mMainScene.reset(); this.mMenuScene.back(); return true; case MENU_QUIT: pMenuScene.setChildSceneModal(this.mSubMenuScene); return true; case MENU_QUIT_BACK: this.mSubMenuScene.back(); return true; case MENU_QUIT_OK: this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/SubMenuExample.java
Java
lgpl
3,895
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class SpriteExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/SpriteExample.java
Java
lgpl
3,748
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.LoopModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class EntityModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Rectangle rect = new Rectangle(centerX + 100, centerY, 32, 32); rect.setColor(1, 0, 0); final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face.animate(100); face.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); final LoopEntityModifier entityModifier = new LoopEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence finished.", Toast.LENGTH_SHORT).show(); } }); } }, 2, new ILoopEntityModifierListener() { @Override public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show(); } }); } }, new SequenceEntityModifier( new RotationModifier(1, 0, 90), new AlphaModifier(2, 1, 0), new AlphaModifier(1, 0, 1), new ScaleModifier(2, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(3, 0.5f, 5), new RotationByModifier(3, 90) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ) ); face.registerEntityModifier(entityModifier); rect.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(face); scene.attachChild(rect); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/EntityModifierExample.java
Java
lgpl
7,264
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class PathModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "You move my sprite right round, right round...", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { // this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Create the face and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(10, 10, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); /* Add the proper animation when a waypoint of the path is passed. */ player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathStarted"); } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointStarted: " + pWaypointIndex); switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { Debug.d("onPathWaypointFinished: " + pWaypointIndex); } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { Debug.d("onPathFinished"); } }, EaseSineInOut.getInstance()))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/PathModifierExample.java
Java
lgpl
5,845
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:18:08 - 27.06.2010 */ public class PhysicsJumpExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 360; private static final int CAMERA_HEIGHT = 240; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private int mFaceCount = 0; private PhysicsWorld mPhysicsWorld; private float mGravityX; private float mGravityY; private Scene mScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects. Touch an object to shoot it up into the air.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); this.mScene.setOnAreaTouchListener(this); return this.mScene; } @Override public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final AnimatedSprite face = (AnimatedSprite) pTouchArea; this.jumpFace(face); return true; } return false; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { this.mGravityX = pAccelerometerData.getX(); this.mGravityY = pAccelerometerData.getY(); final Vector2 gravity = Vector2Pool.obtain(this.mGravityX, this.mGravityY); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 1){ face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); face.animate(new long[]{200,200}, 0, 1, true); face.setUserData(body); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); } private void jumpFace(final AnimatedSprite face) { final Body faceBody = (Body)face.getUserData(); final Vector2 velocity = Vector2Pool.obtain(this.mGravityX * -50, this.mGravityY * -50); faceBody.setLinearVelocity(velocity); Vector2Pool.recycle(velocity); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/PhysicsJumpExample.java
Java
lgpl
8,649
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemSimpleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/ParticleSystemSimpleExample.java
Java
lgpl
5,632
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.TextMenuItem; import org.anddev.andengine.entity.scene.menu.item.decorator.ColorMenuItemDecorator; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.graphics.Color; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class TextMenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mFontTexture; private Font mFont; protected MenuScene mMenuScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* Load Font/Textures. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 48, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* Load Sprite-Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mMenuScene = this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected MenuScene createMenuScene() { final MenuScene menuScene = new MenuScene(this.mCamera); final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_RESET, this.mFont, "RESET"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(resetMenuItem); final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "QUIT"), 1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); menuScene.addMenuItem(quitMenuItem); menuScene.buildAnimations(); menuScene.setBackgroundEnabled(false); menuScene.setOnMenuItemClickListener(this); return menuScene; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/TextMenuExample.java
Java
lgpl
6,869
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 13.07.2011 */ public class PVRTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTextureRGB565; private ITexture mTextureRGBA5551; private ITexture mTextureARGB4444; private ITexture mTextureRGBA888MipMaps; private TextureRegion mHouseNearestTextureRegion; private TextureRegion mHouseLinearTextureRegion; private TextureRegion mHouseMipMapsNearestTextureRegion; private TextureRegion mHouseMipMapsLinearTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The lower houses use MipMaps!", Toast.LENGTH_LONG); Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTextureRGB565 = new PVRTexture(PVRTextureFormat.RGB_565, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_rgb_565); } }; this.mTextureRGBA5551 = new PVRTexture(PVRTextureFormat.RGBA_5551, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_5551); } }; this.mTextureARGB4444 = new PVRTexture(PVRTextureFormat.RGBA_4444, new TextureOptions(GL10.GL_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_4444); } }; this.mTextureRGBA888MipMaps = new PVRTexture(PVRTextureFormat.RGBA_8888, new TextureOptions(GL10.GL_LINEAR_MIPMAP_LINEAR, GL10.GL_LINEAR, GL10.GL_CLAMP_TO_EDGE, GL10.GL_CLAMP_TO_EDGE, false)) { @Override protected InputStream onGetInputStream() throws IOException { return PVRTextureExample.this.getResources().openRawResource(R.raw.house_pvr_argb_8888_mipmaps); } }; this.mHouseNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGB565, 0, 0, 512, 512, true); this.mHouseLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA5551, 0, 0, 512, 512, true); this.mHouseMipMapsNearestTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureARGB4444, 0, 0, 512, 512, true); this.mHouseMipMapsLinearTextureRegion = TextureRegionFactory.extractFromTexture(this.mTextureRGBA888MipMaps, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTextureRGB565, this.mTextureRGBA5551, this.mTextureARGB4444, this.mTextureRGBA888MipMaps); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final Entity container = new Entity(centerX, centerY); container.setScale(0.5f); container.attachChild(new Sprite(-512, -384, this.mHouseNearestTextureRegion)); container.attachChild(new Sprite(0, -384, this.mHouseLinearTextureRegion)); container.attachChild(new Sprite(-512, -128, this.mHouseMipMapsNearestTextureRegion)); container.attachChild(new Sprite(0, -128, this.mHouseMipMapsLinearTextureRegion)); scene.attachChild(container); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRTextureExample.this.mZoomState = ZoomState.IN; } else { PVRTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/PVRTextureExample.java
Java
lgpl
7,781
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/AnalogOnScreenControlsExample.java
Java
lgpl
8,315
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Also try tapping this AnalogOnScreenControl!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { face.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1))); } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); analogOnScreenControl.getControlBase().setScaleCenter(0, 128); analogOnScreenControl.getControlBase().setScale(1.25f); analogOnScreenControl.getControlKnob().setScale(1.25f); analogOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(analogOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/AnalogOnScreenControlExample.java
Java
lgpl
6,263
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ZoomExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch and hold the scene and the camera will smoothly zoom in.\nRelease the scene it to zoom out again.", Toast.LENGTH_LONG).show(); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 10, 10, 1.0f); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the screen-center. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create some faces and add them to the scene. */ scene.attachChild(new Sprite(centerX - 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX + 25, centerY - 25, this.mFaceTextureRegion)); scene.attachChild(new Sprite(centerX, centerY + 25, this.mFaceTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: ZoomExample.this.mSmoothCamera.setZoomFactor(5.0f); break; case TouchEvent.ACTION_UP: ZoomExample.this.mSmoothCamera.setZoomFactor(1.0f); break; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/ZoomExample.java
Java
lgpl
4,712
package org.anddev.andengine.examples; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X; import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CoordinateConversionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Scene mScene; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "The arrow will always point to the left eye of the face!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_LONG).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 0); arrowLineWingLeft.setColor(1, 0, 0); arrowLineWingRight.setColor(1, 0, 0); /* Create a face-sprite. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion){ @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); final float[] eyeCoordinates = this.convertLocalToSceneCoordinates(11, 13); final float eyeX = eyeCoordinates[VERTEX_INDEX_X]; final float eyeY = eyeCoordinates[VERTEX_INDEX_Y]; arrowLineMain.setPosition(eyeX, eyeY, eyeX, eyeY - 50); arrowLineWingLeft.setPosition(eyeX, eyeY, eyeX - 10, eyeY - 10); arrowLineWingRight.setPosition(eyeX, eyeY, eyeX + 10, eyeY - 10); } }; final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); face.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(3, 1, 1.75f), new ScaleModifier(3, 1.75f, 1)))); this.mScene.attachChild(face); this.mScene.attachChild(arrowLineMain); this.mScene.attachChild(arrowLineWingLeft); this.mScene.attachChild(arrowLineWingRight); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); this.mScene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/CoordinateConversionExample.java
Java
lgpl
10,099
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.entity.util.ScreenCapture; import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.FileUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ScreenCaptureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to capture it (screenshot).", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final ScreenCapture screenCapture = new ScreenCapture(); scene.setBackground(new ColorBackground(0, 0, 0)); /* Create three lines that will form an arrow pointing to the eye. */ final Line arrowLineMain = new Line(0, 0, 0, 0, 3); final Line arrowLineWingLeft = new Line(0, 0, 0, 0, 3); final Line arrowLineWingRight = new Line(0, 0, 0, 0, 3); arrowLineMain.setColor(1, 0, 1); arrowLineWingLeft.setColor(1, 0, 1); arrowLineWingRight.setColor(1, 0, 1); scene.attachChild(arrowLineMain); scene.attachChild(arrowLineWingLeft); scene.attachChild(arrowLineWingRight); /* Create the rectangles. */ final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0); final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0); final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1); final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0); final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2); rectangleGroup.registerEntityModifier(new LoopEntityModifier(new ParallelEntityModifier( new SequenceEntityModifier( new ScaleModifier(10, 1, 0.5f), new ScaleModifier(10, 0.5f, 1) ), new RotationModifier(20, 0, 360)) )); rectangleGroup.attachChild(rect1); rectangleGroup.attachChild(rect2); rectangleGroup.attachChild(rect3); rectangleGroup.attachChild(rect4); scene.attachChild(rectangleGroup); /* Attaching the ScreenCapture to the end. */ scene.attachChild(screenCapture); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { final int viewWidth = ScreenCaptureExample.this.mRenderSurfaceView.getWidth(); final int viewHeight = ScreenCaptureExample.this.mRenderSurfaceView.getHeight(); screenCapture.capture(viewWidth, viewHeight, FileUtils.getAbsolutePathOnExternalStorage(ScreenCaptureExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() { @Override public void onScreenCaptured(final String pFilePath) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onScreenCaptureFailed(final String pFilePath, final Exception pException) { ScreenCaptureExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ScreenCaptureExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show(); } }); } }); } return true; } }); return scene; } private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) { final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180); coloredRect.setColor(pRed, pGreen, pBlue); final Rectangle subRectangle = new Rectangle(45, 45, 90, 90); subRectangle.registerEntityModifier(new LoopEntityModifier(new RotationModifier(3, 0, 360))); coloredRect.attachChild(subRectangle); return coloredRect; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
0bigdream10-tungclone
src/org/anddev/andengine/examples/ScreenCaptureExample.java
Java
lgpl
6,776