text
stringlengths 30
1.67M
|
|---|
<s> package org . eclipse . zest . layouts . algorithms ; public class BoxLayoutAlgorithm extends GridLayoutAlgorithm { public static final int HORIZONTAL = <NUM_LIT:1> ; public static final int VERTICAL = <NUM_LIT:2> ; private int orientation = HORIZONTAL ; public BoxLayoutAlgorithm ( ) { } public BoxLayoutAlgorithm ( int orientation ) { setOrientation ( orientation ) ; } public int getOrientation ( ) { return orientation ; } public void setOrientation ( int orientation ) { if ( orientation == HORIZONTAL || orientation == VERTICAL ) this . orientation = orientation ; else throw new RuntimeException ( "<STR_LIT>" + orientation ) ; } protected int [ ] calculateNumberOfRowsAndCols ( int numChildren , double boundX , double boundY , double boundWidth , double boundHeight ) { if ( orientation == HORIZONTAL ) return new int [ ] { numChildren , <NUM_LIT:1> } ; else return new int [ ] { <NUM_LIT:1> , numChildren } ; } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import java . lang . reflect . Field ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import org . eclipse . draw2d . geometry . Dimension ; import org . eclipse . draw2d . graph . DirectedGraph ; import org . eclipse . draw2d . graph . DirectedGraphLayout ; import org . eclipse . draw2d . graph . Edge ; import org . eclipse . draw2d . graph . Node ; import org . eclipse . zest . layouts . LayoutAlgorithm ; import org . eclipse . zest . layouts . interfaces . ConnectionLayout ; import org . eclipse . zest . layouts . interfaces . EntityLayout ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; import org . eclipse . zest . layouts . interfaces . NodeLayout ; import org . eclipse . zest . layouts . interfaces . SubgraphLayout ; public class DirectedGraphLayoutAlgorithm implements LayoutAlgorithm { class ExtendedDirectedGraphLayout extends DirectedGraphLayout { public void visit ( DirectedGraph graph ) { Field field ; try { field = DirectedGraphLayout . class . getDeclaredField ( "<STR_LIT>" ) ; field . setAccessible ( true ) ; Object object = field . get ( this ) ; List steps = ( List ) object ; field . setAccessible ( false ) ; super . visit ( graph ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } } public static final int HORIZONTAL = <NUM_LIT:1> ; public static final int VERTICAL = <NUM_LIT:2> ; private int orientation = VERTICAL ; private LayoutContext context ; public DirectedGraphLayoutAlgorithm ( ) { } public DirectedGraphLayoutAlgorithm ( int orientation ) { if ( orientation == VERTICAL ) this . orientation = orientation ; } public int getOrientation ( ) { return orientation ; } public void setOrientation ( int orientation ) { if ( orientation == HORIZONTAL || orientation == VERTICAL ) this . orientation = orientation ; } public void applyLayout ( boolean clean ) { if ( ! clean ) return ; HashMap mapping = new HashMap ( ) ; DirectedGraph graph = new DirectedGraph ( ) ; EntityLayout [ ] entities = context . getEntities ( ) ; for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { Node node = new Node ( entities [ i ] ) ; node . setSize ( new Dimension ( <NUM_LIT:10> , <NUM_LIT:10> ) ) ; mapping . put ( entities [ i ] , node ) ; graph . nodes . add ( node ) ; } ConnectionLayout [ ] connections = context . getConnections ( ) ; for ( int i = <NUM_LIT:0> ; i < connections . length ; i ++ ) { Node source = ( Node ) mapping . get ( getEntity ( connections [ i ] . getSource ( ) ) ) ; Node dest = ( Node ) mapping . get ( getEntity ( connections [ i ] . getTarget ( ) ) ) ; if ( source != null && dest != null ) { Edge edge = new Edge ( connections [ i ] , source , dest ) ; graph . edges . add ( edge ) ; } } DirectedGraphLayout directedGraphLayout = new ExtendedDirectedGraphLayout ( ) ; directedGraphLayout . visit ( graph ) ; for ( Iterator iterator = graph . nodes . iterator ( ) ; iterator . hasNext ( ) ; ) { Node node = ( Node ) iterator . next ( ) ; EntityLayout entity = ( EntityLayout ) node . data ; if ( orientation == VERTICAL ) { entity . setLocation ( node . x , node . y ) ; } else { entity . setLocation ( node . y , node . x ) ; } } } private EntityLayout getEntity ( NodeLayout node ) { if ( ! node . isPruned ( ) ) return node ; SubgraphLayout subgraph = node . getSubgraph ( ) ; if ( subgraph . isGraphEntity ( ) ) return subgraph ; return null ; } public void setLayoutContext ( LayoutContext context ) { this . context = context ; } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; public class HorizontalShift extends HorizontalShiftAlgorithm { public HorizontalShift ( int style ) { } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import org . eclipse . zest . layouts . LayoutAlgorithm ; import org . eclipse . zest . layouts . LayoutStyles ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentDimension ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentRectangle ; import org . eclipse . zest . layouts . interfaces . EntityLayout ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; public class GridLayoutAlgorithm implements LayoutAlgorithm { private static final double PADDING_PERCENTAGE = <NUM_LIT> ; private static final int MIN_ENTITY_SIZE = <NUM_LIT:5> ; protected double aspectRatio = <NUM_LIT:1.0> ; protected int rowPadding = <NUM_LIT:0> ; private boolean resize = false ; protected int rows , cols , numChildren ; protected double colWidth , rowHeight , offsetX , offsetY ; protected double childrenHeight , childrenWidth ; private LayoutContext context ; public GridLayoutAlgorithm ( int style ) { this ( ) ; setResizing ( style != LayoutStyles . NO_LAYOUT_NODE_RESIZING ) ; } public GridLayoutAlgorithm ( ) { } public void setLayoutContext ( LayoutContext context ) { this . context = context ; } public void applyLayout ( boolean clean ) { if ( ! clean ) return ; DisplayIndependentRectangle bounds = context . getBounds ( ) ; calculateGrid ( bounds ) ; applyLayoutInternal ( context . getEntities ( ) , bounds ) ; } protected void calculateGrid ( DisplayIndependentRectangle bounds ) { numChildren = context . getNodes ( ) . length ; int [ ] result = calculateNumberOfRowsAndCols ( numChildren , bounds . x , bounds . y , bounds . width , bounds . height ) ; cols = result [ <NUM_LIT:0> ] ; rows = result [ <NUM_LIT:1> ] ; colWidth = bounds . width / cols ; rowHeight = bounds . height / rows ; double [ ] nodeSize = calculateNodeSize ( colWidth , rowHeight ) ; childrenWidth = nodeSize [ <NUM_LIT:0> ] ; childrenHeight = nodeSize [ <NUM_LIT:1> ] ; offsetX = ( colWidth - childrenWidth ) / <NUM_LIT> ; offsetY = ( rowHeight - childrenHeight ) / <NUM_LIT> ; } protected synchronized void applyLayoutInternal ( EntityLayout [ ] entitiesToLayout , DisplayIndependentRectangle bounds ) { int index = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < rows ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < cols ; j ++ ) { if ( ( i * cols + j ) < numChildren ) { EntityLayout node = entitiesToLayout [ index ++ ] ; if ( resize && node . isResizable ( ) ) node . setSize ( Math . max ( childrenWidth , MIN_ENTITY_SIZE ) , Math . max ( childrenHeight , MIN_ENTITY_SIZE ) ) ; DisplayIndependentDimension size = node . getSize ( ) ; double xmove = bounds . x + j * colWidth + offsetX + size . width / <NUM_LIT:2> ; double ymove = bounds . y + i * rowHeight + offsetY + size . height / <NUM_LIT:2> ; if ( node . isMovable ( ) ) node . setLocation ( xmove , ymove ) ; } } } } protected int [ ] calculateNumberOfRowsAndCols ( int numChildren , double boundX , double boundY , double boundWidth , double boundHeight ) { if ( aspectRatio == <NUM_LIT:1.0> ) { return calculateNumberOfRowsAndCols_square ( numChildren , boundX , boundY , boundWidth , boundHeight ) ; } else { return calculateNumberOfRowsAndCols_rectangular ( numChildren ) ; } } protected int [ ] calculateNumberOfRowsAndCols_square ( int numChildren , double boundX , double boundY , double boundWidth , double boundHeight ) { int rows = Math . max ( <NUM_LIT:1> , ( int ) Math . sqrt ( numChildren * boundHeight / boundWidth ) ) ; int cols = Math . max ( <NUM_LIT:1> , ( int ) Math . sqrt ( numChildren * boundWidth / boundHeight ) ) ; if ( boundWidth <= boundHeight ) { while ( rows * cols > numChildren ) { if ( rows > <NUM_LIT:1> ) rows -- ; if ( rows * cols > numChildren ) if ( cols > <NUM_LIT:1> ) cols -- ; } while ( rows * cols < numChildren ) { rows ++ ; if ( rows * cols < numChildren ) cols ++ ; } } else { while ( rows * cols > numChildren ) { if ( cols > <NUM_LIT:1> ) cols -- ; if ( rows * cols > numChildren ) if ( rows > <NUM_LIT:1> ) rows -- ; } while ( rows * cols < numChildren ) { cols ++ ; if ( rows * cols < numChildren ) rows ++ ; } } int [ ] result = { cols , rows } ; return result ; } protected int [ ] calculateNumberOfRowsAndCols_rectangular ( int numChildren ) { int rows = Math . max ( <NUM_LIT:1> , ( int ) Math . ceil ( Math . sqrt ( numChildren ) ) ) ; int cols = Math . max ( <NUM_LIT:1> , ( int ) Math . ceil ( Math . sqrt ( numChildren ) ) ) ; int [ ] result = { cols , rows } ; return result ; } protected double [ ] calculateNodeSize ( double colWidth , double rowHeight ) { double childW = Math . max ( MIN_ENTITY_SIZE , PADDING_PERCENTAGE * colWidth ) ; double childH = Math . max ( MIN_ENTITY_SIZE , PADDING_PERCENTAGE * ( rowHeight - rowPadding ) ) ; double whRatio = colWidth / rowHeight ; if ( whRatio < aspectRatio ) { childH = childW / aspectRatio ; } else { childW = childH * aspectRatio ; } double [ ] result = { childW , childH } ; return result ; } public void setRowPadding ( int rowPadding ) { if ( rowPadding >= <NUM_LIT:0> ) { this . rowPadding = rowPadding ; } } public void setAspectRatio ( double aspectRatio ) { if ( aspectRatio > <NUM_LIT:0> ) { this . aspectRatio = aspectRatio ; } } public boolean isResizing ( ) { return resize ; } public void setResizing ( boolean resizing ) { resize = resizing ; } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . ListIterator ; import org . eclipse . zest . layouts . LayoutAlgorithm ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentDimension ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentPoint ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentRectangle ; import org . eclipse . zest . layouts . interfaces . ContextListener ; import org . eclipse . zest . layouts . interfaces . ExpandCollapseManager ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; import org . eclipse . zest . layouts . interfaces . LayoutListener ; import org . eclipse . zest . layouts . interfaces . NodeLayout ; import org . eclipse . zest . layouts . interfaces . SubgraphLayout ; public class SpaceTreeLayoutAlgorithm implements LayoutAlgorithm { public final static int TOP_DOWN = <NUM_LIT:1> ; public final static int BOTTOM_UP = <NUM_LIT:2> ; public final static int LEFT_RIGHT = <NUM_LIT:3> ; public final static int RIGHT_LEFT = <NUM_LIT:4> ; private class SpaceTreeNode extends TreeLayoutObserver . TreeNode { public SubgraphLayout subgraph = null ; public boolean expanded = false ; public double positionInLayer ; public SpaceTreeNode ( NodeLayout node , TreeLayoutObserver owner ) { super ( node , owner ) ; } protected void addChild ( TreeLayoutObserver . TreeNode child ) { super . addChild ( child ) ; SpaceTreeNode child2 = ( SpaceTreeNode ) child ; child2 . expanded = false ; child2 . setSubgraph ( null ) ; if ( child . depth >= <NUM_LIT:0> ) ( ( SpaceTreeLayer ) spaceTreeLayers . get ( child . depth ) ) . removeNode ( child2 ) ; if ( expanded ) { child . depth = this . depth + <NUM_LIT:1> ; SpaceTreeLayer childLayer ; if ( child . depth < spaceTreeLayers . size ( ) ) childLayer = ( ( SpaceTreeLayer ) spaceTreeLayers . get ( child . depth ) ) ; else spaceTreeLayers . add ( childLayer = new SpaceTreeLayer ( child . depth ) ) ; if ( childLayer . nodes . isEmpty ( ) ) child . order = <NUM_LIT:0> ; else child . order = ( ( SpaceTreeNode ) childLayer . nodes . get ( childLayer . nodes . size ( ) - <NUM_LIT:1> ) ) . order + <NUM_LIT:1> ; childLayer . addNodes ( Arrays . asList ( new Object [ ] { child } ) ) ; } } public void precomputeTree ( ) { super . precomputeTree ( ) ; if ( this == owner . getSuperRoot ( ) ) { expanded = true ; while ( spaceTreeLayers . size ( ) <= this . height ) spaceTreeLayers . add ( new SpaceTreeLayer ( spaceTreeLayers . size ( ) ) ) ; if ( treeObserver != null ) refreshLayout ( true ) ; } } public SubgraphLayout collapseAllChildrenIntoSubgraph ( SubgraphLayout subgraph , boolean includeYourself ) { expanded = false ; ArrayList allChildren = new ArrayList ( ) ; LinkedList nodesToVisit = new LinkedList ( ) ; nodesToVisit . addLast ( this ) ; while ( ! nodesToVisit . isEmpty ( ) ) { SpaceTreeNode currentNode = ( SpaceTreeNode ) nodesToVisit . removeFirst ( ) ; for ( Iterator iterator = currentNode . children . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode child = ( SpaceTreeNode ) iterator . next ( ) ; allChildren . add ( child . node ) ; child . setSubgraph ( null ) ; child . expanded = false ; nodesToVisit . addLast ( child ) ; } } if ( includeYourself ) allChildren . add ( this . node ) ; if ( allChildren . isEmpty ( ) ) { setSubgraph ( null ) ; return null ; } NodeLayout [ ] childrenArray = ( NodeLayout [ ] ) allChildren . toArray ( new NodeLayout [ allChildren . size ( ) ] ) ; if ( subgraph == null ) { subgraph = context . createSubgraph ( childrenArray ) ; subgraph . setDirection ( getSubgraphDirection ( ) ) ; } else { subgraph . addNodes ( childrenArray ) ; } if ( ! includeYourself ) setSubgraph ( subgraph ) ; return subgraph ; } public void setSubgraph ( SubgraphLayout subgraph ) { if ( this . subgraph != subgraph ) { this . subgraph = subgraph ; refreshSubgraphLocation ( ) ; } } public void adjustPosition ( DisplayIndependentPoint preferredLocation ) { protectedNode = ( SpaceTreeNode ) owner . getSuperRoot ( ) ; double newPositionInLayer = ( direction == BOTTOM_UP || direction == TOP_DOWN ) ? preferredLocation . x : preferredLocation . y ; if ( ( ( SpaceTreeNode ) parent ) . expanded ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( depth ) ) . moveNode ( this , newPositionInLayer ) ; centerParentsTopDown ( ) ; } } public void refreshSubgraphLocation ( ) { if ( subgraph != null && subgraph . isGraphEntity ( ) ) { DisplayIndependentPoint nodeLocation = node . getLocation ( ) ; DisplayIndependentDimension nodeSize = node . getSize ( ) ; DisplayIndependentDimension subgraphSize = subgraph . getSize ( ) ; double x = <NUM_LIT:0> , y = <NUM_LIT:0> ; switch ( direction ) { case TOP_DOWN : x = nodeLocation . x ; y = nodeLocation . y + ( nodeSize . height + subgraphSize . height ) / <NUM_LIT:2> ; break ; case BOTTOM_UP : x = nodeLocation . x ; y = nodeLocation . y - ( nodeSize . height + subgraphSize . height ) / <NUM_LIT:2> ; break ; case LEFT_RIGHT : x = nodeLocation . x + ( nodeSize . width + subgraphSize . width ) / <NUM_LIT:2> ; y = nodeLocation . y ; break ; case RIGHT_LEFT : x = nodeLocation . x - ( nodeSize . width + subgraphSize . height ) / <NUM_LIT:2> ; y = nodeLocation . y ; break ; } subgraph . setLocation ( x , y ) ; } ( ( SpaceTreeLayer ) spaceTreeLayers . get ( depth ) ) . refreshThickness ( ) ; } public double spaceRequiredForNode ( ) { if ( node == null ) return <NUM_LIT:0> ; switch ( direction ) { case TOP_DOWN : case BOTTOM_UP : return node . getSize ( ) . width ; case LEFT_RIGHT : case RIGHT_LEFT : return node . getSize ( ) . height ; } throw new RuntimeException ( "<STR_LIT>" ) ; } public double spaceRequiredForChildren ( ) { if ( children . isEmpty ( ) ) return <NUM_LIT:0> ; double result = <NUM_LIT:0> ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode child = ( SpaceTreeNode ) iterator . next ( ) ; result += child . spaceRequiredForNode ( ) ; } result += leafGap * ( children . size ( ) - <NUM_LIT:1> ) ; return result ; } public boolean childrenPositionsOK ( ArrayList nodesToCheck ) { for ( Iterator iterator = nodesToCheck . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode node = ( SpaceTreeNode ) iterator . next ( ) ; if ( node . depth < <NUM_LIT:0> || node . children . isEmpty ( ) ) continue ; SpaceTreeNode child = ( ( SpaceTreeNode ) node . children . get ( <NUM_LIT:0> ) ) ; if ( child . positionInLayer > node . positionInLayer ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( node . depth ) ) . moveNode ( node , child . positionInLayer ) ; if ( child . positionInLayer > node . positionInLayer ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( child . depth ) ) . moveNode ( child , node . positionInLayer ) ; if ( child . positionInLayer > node . positionInLayer ) { return false ; } } } child = ( ( SpaceTreeNode ) node . children . get ( node . children . size ( ) - <NUM_LIT:1> ) ) ; if ( child . positionInLayer < node . positionInLayer ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( node . depth ) ) . moveNode ( node , child . positionInLayer ) ; if ( child . positionInLayer < node . positionInLayer ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( child . depth ) ) . moveNode ( child , node . positionInLayer ) ; if ( child . positionInLayer < node . positionInLayer ) { return false ; } } } } return true ; } public void centerParentsBottomUp ( ) { if ( ! children . isEmpty ( ) && expanded ) { for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { ( ( SpaceTreeNode ) iterator . next ( ) ) . centerParentsBottomUp ( ) ; } if ( depth >= <NUM_LIT:0> ) { SpaceTreeNode firstChild = ( SpaceTreeNode ) children . get ( <NUM_LIT:0> ) ; SpaceTreeNode lastChild = ( SpaceTreeNode ) children . get ( children . size ( ) - <NUM_LIT:1> ) ; SpaceTreeLayer layer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth ) ; layer . moveNode ( this , ( firstChild . positionInLayer + lastChild . positionInLayer ) / <NUM_LIT:2> ) ; } } } public void centerParentsTopDown ( ) { if ( this == owner . getSuperRoot ( ) ) { this . positionInLayer = getAvailableSpace ( ) / <NUM_LIT:2> ; } if ( ! children . isEmpty ( ) && expanded ) { SpaceTreeNode firstChild = ( SpaceTreeNode ) children . get ( <NUM_LIT:0> ) ; SpaceTreeNode lastChild = ( SpaceTreeNode ) children . get ( children . size ( ) - <NUM_LIT:1> ) ; double offset = this . positionInLayer - ( firstChild . positionInLayer + lastChild . positionInLayer ) / <NUM_LIT:2> ; if ( firstChild . positionInLayer - firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> + offset < <NUM_LIT:0> ) offset = - firstChild . positionInLayer + firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ; double availableSpace = getAvailableSpace ( ) ; if ( lastChild . positionInLayer + lastChild . spaceRequiredForNode ( ) / <NUM_LIT:2> + offset > availableSpace ) { offset = availableSpace - lastChild . positionInLayer - lastChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ; } SpaceTreeLayer layer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth + <NUM_LIT:1> ) ; layer . fitNodesWithinBounds ( children , firstChild . positionInLayer + offset , lastChild . positionInLayer + offset ) ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { ( ( SpaceTreeNode ) iterator . next ( ) ) . centerParentsTopDown ( ) ; } } } public void flushExpansionChanges ( ) { if ( node != null ) node . prune ( null ) ; if ( this . expanded ) { setSubgraph ( null ) ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { ( ( SpaceTreeNode ) iterator . next ( ) ) . flushExpansionChanges ( ) ; } } if ( ! this . expanded && subgraph == null ) { collapseAllChildrenIntoSubgraph ( null , false ) ; } } public boolean flushCollapseChanges ( ) { if ( ! expanded ) { int numberOfChildrenInSubgraph = subgraph == null ? <NUM_LIT:0> : subgraph . countNodes ( ) ; collapseAllChildrenIntoSubgraph ( subgraph , false ) ; int newNumberOfChildrenInSubgraph = ( subgraph == null ? <NUM_LIT:0> : subgraph . countNodes ( ) ) ; if ( numberOfChildrenInSubgraph != newNumberOfChildrenInSubgraph && newNumberOfChildrenInSubgraph > <NUM_LIT:0> ) refreshSubgraphLocation ( ) ; return numberOfChildrenInSubgraph != newNumberOfChildrenInSubgraph ; } if ( expanded && subgraph == null ) { boolean madeChagnes = false ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { madeChagnes = ( ( SpaceTreeNode ) iterator . next ( ) ) . flushCollapseChanges ( ) || madeChagnes ; } return madeChagnes ; } return false ; } public boolean flushLocationChanges ( double thicknessSoFar ) { boolean madeChanges = false ; if ( node != null ) { DisplayIndependentDimension nodeSize = node . getSize ( ) ; double x = <NUM_LIT:0> , y = <NUM_LIT:0> ; switch ( direction ) { case TOP_DOWN : x = bounds . x + positionInLayer ; y = thicknessSoFar + nodeSize . height / <NUM_LIT:2> ; break ; case BOTTOM_UP : x = bounds . x + positionInLayer ; y = bounds . y + bounds . height - thicknessSoFar - nodeSize . height / <NUM_LIT:2> ; break ; case LEFT_RIGHT : x = thicknessSoFar + nodeSize . height / <NUM_LIT:2> ; y = bounds . y + positionInLayer ; break ; case RIGHT_LEFT : x = bounds . x + bounds . width - thicknessSoFar - nodeSize . height / <NUM_LIT:2> ; y = bounds . y + positionInLayer ; break ; } DisplayIndependentPoint currentLocation = node . getLocation ( ) ; if ( currentLocation . x != x || currentLocation . y != y ) { node . setLocation ( x , y ) ; refreshSubgraphLocation ( ) ; madeChanges = true ; } } if ( expanded && subgraph == null ) { thicknessSoFar += ( depth >= <NUM_LIT:0> ? ( ( SpaceTreeLayer ) spaceTreeLayers . get ( depth ) ) . thickness : <NUM_LIT:0> ) + layerGap ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode child = ( SpaceTreeNode ) iterator . next ( ) ; madeChanges = child . flushLocationChanges ( thicknessSoFar ) || madeChanges ; } } return madeChanges ; } public String toString ( ) { StringBuffer sb = new StringBuffer ( ) ; for ( int i = <NUM_LIT:0> ; i < depth ; i ++ ) sb . append ( "<STR_LIT:U+0020>" ) ; if ( node != null ) sb . append ( node . toString ( ) ) ; sb . append ( "<STR_LIT:|>" + this . order ) ; sb . append ( '<STR_LIT:\n>' ) ; for ( Iterator iterator = children . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode child = ( SpaceTreeNode ) iterator . next ( ) ; sb . append ( child . toString ( ) ) ; } return sb . toString ( ) ; } } private TreeLayoutObserver . TreeNodeFactory spaceTreeNodeFactory = new TreeLayoutObserver . TreeNodeFactory ( ) { public TreeLayoutObserver . TreeNode createTreeNode ( NodeLayout nodeLayout , TreeLayoutObserver observer ) { return new SpaceTreeNode ( nodeLayout , observer ) ; } ; } ; private class SpaceTreeLayer { public ArrayList nodes = new ArrayList ( ) ; private final int depth ; public double thickness = <NUM_LIT:0> ; public SpaceTreeLayer ( int depth ) { this . depth = depth ; } public void addNodes ( List nodesToAdd ) { ListIterator layerIterator = nodes . listIterator ( ) ; SpaceTreeNode previousNode = null ; for ( Iterator iterator = nodesToAdd . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode nodeToAdd = ( SpaceTreeNode ) iterator . next ( ) ; SpaceTreeNode nodeInLayer = null ; while ( layerIterator . hasNext ( ) ) { nodeInLayer = ( SpaceTreeNode ) layerIterator . next ( ) ; if ( nodeInLayer . order >= nodeToAdd . order ) break ; double expectedPostion = ( previousNode == null ) ? <NUM_LIT:0> : previousNode . positionInLayer + expectedDistance ( previousNode , nodeInLayer ) ; nodeInLayer . positionInLayer = Math . max ( nodeInLayer . positionInLayer , expectedPostion ) ; previousNode = nodeInLayer ; } if ( nodeInLayer == null ) { layerIterator . add ( nodeToAdd ) ; } else if ( nodeInLayer . order == nodeToAdd . order ) { layerIterator . set ( nodeToAdd ) ; } else { if ( nodeInLayer . order > nodeToAdd . order ) layerIterator . previous ( ) ; layerIterator . add ( nodeToAdd ) ; } layerIterator . previous ( ) ; } while ( layerIterator . hasNext ( ) ) { SpaceTreeNode nodeInLayer = ( SpaceTreeNode ) layerIterator . next ( ) ; double expectedPostion = ( previousNode == null ) ? <NUM_LIT:0> : previousNode . positionInLayer + expectedDistance ( previousNode , nodeInLayer ) ; nodeInLayer . positionInLayer = Math . max ( nodeInLayer . positionInLayer , expectedPostion ) ; previousNode = nodeInLayer ; } refreshThickness ( ) ; } public void removeNode ( SpaceTreeNode node ) { if ( nodes . remove ( node ) ) { ( ( SpaceTreeLayer ) spaceTreeLayers . get ( depth + <NUM_LIT:1> ) ) . removeNodes ( node . children ) ; refreshThickness ( ) ; } } public void removeNodes ( List nodesToRemove ) { if ( this . nodes . removeAll ( nodesToRemove ) ) { SpaceTreeLayer nextLayer = ( ( SpaceTreeLayer ) spaceTreeLayers . get ( depth + <NUM_LIT:1> ) ) ; for ( Iterator iterator = nodesToRemove . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode nodeToRemove = ( SpaceTreeNode ) iterator . next ( ) ; nextLayer . removeNodes ( nodeToRemove . children ) ; } refreshThickness ( ) ; } } public void checkThickness ( SpaceTreeNode node ) { double nodeThickness = <NUM_LIT:0> ; DisplayIndependentDimension size = node . node . getSize ( ) ; nodeThickness = ( direction == TOP_DOWN || direction == BOTTOM_UP ) ? size . height : size . width ; if ( node . subgraph != null && node . subgraph . isGraphEntity ( ) ) { size = node . subgraph . getSize ( ) ; nodeThickness += ( direction == TOP_DOWN || direction == BOTTOM_UP ) ? size . height : size . width ; } this . thickness = Math . max ( this . thickness , nodeThickness ) ; } public void refreshThickness ( ) { this . thickness = <NUM_LIT:0> ; for ( Iterator iterator = nodes . iterator ( ) ; iterator . hasNext ( ) ; ) { checkThickness ( ( SpaceTreeNode ) iterator . next ( ) ) ; } } public void fitNodesWithinBounds ( List nodeList , double startPosition , double endPosition ) { NodeSnapshot [ ] [ ] snapShot = takeSnapShot ( ) ; SpaceTreeNode [ ] nodes = ( SpaceTreeNode [ ] ) nodeList . toArray ( new SpaceTreeNode [ nodeList . size ( ) ] ) ; double initialStartPosition = nodes [ <NUM_LIT:0> ] . positionInLayer ; double initialNodesBredth = nodes [ nodes . length - <NUM_LIT:1> ] . positionInLayer - initialStartPosition ; double [ ] desiredPositions = new double [ nodes . length ] ; for ( int i = <NUM_LIT:0> ; i < nodes . length ; i ++ ) { double initialPositionAsPercent = ( initialNodesBredth > <NUM_LIT:0> ) ? ( nodes [ i ] . positionInLayer - initialStartPosition ) / initialNodesBredth : <NUM_LIT:0> ; desiredPositions [ i ] = initialPositionAsPercent * ( endPosition - startPosition ) ; } for ( int i = <NUM_LIT:1> ; i < nodes . length ; i ++ ) { SpaceTreeNode node = nodes [ i ] ; SpaceTreeNode previousNode = nodes [ i - <NUM_LIT:1> ] ; double expectedDistance = expectedDistance ( previousNode , node ) ; if ( desiredPositions [ i ] - desiredPositions [ i - <NUM_LIT:1> ] < expectedDistance ) { desiredPositions [ i ] = desiredPositions [ i - <NUM_LIT:1> ] + expectedDistance ; } } if ( desiredPositions [ nodes . length - <NUM_LIT:1> ] > ( endPosition - startPosition ) ) { desiredPositions [ nodes . length - <NUM_LIT:1> ] = ( endPosition - startPosition ) ; for ( int i = nodes . length - <NUM_LIT:1> ; i > <NUM_LIT:0> ; i -- ) { SpaceTreeNode node = nodes [ i ] ; SpaceTreeNode previousNode = nodes [ i - <NUM_LIT:1> ] ; double expectedDistance = expectedDistance ( previousNode , node ) ; if ( desiredPositions [ i ] - desiredPositions [ i - <NUM_LIT:1> ] < expectedDistance ) { desiredPositions [ i - <NUM_LIT:1> ] = desiredPositions [ i ] - expectedDistance ; } else break ; } } for ( int i = <NUM_LIT:0> ; i < nodeList . size ( ) ; i ++ ) { SpaceTreeNode node = ( SpaceTreeNode ) nodeList . get ( i ) ; double desiredPosition = startPosition + desiredPositions [ i ] ; moveNode ( node , desiredPosition ) ; if ( Math . abs ( node . positionInLayer - desiredPosition ) > <NUM_LIT> ) { startPosition += ( node . positionInLayer - desiredPosition ) ; i = - <NUM_LIT:1> ; revertToShanpshot ( snapShot ) ; } } } public void moveNode ( SpaceTreeNode node , double newPosition ) { Collections . sort ( nodes , new Comparator ( ) { public int compare ( Object arg0 , Object arg1 ) { return ( ( SpaceTreeNode ) arg0 ) . order - ( ( SpaceTreeNode ) arg1 ) . order ; } } ) ; double positionInLayerAtStart = node . positionInLayer ; if ( newPosition >= positionInLayerAtStart ) moveNodeForward ( node , newPosition ) ; if ( newPosition <= positionInLayerAtStart ) moveNodeBackward ( node , newPosition ) ; } private void moveNodeForward ( SpaceTreeNode nodeToMove , double newPosition ) { int nodeIndex = nodes . indexOf ( nodeToMove ) ; if ( nodeIndex == - <NUM_LIT:1> ) throw new IllegalArgumentException ( "<STR_LIT>" ) ; NodeSnapshot [ ] [ ] snapShot = takeSnapShot ( ) ; boolean firstRun = true ; mainLoop : while ( firstRun || nodeToMove . positionInLayer < newPosition ) { firstRun = false ; double requiredSpace = <NUM_LIT:0> ; SpaceTreeNode previousNode = nodeToMove ; for ( int i = nodeIndex + <NUM_LIT:1> ; i < nodes . size ( ) ; i ++ ) { SpaceTreeNode nextNode = ( SpaceTreeNode ) nodes . get ( i ) ; requiredSpace += expectedDistance ( previousNode , nextNode ) ; previousNode = nextNode ; } requiredSpace += previousNode . spaceRequiredForNode ( ) / <NUM_LIT:2> ; if ( requiredSpace > getAvailableSpace ( ) - newPosition ) { boolean removed = false ; for ( int i = nodeIndex ; i < nodes . size ( ) ; i ++ ) { SpaceTreeNode nextNode = ( ( SpaceTreeNode ) nodes . get ( i ) ) ; if ( protectedNode == null || ( ! protectedNode . isAncestorOf ( nextNode ) && ! nextNode . parent . isAncestorOf ( protectedNode ) ) ) { collapseNode ( ( SpaceTreeNode ) nextNode . parent ) ; if ( nextNode . parent == nodeToMove . parent ) break mainLoop ; removed = true ; break ; } } if ( ! removed ) { newPosition = getAvailableSpace ( ) - requiredSpace ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } SpaceTreeNode currentNodeToMove = nodeToMove ; double newPositionForCurrent = newPosition ; for ( int i = nodeIndex ; i < nodes . size ( ) ; i ++ ) { currentNodeToMove . positionInLayer = newPositionForCurrent ; if ( currentNodeToMove . firstChild ) { SpaceTreeNode parent = ( SpaceTreeNode ) currentNodeToMove . parent ; if ( depth > <NUM_LIT:0> && parent . positionInLayer <= newPositionForCurrent ) { SpaceTreeLayer parentLayer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth - <NUM_LIT:1> ) ; parentLayer . moveNodeForward ( parent , newPositionForCurrent ) ; if ( parent . positionInLayer < newPositionForCurrent ) { double delta = newPositionForCurrent - parent . positionInLayer ; newPosition -= delta ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } } if ( currentNodeToMove . expanded && ! currentNodeToMove . children . isEmpty ( ) ) { SpaceTreeNode lastChild = ( SpaceTreeNode ) currentNodeToMove . children . get ( currentNodeToMove . children . size ( ) - <NUM_LIT:1> ) ; if ( lastChild . positionInLayer < newPositionForCurrent ) { SpaceTreeNode firstChild = ( SpaceTreeNode ) currentNodeToMove . children . get ( <NUM_LIT:0> ) ; SpaceTreeLayer childLayer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth + <NUM_LIT:1> ) ; double expectedDistanceBetweenChildren = currentNodeToMove . spaceRequiredForChildren ( ) - firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> - lastChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ; childLayer . moveNodeForward ( firstChild , newPositionForCurrent - expectedDistanceBetweenChildren ) ; if ( currentNodeToMove . expanded && lastChild . positionInLayer < newPositionForCurrent ) { childLayer . moveNodeForward ( lastChild , newPositionForCurrent ) ; if ( lastChild . positionInLayer < newPositionForCurrent ) { double delta = newPositionForCurrent - lastChild . positionInLayer ; newPosition -= delta ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } } } if ( i < nodes . size ( ) - <NUM_LIT:1> ) { SpaceTreeNode nextNode = ( SpaceTreeNode ) nodes . get ( i + <NUM_LIT:1> ) ; newPositionForCurrent += expectedDistance ( currentNodeToMove , nextNode ) ; currentNodeToMove = nextNode ; if ( currentNodeToMove . positionInLayer > newPositionForCurrent ) break ; } } } } private void moveNodeBackward ( SpaceTreeNode nodeToMove , double newPosition ) { int nodeIndex = nodes . indexOf ( nodeToMove ) ; if ( nodeIndex == - <NUM_LIT:1> ) throw new IllegalArgumentException ( "<STR_LIT>" ) ; NodeSnapshot [ ] [ ] snapShot = takeSnapShot ( ) ; boolean firstRun = true ; mainLoop : while ( firstRun || nodeToMove . positionInLayer > newPosition ) { firstRun = false ; double requiredSpace = <NUM_LIT:0> ; SpaceTreeNode previousNode = nodeToMove ; for ( int i = nodeIndex - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { SpaceTreeNode nextNode = ( SpaceTreeNode ) nodes . get ( i ) ; requiredSpace += expectedDistance ( previousNode , nextNode ) ; previousNode = nextNode ; } requiredSpace += previousNode . spaceRequiredForNode ( ) / <NUM_LIT:2> ; if ( requiredSpace > newPosition ) { boolean removed = false ; for ( int i = nodeIndex ; i >= <NUM_LIT:0> ; i -- ) { SpaceTreeNode nextNode = ( ( SpaceTreeNode ) nodes . get ( i ) ) ; if ( protectedNode == null || ( ! protectedNode . isAncestorOf ( nextNode ) && ! nextNode . parent . isAncestorOf ( protectedNode ) ) ) { collapseNode ( ( SpaceTreeNode ) nextNode . parent ) ; if ( nextNode . parent == nodeToMove . parent ) break mainLoop ; nodeIndex -= nextNode . parent . children . size ( ) ; removed = true ; break ; } } if ( ! removed ) { newPosition = requiredSpace ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } SpaceTreeNode currentNodeToMove = nodeToMove ; double newPositionForCurrent = newPosition ; for ( int i = nodeIndex ; i >= <NUM_LIT:0> ; i -- ) { currentNodeToMove . positionInLayer = newPositionForCurrent ; if ( currentNodeToMove . lastChild ) { SpaceTreeNode parent = ( SpaceTreeNode ) currentNodeToMove . parent ; if ( depth > <NUM_LIT:0> && parent . positionInLayer >= newPositionForCurrent ) { SpaceTreeLayer parentLayer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth - <NUM_LIT:1> ) ; parentLayer . moveNodeBackward ( parent , newPositionForCurrent ) ; if ( parent . positionInLayer > newPositionForCurrent ) { double delta = parent . positionInLayer - newPositionForCurrent ; newPosition += delta ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } } if ( currentNodeToMove . expanded && ! currentNodeToMove . children . isEmpty ( ) ) { SpaceTreeNode firstChild = ( SpaceTreeNode ) currentNodeToMove . children . get ( <NUM_LIT:0> ) ; if ( firstChild . positionInLayer > newPositionForCurrent ) { SpaceTreeNode lastChild = ( SpaceTreeNode ) currentNodeToMove . children . get ( currentNodeToMove . children . size ( ) - <NUM_LIT:1> ) ; SpaceTreeLayer childLayer = ( SpaceTreeLayer ) spaceTreeLayers . get ( depth + <NUM_LIT:1> ) ; double expectedDistanceBetweenChildren = currentNodeToMove . spaceRequiredForChildren ( ) - firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> - lastChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ; childLayer . moveNodeBackward ( lastChild , newPositionForCurrent + expectedDistanceBetweenChildren ) ; if ( currentNodeToMove . expanded && firstChild . positionInLayer > newPositionForCurrent ) { childLayer . moveNodeBackward ( firstChild , newPositionForCurrent ) ; if ( firstChild . positionInLayer > newPositionForCurrent ) { double delta = firstChild . positionInLayer - newPositionForCurrent ; newPosition += delta ; revertToShanpshot ( snapShot ) ; continue mainLoop ; } } } } if ( i > <NUM_LIT:0> ) { SpaceTreeNode nextNode = ( SpaceTreeNode ) nodes . get ( i - <NUM_LIT:1> ) ; newPositionForCurrent -= expectedDistance ( currentNodeToMove , nextNode ) ; currentNodeToMove = nextNode ; if ( currentNodeToMove . positionInLayer < newPositionForCurrent ) break ; } } } } public String toString ( ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "<STR_LIT>" ) . append ( depth ) . append ( "<STR_LIT::U+0020>" ) ; for ( Iterator iterator = nodes . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode node = ( SpaceTreeNode ) iterator . next ( ) ; buffer . append ( node . node ) . append ( "<STR_LIT:U+002CU+0020>" ) ; } return buffer . toString ( ) ; } private void collapseNode ( SpaceTreeNode node ) { node . expanded = false ; SpaceTreeLayer layer = ( SpaceTreeLayer ) spaceTreeLayers . get ( node . depth + <NUM_LIT:1> ) ; layer . removeNodes ( node . children ) ; for ( Iterator iterator = node . children . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode child = ( SpaceTreeNode ) iterator . next ( ) ; if ( child . expanded ) collapseNode ( child ) ; } } } private class SpaceTreeExpandCollapseManager implements ExpandCollapseManager { public void initExpansion ( LayoutContext context ) { } public void setExpanded ( LayoutContext context , NodeLayout node , boolean expanded ) { SpaceTreeNode spaceTreeNode = ( SpaceTreeNode ) treeObserver . getTreeNode ( node ) ; if ( expanded ) { maximizeExpansion ( spaceTreeNode ) ; refreshLayout ( true ) ; } else if ( spaceTreeNode . expanded ) { spaceTreeNode . expanded = false ; ( ( SpaceTreeLayer ) spaceTreeLayers . get ( spaceTreeNode . depth + <NUM_LIT:1> ) ) . removeNodes ( spaceTreeNode . children ) ; refreshLayout ( true ) ; } } public boolean canExpand ( LayoutContext context , NodeLayout node ) { SpaceTreeNode spaceTreeNode = ( SpaceTreeNode ) treeObserver . getTreeNode ( node ) ; if ( spaceTreeNode != null ) { return ! spaceTreeNode . children . isEmpty ( ) ; } return false ; } public boolean canCollapse ( LayoutContext context , NodeLayout node ) { SpaceTreeNode spaceTreeNode = ( SpaceTreeNode ) treeObserver . getTreeNode ( node ) ; if ( spaceTreeNode != null ) { return spaceTreeNode . expanded && ! spaceTreeNode . children . isEmpty ( ) ; } return false ; } public void maximizeExpansion ( SpaceTreeNode nodeToExpand ) { protectedNode = nodeToExpand ; double availableSpace = getAvailableSpace ( ) ; double requiredSpace = <NUM_LIT:0> ; ( ( SpaceTreeLayer ) spaceTreeLayers . get ( nodeToExpand . depth + <NUM_LIT:1> ) ) . removeNodes ( nodeToExpand . children ) ; ArrayList nodesInThisLayer = null ; ArrayList nodesInNextLayer = new ArrayList ( ) ; nodesInNextLayer . add ( nodeToExpand ) ; double spaceRequiredInNextLayer = nodeToExpand . spaceRequiredForNode ( ) ; for ( int layer = <NUM_LIT:0> ; ! nodesInNextLayer . isEmpty ( ) ; layer ++ ) { NodeSnapshot [ ] [ ] snapShot = takeSnapShot ( ) ; requiredSpace = Math . max ( requiredSpace , spaceRequiredInNextLayer ) ; spaceRequiredInNextLayer = <NUM_LIT:0> ; nodesInThisLayer = nodesInNextLayer ; nodesInNextLayer = new ArrayList ( ) ; int numOfNodesWithChildren = <NUM_LIT:0> ; for ( Iterator iterator = nodesInThisLayer . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode node = ( SpaceTreeNode ) iterator . next ( ) ; if ( ! node . children . isEmpty ( ) ) { node . expanded = true ; spaceRequiredInNextLayer += node . spaceRequiredForChildren ( ) ; nodesInNextLayer . addAll ( node . children ) ; numOfNodesWithChildren ++ ; } } for ( Iterator iterator = nodesInNextLayer . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeNode node = ( SpaceTreeNode ) iterator . next ( ) ; node . expanded = false ; } if ( numOfNodesWithChildren == <NUM_LIT:0> ) break ; spaceRequiredInNextLayer += branchGap * ( numOfNodesWithChildren - <NUM_LIT:1> ) ; boolean addedNewLayer = false ; if ( ( spaceRequiredInNextLayer <= requiredSpace || spaceRequiredInNextLayer <= availableSpace || ( layer < <NUM_LIT:1> && nodeToExpand . depth + layer < <NUM_LIT:1> ) ) && ! nodesInNextLayer . isEmpty ( ) ) { SpaceTreeLayer childLayer = ( SpaceTreeLayer ) spaceTreeLayers . get ( nodeToExpand . depth + layer + <NUM_LIT:1> ) ; childLayer . addNodes ( nodesInNextLayer ) ; SpaceTreeNode firstChild = ( ( SpaceTreeNode ) nodesInNextLayer . get ( <NUM_LIT:0> ) ) ; SpaceTreeNode lastChild = ( ( SpaceTreeNode ) nodesInNextLayer . get ( nodesInNextLayer . size ( ) - <NUM_LIT:1> ) ) ; double boundsWidth = spaceRequiredInNextLayer - firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> - lastChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ; double startPosition = Math . max ( ( availableSpace - boundsWidth ) / <NUM_LIT:2> , firstChild . spaceRequiredForNode ( ) / <NUM_LIT:2> ) ; setAvailableSpace ( spaceRequiredInNextLayer ) ; childLayer . fitNodesWithinBounds ( nodesInNextLayer , startPosition , startPosition + boundsWidth ) ; setAvailableSpace ( <NUM_LIT:0> ) ; if ( nodeToExpand . childrenPositionsOK ( nodesInThisLayer ) || layer == <NUM_LIT:0> || nodeToExpand . depth + layer < <NUM_LIT:1> ) addedNewLayer = true ; } if ( ! addedNewLayer ) { revertToShanpshot ( snapShot ) ; break ; } } nodeToExpand . centerParentsBottomUp ( ) ; nodeToExpand . centerParentsTopDown ( ) ; } } ; private SpaceTreeExpandCollapseManager expandCollapseManager = new SpaceTreeExpandCollapseManager ( ) ; private ContextListener contextListener = new ContextListener . Stub ( ) { public boolean boundsChanged ( LayoutContext context ) { boolean previousBoundsWrong = ( bounds == null || bounds . width * bounds . height <= <NUM_LIT:0> ) ; bounds = context . getBounds ( ) ; if ( bounds . width * bounds . height > <NUM_LIT:0> && previousBoundsWrong ) { expandCollapseManager . maximizeExpansion ( ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ) ; refreshLayout ( false ) ; } return false ; } } ; private LayoutListener layoutListener = new LayoutListener ( ) { public boolean subgraphResized ( LayoutContext context , SubgraphLayout subgraph ) { return defaultSubgraphHandle ( context , subgraph ) ; } public boolean subgraphMoved ( LayoutContext context , SubgraphLayout subgraph ) { return defaultSubgraphHandle ( context , subgraph ) ; } public boolean nodeResized ( LayoutContext context , NodeLayout node ) { setAvailableSpace ( getAvailableSpace ( ) + ( ( SpaceTreeNode ) treeObserver . getTreeNode ( node ) ) . spaceRequiredForNode ( ) ) ; boolean result = defaultNodeHandle ( context , node ) ; setAvailableSpace ( <NUM_LIT:0> ) ; return result ; } public boolean nodeMoved ( LayoutContext context , NodeLayout node ) { return defaultNodeHandle ( context , node ) ; } private boolean defaultSubgraphHandle ( LayoutContext context , SubgraphLayout subgraph ) { SpaceTreeNode node = ( SpaceTreeNode ) treeObserver . getTreeNode ( subgraph . getNodes ( ) [ <NUM_LIT:0> ] ) ; while ( node != null && node . node != null && node . node . getSubgraph ( ) == subgraph ) { node = ( SpaceTreeNode ) node . parent ; } if ( node != null && node . subgraph == subgraph ) { node . adjustPosition ( subgraph . getLocation ( ) ) ; if ( context . isBackgroundLayoutEnabled ( ) ) { ( ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ) . flushLocationChanges ( <NUM_LIT:0> ) ; node . refreshSubgraphLocation ( ) ; context . flushChanges ( false ) ; } } return false ; } private boolean defaultNodeHandle ( LayoutContext context , NodeLayout node ) { if ( bounds . width * bounds . height <= <NUM_LIT:0> ) return false ; SpaceTreeNode spaceTreeNode = ( SpaceTreeNode ) treeObserver . getTreeNode ( node ) ; spaceTreeNode . adjustPosition ( node . getLocation ( ) ) ; if ( context . isBackgroundLayoutEnabled ( ) ) { ( ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ) . flushLocationChanges ( <NUM_LIT:0> ) ; spaceTreeNode . refreshSubgraphLocation ( ) ; context . flushChanges ( false ) ; } return false ; } } ; private int direction = TOP_DOWN ; private double leafGap = <NUM_LIT:15> ; private double branchGap = leafGap + <NUM_LIT:5> ; private double layerGap = <NUM_LIT:20> ; private boolean directionChanged = false ; private LayoutContext context ; private DisplayIndependentRectangle bounds ; private TreeLayoutObserver treeObserver ; private double availableSpace ; private ArrayList spaceTreeLayers = new ArrayList ( ) ; private SpaceTreeNode protectedNode = null ; public SpaceTreeLayoutAlgorithm ( ) { } public SpaceTreeLayoutAlgorithm ( int direction ) { setDirection ( direction ) ; } public int getDirection ( ) { return direction ; } public void setDirection ( int direction ) { if ( direction == this . direction ) return ; if ( direction == TOP_DOWN || direction == BOTTOM_UP || direction == LEFT_RIGHT || direction == RIGHT_LEFT ) { this . direction = direction ; directionChanged = true ; if ( context . isBackgroundLayoutEnabled ( ) ) checkPendingChangeDirection ( ) ; } else throw new IllegalArgumentException ( "<STR_LIT>" + direction ) ; } public void applyLayout ( boolean clean ) { bounds = context . getBounds ( ) ; if ( bounds . width * bounds . height == <NUM_LIT:0> ) return ; if ( clean ) { treeObserver . recomputeTree ( ) ; expandCollapseManager . maximizeExpansion ( ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ) ; } SpaceTreeNode superRoot = ( ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ) ; superRoot . flushExpansionChanges ( ) ; superRoot . flushLocationChanges ( <NUM_LIT:0> ) ; checkPendingChangeDirection ( ) ; } public void setLayoutContext ( LayoutContext context ) { if ( this . context != null ) { this . context . removeContextListener ( contextListener ) ; this . context . removeLayoutListener ( layoutListener ) ; treeObserver . stop ( ) ; } this . context = context ; context . addContextListener ( contextListener ) ; context . addLayoutListener ( layoutListener ) ; treeObserver = new TreeLayoutObserver ( context , spaceTreeNodeFactory ) ; bounds = context . getBounds ( ) ; } public ExpandCollapseManager getExpandCollapseManager ( ) { return expandCollapseManager ; } private void checkPendingChangeDirection ( ) { if ( directionChanged ) { SubgraphLayout [ ] subgraphs = context . getSubgraphs ( ) ; int subgraphDirection = getSubgraphDirection ( ) ; for ( int i = <NUM_LIT:0> ; i < subgraphs . length ; i ++ ) { subgraphs [ i ] . setDirection ( subgraphDirection ) ; } directionChanged = false ; } } private int getSubgraphDirection ( ) { switch ( direction ) { case TOP_DOWN : return SubgraphLayout . TOP_DOWN ; case BOTTOM_UP : return SubgraphLayout . BOTTOM_UP ; case LEFT_RIGHT : return SubgraphLayout . LEFT_RIGHT ; case RIGHT_LEFT : return SubgraphLayout . RIGHT_LEFT ; } throw new RuntimeException ( ) ; } protected void refreshLayout ( boolean animation ) { if ( ! context . isBackgroundLayoutEnabled ( ) ) return ; SpaceTreeNode superRoot = ( SpaceTreeNode ) treeObserver . getSuperRoot ( ) ; if ( animation && superRoot . flushCollapseChanges ( ) ) context . flushChanges ( true ) ; if ( superRoot . flushLocationChanges ( <NUM_LIT:0> ) && animation ) context . flushChanges ( true ) ; superRoot . flushExpansionChanges ( ) ; superRoot . flushLocationChanges ( <NUM_LIT:0> ) ; context . flushChanges ( animation ) ; } private double getAvailableSpace ( ) { double result = ( direction == TOP_DOWN || direction == BOTTOM_UP ) ? bounds . width : bounds . height ; result = Math . max ( result , this . availableSpace ) ; for ( Iterator iterator = spaceTreeLayers . iterator ( ) ; iterator . hasNext ( ) ; ) { SpaceTreeLayer layer = ( SpaceTreeLayer ) iterator . next ( ) ; if ( ! layer . nodes . isEmpty ( ) ) { SpaceTreeNode first = ( SpaceTreeNode ) layer . nodes . get ( <NUM_LIT:0> ) ; SpaceTreeNode last = ( SpaceTreeNode ) layer . nodes . get ( layer . nodes . size ( ) - <NUM_LIT:1> ) ; result = Math . max ( result , last . positionInLayer - first . positionInLayer + ( first . spaceRequiredForNode ( ) + last . spaceRequiredForNode ( ) ) / <NUM_LIT:2> ) ; } else break ; } return result ; } private void setAvailableSpace ( double availableSpace ) { this . availableSpace = availableSpace ; } private double expectedDistance ( SpaceTreeNode node , SpaceTreeNode neighbor ) { double expectedDistance = ( node . spaceRequiredForNode ( ) + neighbor . spaceRequiredForNode ( ) ) / <NUM_LIT:2> ; expectedDistance += ( node . parent == neighbor . parent ) ? leafGap : branchGap ; return expectedDistance ; } private class NodeSnapshot { SpaceTreeNode node ; double position ; boolean expanded ; } private NodeSnapshot [ ] [ ] takeSnapShot ( ) { NodeSnapshot [ ] [ ] result = new NodeSnapshot [ spaceTreeLayers . size ( ) ] [ ] ; for ( int i = <NUM_LIT:0> ; i < result . length ; i ++ ) { SpaceTreeLayer layer = ( SpaceTreeLayer ) spaceTreeLayers . get ( i ) ; result [ i ] = new NodeSnapshot [ layer . nodes . size ( ) ] ; for ( int j = <NUM_LIT:0> ; j < result [ i ] . length ; j ++ ) { result [ i ] [ j ] = new NodeSnapshot ( ) ; result [ i ] [ j ] . node = ( ( SpaceTreeNode ) layer . nodes . get ( j ) ) ; result [ i ] [ j ] . position = result [ i ] [ j ] . node . positionInLayer ; result [ i ] [ j ] . expanded = result [ i ] [ j ] . node . expanded ; } } return result ; } private void revertToShanpshot ( NodeSnapshot [ ] [ ] snapShot ) { for ( int i = <NUM_LIT:0> ; i < snapShot . length ; i ++ ) { SpaceTreeLayer layer = ( SpaceTreeLayer ) spaceTreeLayers . get ( i ) ; layer . nodes . clear ( ) ; for ( int j = <NUM_LIT:0> ; j < snapShot [ i ] . length ; j ++ ) { snapShot [ i ] [ j ] . node . positionInLayer = snapShot [ i ] [ j ] . position ; snapShot [ i ] [ j ] . node . expanded = snapShot [ i ] [ j ] . expanded ; layer . nodes . add ( snapShot [ i ] [ j ] . node ) ; } } } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . Iterator ; import java . util . List ; import org . eclipse . zest . layouts . LayoutAlgorithm ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentDimension ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentRectangle ; import org . eclipse . zest . layouts . interfaces . EntityLayout ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; public class HorizontalShiftAlgorithm implements LayoutAlgorithm { private static final double DELTA = <NUM_LIT:10> ; private static final double VSPACING = <NUM_LIT:16> ; private LayoutContext context ; public void applyLayout ( boolean clean ) { if ( ! clean ) return ; ArrayList rowsList = new ArrayList ( ) ; EntityLayout [ ] entities = context . getEntities ( ) ; for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { addToRowList ( entities [ i ] , rowsList ) ; } Collections . sort ( rowsList , new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { List a0 = ( List ) o1 ; List a1 = ( List ) o2 ; EntityLayout entity0 = ( EntityLayout ) a0 . get ( <NUM_LIT:0> ) ; EntityLayout entity1 = ( EntityLayout ) a1 . get ( <NUM_LIT:0> ) ; return ( int ) ( entity0 . getLocation ( ) . y - entity1 . getLocation ( ) . y ) ; } } ) ; Comparator entityComparator = new Comparator ( ) { public int compare ( Object o1 , Object o2 ) { return ( int ) ( ( ( EntityLayout ) o1 ) . getLocation ( ) . y - ( ( EntityLayout ) o2 ) . getLocation ( ) . y ) ; } } ; DisplayIndependentRectangle bounds = context . getBounds ( ) ; int heightSoFar = <NUM_LIT:0> ; for ( Iterator iterator = rowsList . iterator ( ) ; iterator . hasNext ( ) ; ) { List currentRow = ( List ) iterator . next ( ) ; Collections . sort ( currentRow , entityComparator ) ; int i = <NUM_LIT:0> ; int width = ( int ) ( bounds . width / <NUM_LIT:2> - currentRow . size ( ) * <NUM_LIT> ) ; heightSoFar += ( ( EntityLayout ) currentRow . get ( <NUM_LIT:0> ) ) . getSize ( ) . height + VSPACING ; for ( Iterator iterator2 = currentRow . iterator ( ) ; iterator2 . hasNext ( ) ; ) { EntityLayout entity = ( EntityLayout ) iterator2 . next ( ) ; DisplayIndependentDimension size = entity . getSize ( ) ; entity . setLocation ( width + <NUM_LIT:10> * ++ i + size . width / <NUM_LIT:2> , heightSoFar + size . height / <NUM_LIT:2> ) ; width += size . width ; } } } public void setLayoutContext ( LayoutContext context ) { this . context = context ; } private void addToRowList ( EntityLayout entity , ArrayList rowsList ) { double layoutY = entity . getLocation ( ) . y ; for ( Iterator iterator = rowsList . iterator ( ) ; iterator . hasNext ( ) ; ) { List currentRow = ( List ) iterator . next ( ) ; EntityLayout currentRowEntity = ( EntityLayout ) currentRow . get ( <NUM_LIT:0> ) ; double currentRowY = currentRowEntity . getLocation ( ) . y ; if ( layoutY >= currentRowY - DELTA && layoutY <= currentRowY + DELTA ) { currentRow . add ( entity ) ; return ; } } List newRow = new ArrayList ( ) ; newRow . add ( entity ) ; rowsList . add ( newRow ) ; } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentDimension ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentPoint ; import org . eclipse . zest . layouts . dataStructures . DisplayIndependentRectangle ; import org . eclipse . zest . layouts . interfaces . EntityLayout ; class AlgorithmHelper { public static int MIN_NODE_SIZE = <NUM_LIT:8> ; public static double PADDING_PERCENT = <NUM_LIT> ; public static void fitWithinBounds ( EntityLayout [ ] entities , DisplayIndependentRectangle destinationBounds , boolean resize ) { DisplayIndependentRectangle startingBounds = getLayoutBounds ( entities , false ) ; double sizeScale = Math . min ( destinationBounds . width / startingBounds . width , destinationBounds . height / startingBounds . height ) ; if ( entities . length == <NUM_LIT:1> ) { fitSingleEntity ( entities [ <NUM_LIT:0> ] , destinationBounds , resize ) ; return ; } for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { EntityLayout entity = entities [ i ] ; DisplayIndependentDimension size = entity . getSize ( ) ; if ( entity . isMovable ( ) ) { DisplayIndependentPoint location = entity . getLocation ( ) ; double percentX = ( location . x - startingBounds . x ) / ( startingBounds . width ) ; double percentY = ( location . y - startingBounds . y ) / ( startingBounds . height ) ; if ( resize && entity . isResizable ( ) ) { size . width *= sizeScale ; size . height *= sizeScale ; entity . setSize ( size . width , size . height ) ; } location . x = destinationBounds . x + size . width / <NUM_LIT:2> + percentX * ( destinationBounds . width - size . width ) ; location . y = destinationBounds . y + size . height / <NUM_LIT:2> + percentY * ( destinationBounds . height - size . height ) ; entity . setLocation ( location . x , location . y ) ; } else if ( resize && entity . isResizable ( ) ) { entity . setSize ( size . width * sizeScale , size . height * sizeScale ) ; } } } private static void fitSingleEntity ( EntityLayout entity , DisplayIndependentRectangle destinationBounds , boolean resize ) { if ( entity . isMovable ( ) ) { entity . setLocation ( destinationBounds . x + destinationBounds . width / <NUM_LIT:2> , destinationBounds . y + destinationBounds . height / <NUM_LIT:2> ) ; } if ( resize && entity . isResizable ( ) ) { double width = destinationBounds . width ; double height = destinationBounds . height ; double preferredAspectRatio = entity . getPreferredAspectRatio ( ) ; if ( preferredAspectRatio > <NUM_LIT:0> ) { DisplayIndependentDimension fixedSize = fixAspectRatio ( width , height , preferredAspectRatio ) ; entity . setSize ( fixedSize . width , fixedSize . height ) ; } else { entity . setSize ( width , height ) ; } } } public static void maximizeSizes ( EntityLayout [ ] entities ) { if ( entities . length > <NUM_LIT:1> ) { DisplayIndependentDimension minDistance = getMinimumDistance ( entities ) ; double nodeSize = Math . max ( minDistance . width , minDistance . height ) * PADDING_PERCENT ; double width = nodeSize ; double height = nodeSize ; for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { EntityLayout entity = entities [ i ] ; if ( entity . isResizable ( ) ) { double preferredRatio = entity . getPreferredAspectRatio ( ) ; if ( preferredRatio > <NUM_LIT:0> ) { DisplayIndependentDimension fixedSize = fixAspectRatio ( width , height , preferredRatio ) ; entity . setSize ( fixedSize . width , fixedSize . height ) ; } else { entity . setSize ( width , height ) ; } } } } } private static DisplayIndependentDimension fixAspectRatio ( double width , double height , double preferredRatio ) { double actualRatio = width / height ; if ( actualRatio > preferredRatio ) { width = height * preferredRatio ; if ( width < MIN_NODE_SIZE ) { width = MIN_NODE_SIZE ; height = width / preferredRatio ; } } if ( actualRatio < preferredRatio ) { height = width / preferredRatio ; if ( height < MIN_NODE_SIZE ) { height = MIN_NODE_SIZE ; width = height * preferredRatio ; } } return new DisplayIndependentDimension ( width , height ) ; } public static DisplayIndependentRectangle getLayoutBounds ( EntityLayout [ ] entities , boolean includeNodeSize ) { double rightSide = Double . NEGATIVE_INFINITY ; double bottomSide = Double . NEGATIVE_INFINITY ; double leftSide = Double . POSITIVE_INFINITY ; double topSide = Double . POSITIVE_INFINITY ; for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { EntityLayout entity = entities [ i ] ; DisplayIndependentPoint location = entity . getLocation ( ) ; DisplayIndependentDimension size = entity . getSize ( ) ; if ( includeNodeSize ) { leftSide = Math . min ( location . x - size . width / <NUM_LIT:2> , leftSide ) ; topSide = Math . min ( location . y - size . height / <NUM_LIT:2> , topSide ) ; rightSide = Math . max ( location . x + size . width / <NUM_LIT:2> , rightSide ) ; bottomSide = Math . max ( location . y + size . height / <NUM_LIT:2> , bottomSide ) ; } else { leftSide = Math . min ( location . x , leftSide ) ; topSide = Math . min ( location . y , topSide ) ; rightSide = Math . max ( location . x , rightSide ) ; bottomSide = Math . max ( location . y , bottomSide ) ; } } return new DisplayIndependentRectangle ( leftSide , topSide , rightSide - leftSide , bottomSide - topSide ) ; } public static DisplayIndependentDimension getMinimumDistance ( EntityLayout [ ] entities ) { DisplayIndependentDimension horAndVertdistance = new DisplayIndependentDimension ( Double . MAX_VALUE , Double . MAX_VALUE ) ; double minDistance = Double . MAX_VALUE ; for ( int i = <NUM_LIT:0> ; i < entities . length ; i ++ ) { DisplayIndependentPoint location1 = entities [ i ] . getLocation ( ) ; for ( int j = i + <NUM_LIT:1> ; j < entities . length ; j ++ ) { DisplayIndependentPoint location2 = entities [ j ] . getLocation ( ) ; double distanceX = location1 . x - location2 . x ; double distanceY = location1 . y - location2 . y ; double distance = distanceX * distanceX + distanceY * distanceY ; if ( distance < minDistance ) { minDistance = distance ; horAndVertdistance . width = Math . abs ( distanceX ) ; horAndVertdistance . height = Math . abs ( distanceY ) ; } } } return horAndVertdistance ; } } </s>
|
<s> package org . eclipse . zest . layouts . algorithms ; import java . util . ArrayList ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . ListIterator ; import java . util . Set ; import org . eclipse . zest . layouts . interfaces . ConnectionLayout ; import org . eclipse . zest . layouts . interfaces . GraphStructureListener ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; import org . eclipse . zest . layouts . interfaces . NodeLayout ; public class TreeLayoutObserver { public static class TreeNodeFactory { public TreeNode createTreeNode ( NodeLayout nodeLayout , TreeLayoutObserver observer ) { return new TreeNode ( nodeLayout , observer ) ; } } public static class TreeNode { final protected NodeLayout node ; final protected TreeLayoutObserver owner ; protected int height = <NUM_LIT:0> ; protected int depth = - <NUM_LIT:1> ; protected int numOfLeaves = <NUM_LIT:0> ; protected int numOfDescendants = <NUM_LIT:0> ; protected int order = <NUM_LIT:0> ; protected final List children = new ArrayList ( ) ; protected TreeNode parent ; protected boolean firstChild = false , lastChild = false ; public NodeLayout getNode ( ) { return node ; } public TreeLayoutObserver getOwner ( ) { return owner ; } public int getHeight ( ) { return height ; } public int getDepth ( ) { return depth ; } public int getNumOfLeaves ( ) { return numOfLeaves ; } public int getNumOfDescendants ( ) { return numOfDescendants ; } public int getOrder ( ) { return order ; } public List getChildren ( ) { return Collections . unmodifiableList ( children ) ; } public TreeNode getParent ( ) { return parent ; } public boolean isFirstChild ( ) { return firstChild ; } public boolean isLastChild ( ) { return lastChild ; } protected TreeNode ( NodeLayout node , TreeLayoutObserver owner ) { this . node = node ; this . owner = owner ; } protected void addChild ( TreeNode child ) { children . add ( child ) ; child . parent = this ; } protected void precomputeTree ( ) { if ( children . isEmpty ( ) ) { height = <NUM_LIT:0> ; numOfLeaves = <NUM_LIT:1> ; numOfDescendants = <NUM_LIT:0> ; } else { height = <NUM_LIT:0> ; numOfLeaves = <NUM_LIT:0> ; numOfDescendants = <NUM_LIT:0> ; for ( ListIterator iterator = children . listIterator ( ) ; iterator . hasNext ( ) ; ) { TreeNode child = ( TreeNode ) iterator . next ( ) ; child . depth = this . depth + <NUM_LIT:1> ; child . order = this . order + this . numOfLeaves ; child . precomputeTree ( ) ; child . firstChild = ( this . numOfLeaves == <NUM_LIT:0> ) ; child . lastChild = ! iterator . hasNext ( ) ; this . height = Math . max ( this . height , child . height + <NUM_LIT:1> ) ; this . numOfLeaves += child . numOfLeaves ; this . numOfDescendants += child . numOfDescendants + <NUM_LIT:1> ; } } } protected void findNewParent ( ) { if ( parent != null ) parent . children . remove ( this ) ; NodeLayout [ ] predecessingNodes = node . getPredecessingNodes ( ) ; parent = null ; for ( int i = <NUM_LIT:0> ; i < predecessingNodes . length ; i ++ ) { TreeNode potentialParent = ( TreeNode ) owner . layoutToTree . get ( predecessingNodes [ i ] ) ; if ( ! children . contains ( potentialParent ) && isBetterParent ( potentialParent ) ) parent = potentialParent ; } if ( parent == null ) parent = owner . superRoot ; parent . addChild ( this ) ; } protected boolean isBetterParent ( TreeNode potentialParent ) { if ( potentialParent == null ) return false ; if ( this . parent == null && ! this . isAncestorOf ( potentialParent ) ) return true ; if ( potentialParent . depth <= this . depth && potentialParent . depth != - <NUM_LIT:1> ) return true ; if ( this . parent != null && this . parent . depth == - <NUM_LIT:1> && potentialParent . depth >= <NUM_LIT:0> && ! this . isAncestorOf ( potentialParent ) ) return true ; return false ; } public boolean isAncestorOf ( TreeNode descendant ) { while ( descendant . depth > this . depth ) descendant = descendant . parent ; return descendant == this ; } } public static class TreeListener { public void nodeAdded ( TreeNode newNode ) { defaultHandle ( newNode ) ; } public void nodeRemoved ( TreeNode removedNode ) { defaultHandle ( removedNode ) ; } public void parentChanged ( TreeNode node , TreeNode previousParent ) { defaultHandle ( node ) ; } protected void defaultHandle ( TreeNode changedNode ) { } } private GraphStructureListener structureListener = new GraphStructureListener ( ) { public boolean nodeRemoved ( LayoutContext context , NodeLayout node ) { TreeNode treeNode = ( TreeNode ) layoutToTree . get ( node ) ; treeNode . parent . children . remove ( treeNode ) ; superRoot . precomputeTree ( ) ; for ( Iterator iterator = treeListeners . iterator ( ) ; iterator . hasNext ( ) ; ) { TreeListener listener = ( TreeListener ) iterator . next ( ) ; listener . nodeRemoved ( treeNode ) ; } return false ; } public boolean nodeAdded ( LayoutContext context , NodeLayout node ) { TreeNode treeNode = getTreeNode ( node ) ; superRoot . addChild ( treeNode ) ; superRoot . precomputeTree ( ) ; for ( Iterator iterator = treeListeners . iterator ( ) ; iterator . hasNext ( ) ; ) { TreeListener listener = ( TreeListener ) iterator . next ( ) ; listener . nodeAdded ( treeNode ) ; } return false ; } public boolean connectionRemoved ( LayoutContext context , ConnectionLayout connection ) { TreeNode node1 = ( TreeNode ) layoutToTree . get ( connection . getSource ( ) ) ; TreeNode node2 = ( TreeNode ) layoutToTree . get ( connection . getTarget ( ) ) ; if ( node1 . parent == node2 ) { node1 . findNewParent ( ) ; if ( node1 . parent != node2 ) { superRoot . precomputeTree ( ) ; fireParentChanged ( node1 , node2 ) ; } } if ( node2 . parent == node1 ) { node2 . findNewParent ( ) ; if ( node2 . parent != node1 ) { superRoot . precomputeTree ( ) ; fireParentChanged ( node2 , node1 ) ; } } return false ; } public boolean connectionAdded ( LayoutContext context , ConnectionLayout connection ) { TreeNode source = ( TreeNode ) layoutToTree . get ( connection . getSource ( ) ) ; TreeNode target = ( TreeNode ) layoutToTree . get ( connection . getTarget ( ) ) ; if ( source == target ) return false ; if ( target . isBetterParent ( source ) ) { TreeNode previousParent = target . parent ; previousParent . children . remove ( target ) ; source . addChild ( target ) ; superRoot . precomputeTree ( ) ; fireParentChanged ( target , previousParent ) ; } if ( ! connection . isDirected ( ) && source . isBetterParent ( target ) ) { TreeNode previousParent = source . parent ; previousParent . children . remove ( source ) ; target . addChild ( source ) ; superRoot . precomputeTree ( ) ; fireParentChanged ( source , previousParent ) ; } return false ; } private void fireParentChanged ( TreeNode node , TreeNode previousParent ) { for ( Iterator iterator = treeListeners . iterator ( ) ; iterator . hasNext ( ) ; ) { TreeListener listener = ( TreeListener ) iterator . next ( ) ; listener . parentChanged ( node , previousParent ) ; } } } ; private final HashMap layoutToTree = new HashMap ( ) ; private final TreeNodeFactory factory ; private final LayoutContext context ; private TreeNode superRoot ; private ArrayList treeListeners = new ArrayList ( ) ; public TreeLayoutObserver ( LayoutContext context , TreeNodeFactory nodeFactory ) { if ( nodeFactory == null ) this . factory = new TreeNodeFactory ( ) ; else this . factory = nodeFactory ; this . context = context ; context . addGraphStructureListener ( structureListener ) ; recomputeTree ( ) ; } public void recomputeTree ( ) { superRoot = factory . createTreeNode ( null , this ) ; layoutToTree . put ( null , superRoot ) ; createTrees ( context . getNodes ( ) ) ; } public void stop ( ) { context . removeGraphStructureListener ( structureListener ) ; } public TreeNode getSuperRoot ( ) { return superRoot ; } public TreeNode getTreeNode ( NodeLayout node ) { TreeNode treeNode = ( TreeNode ) layoutToTree . get ( node ) ; if ( treeNode == null ) { treeNode = factory . createTreeNode ( node , this ) ; layoutToTree . put ( node , treeNode ) ; } return treeNode ; } public void addTreeListener ( TreeListener listener ) { treeListeners . add ( listener ) ; } public void removeTreeListener ( TreeListener listener ) { treeListeners . add ( listener ) ; } private void createTrees ( NodeLayout [ ] nodes ) { HashSet alreadyVisited = new HashSet ( ) ; LinkedList nodesToAdd = new LinkedList ( ) ; for ( int i = <NUM_LIT:0> ; i < nodes . length ; i ++ ) { NodeLayout root = findRoot ( nodes [ i ] , alreadyVisited ) ; if ( root != null ) { alreadyVisited . add ( root ) ; nodesToAdd . addLast ( new Object [ ] { root , superRoot } ) ; } } while ( ! nodesToAdd . isEmpty ( ) ) { Object [ ] dequeued = ( Object [ ] ) nodesToAdd . removeFirst ( ) ; TreeNode currentNode = factory . createTreeNode ( ( NodeLayout ) dequeued [ <NUM_LIT:0> ] , this ) ; layoutToTree . put ( dequeued [ <NUM_LIT:0> ] , currentNode ) ; TreeNode currentRoot = ( TreeNode ) dequeued [ <NUM_LIT:1> ] ; currentRoot . addChild ( currentNode ) ; NodeLayout [ ] children = currentNode . node . getSuccessingNodes ( ) ; for ( int i = <NUM_LIT:0> ; i < children . length ; i ++ ) { if ( ! alreadyVisited . contains ( children [ i ] ) ) { alreadyVisited . add ( children [ i ] ) ; nodesToAdd . addLast ( new Object [ ] { children [ i ] , currentNode } ) ; } } } superRoot . precomputeTree ( ) ; } private NodeLayout findRoot ( NodeLayout nodeLayout , Set alreadyVisited ) { HashSet alreadyVisitedRoot = new HashSet ( ) ; while ( true ) { if ( alreadyVisited . contains ( nodeLayout ) ) return null ; if ( alreadyVisitedRoot . contains ( nodeLayout ) ) return nodeLayout ; alreadyVisitedRoot . add ( nodeLayout ) ; NodeLayout [ ] predecessingNodes = nodeLayout . getPredecessingNodes ( ) ; if ( predecessingNodes . length > <NUM_LIT:0> ) { nodeLayout = predecessingNodes [ <NUM_LIT:0> ] ; } else { return nodeLayout ; } } } } </s>
|
<s> package org . eclipse . zest . layouts ; import org . eclipse . zest . layouts . interfaces . LayoutContext ; public interface LayoutAlgorithm { public void setLayoutContext ( LayoutContext context ) ; public void applyLayout ( boolean clean ) ; } </s>
|
<s> package org . eclipse . zest . layouts . dataStructures ; public class DisplayIndependentRectangle { public double x , y , width , height ; public DisplayIndependentRectangle ( ) { this . x = <NUM_LIT:0> ; this . y = <NUM_LIT:0> ; this . width = <NUM_LIT:0> ; this . height = <NUM_LIT:0> ; } public DisplayIndependentRectangle ( double x , double y , double width , double height ) { this . x = x ; this . y = y ; this . width = width ; this . height = height ; } public DisplayIndependentRectangle ( DisplayIndependentRectangle rect ) { this . x = rect . x ; this . y = rect . y ; this . width = rect . width ; this . height = rect . height ; } public String toString ( ) { return "<STR_LIT:(>" + x + "<STR_LIT:U+002CU+0020>" + y + "<STR_LIT:U+002CU+0020>" + width + "<STR_LIT:U+002CU+0020>" + height + "<STR_LIT:)>" ; } public boolean intersects ( DisplayIndependentRectangle rect ) { return rect . x < x + width && rect . y < y + height && rect . x + rect . width > x && rect . y + rect . height > y ; } } </s>
|
<s> package org . eclipse . zest . layouts . dataStructures ; public class DisplayIndependentPoint { public double x , y ; public boolean equals ( Object o ) { DisplayIndependentPoint that = ( DisplayIndependentPoint ) o ; if ( this . x == that . x && this . y == that . y ) return true ; else return false ; } public DisplayIndependentPoint ( double x , double y ) { this . x = x ; this . y = y ; } public DisplayIndependentPoint ( DisplayIndependentPoint point ) { this . x = point . x ; this . y = point . y ; } public String toString ( ) { return "<STR_LIT:(>" + x + "<STR_LIT:U+002CU+0020>" + y + "<STR_LIT:)>" ; } public DisplayIndependentPoint convert ( DisplayIndependentRectangle currentBounds , DisplayIndependentRectangle targetBounds ) { double currentWidth = currentBounds . width ; double currentHeight = currentBounds . height ; double newX = ( currentBounds . width == <NUM_LIT:0> ) ? <NUM_LIT:0> : ( x / currentWidth ) * targetBounds . width + targetBounds . x ; double newY = ( currentBounds . height == <NUM_LIT:0> ) ? <NUM_LIT:0> : ( y / currentHeight ) * targetBounds . height + targetBounds . y ; return new DisplayIndependentPoint ( newX , newY ) ; } public DisplayIndependentPoint convertToPercent ( DisplayIndependentRectangle bounds ) { double newX = ( bounds . width == <NUM_LIT:0> ) ? <NUM_LIT:0> : ( ( double ) ( x - bounds . x ) ) / bounds . width ; double newY = ( bounds . height == <NUM_LIT:0> ) ? <NUM_LIT:0> : ( ( double ) ( y - bounds . y ) ) / bounds . height ; return new DisplayIndependentPoint ( newX , newY ) ; } public DisplayIndependentPoint convertFromPercent ( DisplayIndependentRectangle bounds ) { double newX = bounds . x + x * bounds . width ; double newY = bounds . y + y * bounds . height ; return new DisplayIndependentPoint ( newX , newY ) ; } } </s>
|
<s> package org . eclipse . zest . layouts . dataStructures ; public class DisplayIndependentDimension { public double width , height ; public DisplayIndependentDimension ( double width , double height ) { this . width = width ; this . height = height ; } public DisplayIndependentDimension ( DisplayIndependentDimension dimension ) { this . width = dimension . width ; this . height = dimension . height ; } public String toString ( ) { return "<STR_LIT:(>" + width + "<STR_LIT:U+002CU+0020>" + height + "<STR_LIT:)>" ; } } </s>
|
<s> package org . eclipse . zest . internal . dot ; import org . eclipse . zest . core . widgets . Graph ; import org . eclipse . zest . core . widgets . GraphConnection ; import org . eclipse . zest . core . widgets . GraphNode ; final class ZestGraphImport { private Graph graphFromDot ; ZestGraphImport ( Graph sourceGraph ) { this . graphFromDot = sourceGraph ; } void into ( Graph targetGraph ) { Graph sourceGraph = graphFromDot ; targetGraph . setNodeStyle ( sourceGraph . getNodeStyle ( ) ) ; targetGraph . setConnectionStyle ( sourceGraph . getConnectionStyle ( ) ) ; targetGraph . setLayoutAlgorithm ( sourceGraph . getLayoutAlgorithm ( ) , true ) ; for ( Object edge : sourceGraph . getConnections ( ) ) { copy ( ( GraphConnection ) edge , targetGraph ) ; } for ( Object node : sourceGraph . getNodes ( ) ) { copy ( ( GraphNode ) node , targetGraph ) ; } targetGraph . update ( ) ; } private GraphConnection copy ( GraphConnection edge , Graph targetGraph ) { GraphNode source = copy ( edge . getSource ( ) , targetGraph ) ; GraphNode target = copy ( edge . getDestination ( ) , targetGraph ) ; GraphConnection copy = new GraphConnection ( targetGraph , edge . getStyle ( ) , source , target ) ; copy . setText ( edge . getText ( ) ) ; copy . setData ( edge . getData ( ) ) ; copy . setLineStyle ( edge . getLineStyle ( ) ) ; return copy ; } private GraphNode copy ( GraphNode node , Graph targetGraph ) { GraphNode find = find ( node , targetGraph ) ; if ( find == null ) { GraphNode copy = new GraphNode ( targetGraph , node . getStyle ( ) , node . getText ( ) ) ; copy . setImage ( node . getImage ( ) ) ; copy . setData ( node . getData ( ) ) ; return copy ; } return find ; } private GraphNode find ( GraphNode node , Graph graph ) { for ( Object o : graph . getNodes ( ) ) { GraphNode n = ( GraphNode ) o ; if ( node . getData ( ) != null && node . getData ( ) . equals ( n . getData ( ) ) ) { return n ; } } return null ; } } </s>
|
<s> package org . eclipse . zest . internal . dot ; import java . io . ByteArrayInputStream ; import java . io . IOException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import org . eclipse . emf . common . util . EList ; import org . eclipse . emf . common . util . URI ; import org . eclipse . emf . ecore . EAttribute ; import org . eclipse . emf . ecore . EObject ; import org . eclipse . emf . ecore . resource . Resource ; import org . eclipse . emf . ecore . resource . Resource . Diagnostic ; import org . eclipse . emf . ecore . resource . ResourceSet ; import org . eclipse . emf . ecore . resource . impl . ResourceSetImpl ; import org . eclipse . swt . SWT ; import org . eclipse . zest . internal . dot . parser . DotStandaloneSetup ; import org . eclipse . zest . layouts . LayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . GridLayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . RadialLayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . SpringLayoutAlgorithm ; import org . eclipse . zest . layouts . algorithms . TreeLayoutAlgorithm ; public final class DotAst { enum Style { DASHED ( SWT . LINE_DASH ) , DOTTED ( SWT . LINE_DOT ) , SOLID ( SWT . LINE_SOLID ) , DASHDOT ( SWT . LINE_DASHDOT ) , DASHDOTDOT ( SWT . LINE_DASHDOTDOT ) ; int style ; Style ( final int style ) { this . style = style ; } } enum Layout { DOT ( new TreeLayoutAlgorithm ( ) ) , OSAGE ( new GridLayoutAlgorithm ( ) ) , TWOPI ( new RadialLayoutAlgorithm ( ) ) , CIRCO ( new RadialLayoutAlgorithm ( ) ) , NEATO ( new RadialLayoutAlgorithm ( ) ) , FDP ( new SpringLayoutAlgorithm ( ) ) , SFDP ( new SpringLayoutAlgorithm ( ) ) ; LayoutAlgorithm algorithm ; Layout ( final LayoutAlgorithm algorithm ) { this . algorithm = algorithm ; } } private Resource resource ; public DotAst ( final String dotString ) { this . resource = loadResource ( dotString ) ; } public String graphName ( ) { EObject graph = graph ( ) ; Iterator < EAttribute > graphAttributes = graph . eClass ( ) . getEAllAttributes ( ) . iterator ( ) ; while ( graphAttributes . hasNext ( ) ) { EAttribute a = graphAttributes . next ( ) ; if ( a . getName ( ) . equals ( "<STR_LIT:name>" ) ) { return ( String ) graph . eGet ( a ) ; } } System . err . println ( "<STR_LIT>" + graph ) ; return "<STR_LIT>" ; } public List < String > errors ( ) { List < String > result = new ArrayList < String > ( ) ; EList < Diagnostic > errors = resource . getErrors ( ) ; Iterator < Diagnostic > i = errors . iterator ( ) ; while ( i . hasNext ( ) ) { Diagnostic next = i . next ( ) ; result . add ( String . format ( DotMessages . DotAst_0 + "<STR_LIT>" , next . getLine ( ) , next . getMessage ( ) ) ) ; } return result ; } EObject graph ( ) { EList < EObject > contents = resource . getContents ( ) ; EObject graphs = contents . iterator ( ) . next ( ) ; EObject graph = graphs . eContents ( ) . iterator ( ) . next ( ) ; return graph ; } Resource resource ( ) { return resource ; } private static Resource loadResource ( final String dot ) { DotStandaloneSetup . doSetup ( ) ; ResourceSet set = new ResourceSetImpl ( ) ; Resource res = set . createResource ( URI . createURI ( "<STR_LIT>" ) ) ; try { res . load ( new ByteArrayInputStream ( dot . getBytes ( ) ) , Collections . EMPTY_MAP ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return res ; } @ Override public String toString ( ) { return String . format ( "<STR_LIT>" , getClass ( ) . getSimpleName ( ) , graphName ( ) , errors ( ) . size ( ) , resource ) ; } } </s>
|
<s> package org . eclipse . zest . internal . dot ; import java . io . File ; import java . net . MalformedURLException ; import java . util . List ; import org . eclipse . core . resources . IFile ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . zest . core . widgets . Graph ; public final class DotImport { private String dotString ; private DotAst dotAst ; public DotImport ( final File dotFile ) { this . dotString = DotFileUtils . read ( dotFile ) ; load ( ) ; } public DotImport ( final IFile dotFile ) { try { this . dotString = DotFileUtils . read ( DotFileUtils . resolve ( dotFile . getLocationURI ( ) . toURL ( ) ) ) ; load ( ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } } public DotImport ( final String dotString ) { init ( dotString ) ; } private void init ( final String dotString ) { if ( dotString == null || dotString . trim ( ) . length ( ) == <NUM_LIT:0> ) { throw new IllegalArgumentException ( DotMessages . DotImport_2 + "<STR_LIT::U+0020>" + dotString ) ; } loadFrom ( dotString ) ; if ( dotAst . errors ( ) . size ( ) > <NUM_LIT:0> ) { loadFrom ( wrapped ( dotString ) ) ; } } private void loadFrom ( final String dotString ) { this . dotString = dotString ; load ( ) ; } private String wrapped ( final String dotString ) { return String . format ( "<STR_LIT>" , dotString . contains ( "<STR_LIT>" ) ? "<STR_LIT>" : "<STR_LIT>" , dotString ) ; } private void guardFaultyParse ( ) { List < String > errors = this . dotAst . errors ( ) ; if ( errors . size ( ) > <NUM_LIT:0> ) { throw new IllegalArgumentException ( String . format ( DotMessages . DotImport_1 + "<STR_LIT>" , dotString , errors . toString ( ) ) ) ; } } private void load ( ) { this . dotAst = new DotAst ( this . dotString ) ; } public List < String > getErrors ( ) { return dotAst . errors ( ) ; } public String getName ( ) { return dotAst . graphName ( ) ; } public Graph newGraphInstance ( final Composite parent , final int style ) { guardFaultyParse ( ) ; return new GraphCreatorInterpreter ( ) . create ( parent , style , dotAst ) ; } public void into ( Graph graph ) { Shell shell = new Shell ( ) ; new ZestGraphImport ( newGraphInstance ( shell , graph . getStyle ( ) ) ) . into ( graph ) ; shell . dispose ( ) ; } public DotAst getDotAst ( ) { return this . dotAst ; } @ Override public String toString ( ) { return String . format ( "<STR_LIT>" , getClass ( ) . getSimpleName ( ) , dotAst , dotString ) ; } } </s>
|
<s> package org . eclipse . zest . internal . dot . parser . scoping ; import org . eclipse . xtext . scoping . impl . AbstractDeclarativeScopeProvider ; public class DotScopeProvider extends AbstractDeclarativeScopeProvider { } </s>
|
<s> package org . eclipse . zest . internal . dot . parser . formatting ; import org . eclipse . xtext . formatting . impl . AbstractDeclarativeFormatter ; import org . eclipse . xtext . formatting . impl . FormattingConfig ; public class DotFormatter extends AbstractDeclarativeFormatter { @ Override protected void configureFormatting ( FormattingConfig c ) { } } </s>
|
<s> package org . eclipse . zest . internal . dot . parser ; public class DotStandaloneSetup extends DotStandaloneSetupGenerated { public static void doSetup ( ) { new DotStandaloneSetup ( ) . createInjectorAndDoEMFRegistration ( ) ; } } </s>
|
<s> package org . eclipse . zest . internal . dot . parser . validation ; public class DotJavaValidator extends AbstractDotJavaValidator { } </s>
|
<s> package org . eclipse . zest . internal . dot . parser ; public class DotRuntimeModule extends org . eclipse . zest . internal . dot . parser . AbstractDotRuntimeModule { } </s>
|
<s> package org . eclipse . zest . internal . dot ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import org . eclipse . emf . common . util . TreeIterator ; import org . eclipse . emf . ecore . EObject ; import org . eclipse . emf . ecore . util . EcoreUtil ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . zest . core . widgets . Graph ; import org . eclipse . zest . core . widgets . GraphConnection ; import org . eclipse . zest . core . widgets . GraphContainer ; import org . eclipse . zest . core . widgets . GraphNode ; import org . eclipse . zest . core . widgets . IContainer ; import org . eclipse . zest . core . widgets . ZestStyles ; import org . eclipse . zest . internal . dot . DotAst . Layout ; import org . eclipse . zest . internal . dot . DotAst . Style ; import org . eclipse . zest . internal . dot . parser . dot . AList ; import org . eclipse . zest . internal . dot . parser . dot . AttrList ; import org . eclipse . zest . internal . dot . parser . dot . AttrStmt ; import org . eclipse . zest . internal . dot . parser . dot . Attribute ; import org . eclipse . zest . internal . dot . parser . dot . AttributeType ; import org . eclipse . zest . internal . dot . parser . dot . EdgeRhsNode ; import org . eclipse . zest . internal . dot . parser . dot . EdgeStmtNode ; import org . eclipse . zest . internal . dot . parser . dot . GraphType ; import org . eclipse . zest . internal . dot . parser . dot . MainGraph ; import org . eclipse . zest . internal . dot . parser . dot . NodeId ; import org . eclipse . zest . internal . dot . parser . dot . NodeStmt ; import org . eclipse . zest . internal . dot . parser . dot . Stmt ; import org . eclipse . zest . internal . dot . parser . dot . Subgraph ; import org . eclipse . zest . internal . dot . parser . dot . util . DotSwitch ; import org . eclipse . zest . layouts . algorithms . TreeLayoutAlgorithm ; public final class GraphCreatorInterpreter extends DotSwitch < Object > { private Map < String , GraphNode > nodes ; private Graph graph ; private String globalEdgeStyle ; private String globalEdgeLabel ; private String globalNodeLabel ; private String currentEdgeStyleValue ; private String currentEdgeLabelValue ; private String currentEdgeSourceNodeId ; private GraphContainer currentSubgraph ; private boolean gotSource ; public Graph create ( Composite parent , int style , DotAst dotAst ) { return create ( dotAst , new Graph ( parent , style ) ) ; } public Graph create ( DotAst dotAst , Graph graph ) { if ( dotAst . errors ( ) . size ( ) > <NUM_LIT:0> ) { throw new IllegalArgumentException ( String . format ( DotMessages . GraphCreatorInterpreter_0 + "<STR_LIT>" , dotAst . errors ( ) . toString ( ) ) ) ; } this . graph = graph ; nodes = new HashMap < String , GraphNode > ( ) ; TreeIterator < Object > contents = EcoreUtil . getAllProperContents ( dotAst . resource ( ) , false ) ; while ( contents . hasNext ( ) ) { doSwitch ( ( EObject ) contents . next ( ) ) ; } layoutSubgraph ( ) ; return graph ; } @ Override public Object caseMainGraph ( MainGraph object ) { createGraph ( object ) ; return super . caseMainGraph ( object ) ; } @ Override public Object caseAttribute ( Attribute object ) { if ( object . getName ( ) . equals ( "<STR_LIT>" ) && object . getValue ( ) . equals ( "<STR_LIT>" ) ) { TreeLayoutAlgorithm algorithm = new TreeLayoutAlgorithm ( TreeLayoutAlgorithm . LEFT_RIGHT ) ; currentParentGraph ( ) . setLayoutAlgorithm ( algorithm , true ) ; } else if ( currentSubgraph != null && object . getName ( ) . equals ( "<STR_LIT:label>" ) ) { currentSubgraph . setText ( object . getValue ( ) ) ; } return super . caseAttribute ( object ) ; } @ Override public Object caseAttrStmt ( AttrStmt object ) { createAttributes ( object ) ; return super . caseAttrStmt ( object ) ; } @ Override public Object caseNodeStmt ( NodeStmt object ) { createNode ( object ) ; return super . caseNodeStmt ( object ) ; } @ Override public Object caseEdgeStmtNode ( EdgeStmtNode object ) { currentEdgeLabelValue = getAttributeValue ( object , "<STR_LIT:label>" ) ; currentEdgeStyleValue = getAttributeValue ( object , "<STR_LIT>" ) ; return super . caseEdgeStmtNode ( object ) ; } @ Override public Object caseNodeId ( NodeId object ) { if ( ! gotSource ) { gotSource = true ; } else { String targetNodeId = escaped ( object . getName ( ) ) ; if ( currentEdgeSourceNodeId != null && targetNodeId != null ) { addConnectionTo ( targetNodeId ) ; } gotSource = false ; } currentEdgeSourceNodeId = escaped ( object . getName ( ) ) ; return super . caseNodeId ( object ) ; } private void addConnectionTo ( String targetNodeId ) { GraphConnection graphConnection = new GraphConnection ( graph , SWT . NONE , node ( currentEdgeSourceNodeId ) , node ( targetNodeId ) ) ; if ( currentEdgeLabelValue != null ) { graphConnection . setText ( currentEdgeLabelValue ) ; } else if ( globalEdgeLabel != null ) { graphConnection . setText ( globalEdgeLabel ) ; } if ( currentEdgeStyleValue != null ) { Style v = Enum . valueOf ( Style . class , currentEdgeStyleValue . toUpperCase ( ) ) ; graphConnection . setLineStyle ( v . style ) ; } else if ( globalEdgeStyle != null ) { Style v = Enum . valueOf ( Style . class , globalEdgeStyle . toUpperCase ( ) ) ; graphConnection . setLineStyle ( v . style ) ; } } @ Override public Object caseEdgeRhsNode ( EdgeRhsNode object ) { gotSource = true ; return super . caseEdgeRhsNode ( object ) ; } @ Override public Object caseSubgraph ( Subgraph object ) { createSubgraph ( object ) ; return super . caseSubgraph ( object ) ; } private void createSubgraph ( Subgraph object ) { if ( object . getName ( ) != null && object . getName ( ) . startsWith ( "<STR_LIT>" ) ) { layoutSubgraph ( ) ; currentSubgraph = new GraphContainer ( graph , SWT . NONE ) ; currentSubgraph . setLayoutAlgorithm ( new TreeLayoutAlgorithm ( ) , true ) ; } } private void layoutSubgraph ( ) { if ( currentSubgraph != null ) { currentSubgraph . applyLayout ( ) ; currentSubgraph . open ( false ) ; } } private IContainer currentParentGraph ( ) { return currentSubgraph != null ? currentSubgraph : graph ; } private void createGraph ( MainGraph object ) { graph . setLayoutAlgorithm ( new TreeLayoutAlgorithm ( ) , true ) ; GraphType graphType = object . getType ( ) ; graph . setConnectionStyle ( graphType == GraphType . DIGRAPH ? ZestStyles . CONNECTIONS_DIRECTED : ZestStyles . CONNECTIONS_SOLID ) ; } private void createAttributes ( final AttrStmt attrStmt ) { AttributeType type = attrStmt . getType ( ) ; switch ( type ) { case EDGE : { globalEdgeStyle = getAttributeValue ( attrStmt , "<STR_LIT>" ) ; globalEdgeLabel = getAttributeValue ( attrStmt , "<STR_LIT:label>" ) ; break ; } case NODE : { globalNodeLabel = getAttributeValue ( attrStmt , "<STR_LIT:label>" ) ; break ; } case GRAPH : { for ( AList a : attrStmt . getAttributes ( ) . get ( <NUM_LIT:0> ) . getA_list ( ) ) { graph . setData ( a . getName ( ) , a . getValue ( ) ) ; } String graphLayout = getAttributeValue ( attrStmt , "<STR_LIT>" ) ; if ( graphLayout != null ) { Layout layout = Enum . valueOf ( Layout . class , graphLayout . toUpperCase ( ) ) ; currentParentGraph ( ) . setLayoutAlgorithm ( layout . algorithm , true ) ; } break ; } } } private void createNode ( final NodeStmt nodeStatement ) { String nodeId = escaped ( nodeStatement . getName ( ) ) ; GraphNode node = nodes . containsKey ( nodeId ) ? nodes . get ( nodeId ) : new GraphNode ( currentParentGraph ( ) , SWT . NONE , nodeId ) ; node . setText ( nodeId ) ; node . setData ( nodeId ) ; String value = getAttributeValue ( nodeStatement , "<STR_LIT:label>" ) ; if ( value != null ) { node . setText ( value ) ; } else if ( globalNodeLabel != null ) { node . setText ( globalNodeLabel ) ; } nodes . put ( nodeId , node ) ; } private GraphNode node ( String id ) { if ( ! nodes . containsKey ( id ) ) { GraphNode node = new GraphNode ( currentParentGraph ( ) , SWT . NONE , globalNodeLabel != null ? globalNodeLabel : id ) ; node . setData ( id ) ; nodes . put ( id , node ) ; } return nodes . get ( id ) ; } private String getAttributeValue ( final Stmt eStatementObject , final String attributeName ) { Iterator < EObject > nodeContents = eStatementObject . eContents ( ) . iterator ( ) ; while ( nodeContents . hasNext ( ) ) { EObject nodeContentElement = nodeContents . next ( ) ; if ( nodeContentElement instanceof AttrList ) { Iterator < EObject > attributeContents = nodeContentElement . eContents ( ) . iterator ( ) ; while ( attributeContents . hasNext ( ) ) { EObject next = attributeContents . next ( ) ; if ( next instanceof AList ) { AList attributeElement = ( AList ) next ; if ( attributeElement . getName ( ) . equals ( attributeName ) ) { return escaped ( attributeElement . getValue ( ) ) ; } } } } } return null ; } private String escaped ( String id ) { return id . replaceAll ( "<STR_LIT>" , "<STR_LIT>" ) . replaceAll ( "<STR_LIT>" , "<STR_LIT:\">" ) ; } } </s>
|
<s> package org . eclipse . zest . dot ; import java . io . File ; import org . eclipse . core . resources . IFile ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . zest . core . widgets . Graph ; import org . eclipse . zest . internal . dot . DotExport ; import org . eclipse . zest . internal . dot . DotImport ; import org . eclipse . zest . internal . dot . GraphCreatorInterpreter ; public final class DotGraph extends Graph { public DotGraph ( String dot , Composite parent , int style ) { super ( parent , style ) ; new GraphCreatorInterpreter ( ) . create ( new DotImport ( dot ) . getDotAst ( ) , this ) ; } public DotGraph ( IFile dot , Composite parent , int style ) { super ( parent , style ) ; new GraphCreatorInterpreter ( ) . create ( new DotImport ( dot ) . getDotAst ( ) , this ) ; } public DotGraph ( File dot , Composite parent , int style ) { super ( parent , style ) ; new GraphCreatorInterpreter ( ) . create ( new DotImport ( dot ) . getDotAst ( ) , this ) ; } public DotGraph ( Composite parent , int style ) { super ( parent , style ) ; } public DotGraph add ( String dot ) { new DotImport ( dot ) . into ( this ) ; return this ; } public String toDot ( ) { return new DotExport ( this ) . toDotString ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application ; import org . eclipse . swt . graphics . Point ; import org . eclipse . ui . application . ActionBarAdvisor ; import org . eclipse . ui . application . IActionBarConfigurer ; import org . eclipse . ui . application . IWorkbenchWindowConfigurer ; import org . eclipse . ui . application . WorkbenchWindowAdvisor ; public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { public ApplicationWorkbenchWindowAdvisor ( IWorkbenchWindowConfigurer configurer ) { super ( configurer ) ; } public ActionBarAdvisor createActionBarAdvisor ( IActionBarConfigurer configurer ) { return new ApplicationActionBarAdvisor ( configurer ) ; } public void preWindowOpen ( ) { IWorkbenchWindowConfigurer configurer = getWindowConfigurer ( ) ; configurer . setInitialSize ( new Point ( <NUM_LIT> , <NUM_LIT> ) ) ; configurer . setShowCoolBar ( false ) ; configurer . setShowProgressIndicator ( false ) ; configurer . setTitle ( "<STR_LIT>" ) ; configurer . setShowStatusLine ( false ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . application . IActionBarConfigurer ; import org . eclipse . ui . application . IWorkbenchConfigurer ; import org . eclipse . ui . application . IWorkbenchWindowConfigurer ; import org . eclipse . ui . application . WorkbenchAdvisor ; import org . eclipse . ui . application . WorkbenchWindowAdvisor ; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { @ Override public String getInitialWindowPerspectiveId ( ) { return "<STR_LIT>" ; } @ Override public void initialize ( IWorkbenchConfigurer configurer ) { super . initialize ( configurer ) ; } @ Override public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor ( IWorkbenchWindowConfigurer configurer ) { return new ApplicationWorkbenchWindowAdvisor ( configurer ) ; } @ Override public void fillActionBars ( IWorkbenchWindow window , IActionBarConfigurer configurer , int flags ) { } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application ; import org . eclipse . equinox . app . IApplication ; import org . eclipse . equinox . app . IApplicationContext ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . IWorkbench ; import org . eclipse . ui . PlatformUI ; public class Application implements IApplication { public Object start ( IApplicationContext context ) { Display display = PlatformUI . createDisplay ( ) ; try { int returnCode = PlatformUI . createAndRunWorkbench ( display , new ApplicationWorkbenchAdvisor ( ) ) ; if ( returnCode == PlatformUI . RETURN_RESTART ) { return IApplication . EXIT_RESTART ; } return IApplication . EXIT_OK ; } finally { display . dispose ( ) ; } } public void stop ( ) { final IWorkbench workbench = PlatformUI . getWorkbench ( ) ; if ( workbench == null ) return ; final Display display = workbench . getDisplay ( ) ; display . syncExec ( new Runnable ( ) { public void run ( ) { if ( ! display . isDisposed ( ) ) workbench . close ( ) ; } } ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application ; import org . eclipse . jface . action . ActionContributionItem ; import org . eclipse . jface . action . GroupMarker ; import org . eclipse . jface . action . IMenuManager ; import org . eclipse . jface . action . MenuManager ; import org . eclipse . jface . action . Separator ; import org . eclipse . ui . IWorkbenchActionConstants ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . actions . ActionFactory ; import org . eclipse . ui . actions . ActionFactory . IWorkbenchAction ; import org . eclipse . ui . application . ActionBarAdvisor ; import org . eclipse . ui . application . IActionBarConfigurer ; import org . eclipse . zest . examples . cloudio . application . actions . AboutAction ; public class ApplicationActionBarAdvisor extends ActionBarAdvisor { private IWorkbenchAction exitAction ; private IWorkbenchAction aboutAction ; public ApplicationActionBarAdvisor ( IActionBarConfigurer configurer ) { super ( configurer ) ; } protected void makeActions ( final IWorkbenchWindow window ) { exitAction = ActionFactory . QUIT . create ( window ) ; AboutAction about = new AboutAction ( ) ; register ( about ) ; register ( exitAction ) ; this . aboutAction = about ; } @ Override protected void fillMenuBar ( IMenuManager menuBar ) { MenuManager fileMenu = new MenuManager ( "<STR_LIT>" , IWorkbenchActionConstants . M_FILE ) ; menuBar . add ( fileMenu ) ; ActionContributionItem aboutActionItem = new ActionContributionItem ( aboutAction ) ; fileMenu . add ( aboutActionItem ) ; fileMenu . add ( new Separator ( ) ) ; fileMenu . add ( new GroupMarker ( IWorkbenchActionConstants . MB_ADDITIONS ) ) ; fileMenu . add ( new Separator ( ) ) ; MenuManager editMenu = new MenuManager ( "<STR_LIT>" , IWorkbenchActionConstants . M_EDIT ) ; editMenu . add ( new GroupMarker ( "<STR_LIT>" ) ) ; editMenu . add ( new Separator ( ) ) ; editMenu . add ( new GroupMarker ( "<STR_LIT>" ) ) ; menuBar . add ( editMenu ) ; super . fillMenuBar ( menuBar ) ; ActionContributionItem exitActionItem = new ActionContributionItem ( exitAction ) ; fileMenu . add ( exitActionItem ) ; if ( System . getProperty ( "<STR_LIT>" ) . contains ( "<STR_LIT>" ) ) { aboutActionItem . setVisible ( false ) ; exitActionItem . setVisible ( false ) ; } } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . about ; import java . awt . GraphicsEnvironment ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . dialogs . Dialog ; import org . eclipse . jface . dialogs . IDialogConstants ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Control ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . zest . cloudio . TagCloud ; import org . eclipse . zest . cloudio . Word ; import org . eclipse . zest . cloudio . layout . DefaultLayouter ; public class AboutDialog extends Dialog { private static final int RE_LAYOUT = <NUM_LIT:2> ; private TagCloud tc ; public AboutDialog ( Shell parentShell ) { super ( parentShell ) ; setBlockOnOpen ( false ) ; } @ Override protected Control createDialogArea ( Composite parent ) { parent . setLayout ( new GridLayout ( ) ) ; tc = new TagCloud ( parent , SWT . NONE ) { public Rectangle getClientArea ( ) { return new Rectangle ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> ) ; } ; } ; GridData data = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; data . heightHint = <NUM_LIT> ; data . widthHint = <NUM_LIT> ; tc . setLayoutData ( data ) ; tc . setMaxFontSize ( <NUM_LIT> ) ; tc . setMinFontSize ( <NUM_LIT:15> ) ; tc . setLayouter ( new DefaultLayouter ( <NUM_LIT:5> , <NUM_LIT:0> ) ) ; List < Word > values = new ArrayList < Word > ( ) ; String [ ] fontNames = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) . getAvailableFontFamilyNames ( ) ; Color [ ] colors = new Color [ <NUM_LIT:5> ] ; colors [ <NUM_LIT:0> ] = Display . getDefault ( ) . getSystemColor ( SWT . COLOR_DARK_CYAN ) ; colors [ <NUM_LIT:1> ] = Display . getDefault ( ) . getSystemColor ( SWT . COLOR_DARK_GREEN ) ; colors [ <NUM_LIT:2> ] = Display . getDefault ( ) . getSystemColor ( SWT . COLOR_DARK_MAGENTA ) ; colors [ <NUM_LIT:3> ] = Display . getDefault ( ) . getSystemColor ( SWT . COLOR_DARK_YELLOW ) ; colors [ <NUM_LIT:4> ] = Display . getDefault ( ) . getSystemColor ( SWT . COLOR_GRAY ) ; Word w = getWord ( "<STR_LIT>" , fontNames , colors ) ; w . weight = <NUM_LIT> ; w . angle = - <NUM_LIT> ; w . setColor ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_WHITE ) ) ; values . add ( w ) ; w = getWord ( "<STR_LIT>" , fontNames , colors ) ; w . setColor ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_WHITE ) ) ; w . angle = ( float ) ( Math . random ( ) * <NUM_LIT> ) ; if ( Math . random ( ) < <NUM_LIT> ) w . angle = - w . angle ; w . weight = <NUM_LIT> ; if ( Math . random ( ) < <NUM_LIT> ) w . angle = - w . angle ; values . add ( w ) ; w = getWord ( "<STR_LIT>" + System . getProperty ( "<STR_LIT>" ) , fontNames , colors ) ; w . setColor ( Display . getDefault ( ) . getSystemColor ( SWT . COLOR_WHITE ) ) ; w . weight = <NUM_LIT> ; values . add ( w ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:20> ; i ++ ) { w = getWord ( "<STR_LIT>" , fontNames , colors ) ; values . add ( w ) ; w = getWord ( "<STR_LIT>" , fontNames , colors ) ; values . add ( w ) ; } tc . setWords ( values , null ) ; Label l = new Label ( parent , SWT . NONE ) ; l . setText ( "<STR_LIT>" ) ; return tc ; } protected void createButtonsForButtonBar ( Composite parent ) { createButton ( parent , IDialogConstants . OK_ID , IDialogConstants . OK_LABEL , true ) ; createButton ( parent , RE_LAYOUT , "<STR_LIT>" , false ) ; } @ Override protected void buttonPressed ( int buttonId ) { if ( buttonId == RE_LAYOUT ) { tc . layoutCloud ( null , false ) ; } else { super . buttonPressed ( buttonId ) ; } } private Word getWord ( String string , String [ ] fontNames , Color [ ] colors ) { Word w = new Word ( string ) ; w . setColor ( colors [ ( int ) ( Math . random ( ) * colors . length - <NUM_LIT:1> ) ] ) ; w . weight = Math . random ( ) / <NUM_LIT:2> ; w . setFontData ( getShell ( ) . getFont ( ) . getFontData ( ) ) ; w . angle = ( float ) ( Math . random ( ) * <NUM_LIT:20> ) ; if ( Math . random ( ) < <NUM_LIT> ) w . angle = - w . angle ; String name = fontNames [ ( int ) ( Math . random ( ) * ( fontNames . length - <NUM_LIT:1> ) ) ] ; for ( FontData fd : w . getFontData ( ) ) { fd . setName ( name ) ; } return w ; } @ Override public boolean close ( ) { tc . dispose ( ) ; return super . close ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . data ; public class Type { private String string ; private int occurrences ; public Type ( String string , int occurrences ) { this . string = string ; this . occurrences = occurrences ; } public String getString ( ) { return string ; } public int getOccurrences ( ) { return occurrences ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . data ; import java . io . BufferedInputStream ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; import java . io . InputStreamReader ; import java . text . BreakIterator ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Locale ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; public class TypeCollector { private static String stopWords ; public static List < Type > getData ( File file , String encoding ) throws IOException { BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( file ) ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( bis , encoding ) ) ; StringBuffer text = new StringBuffer ( ) ; String s ; while ( ( s = br . readLine ( ) ) != null ) { text . append ( s + "<STR_LIT:n>" ) ; } br . close ( ) ; Set < String > stops = new HashSet < String > ( ) ; if ( stopWords != null ) { bis = new BufferedInputStream ( new FileInputStream ( stopWords ) ) ; br = new BufferedReader ( new InputStreamReader ( bis , encoding ) ) ; while ( ( s = br . readLine ( ) ) != null ) { stops . add ( s . toLowerCase ( ) . trim ( ) ) ; } br . close ( ) ; } BreakIterator iterator = BreakIterator . getWordInstance ( Locale . getDefault ( ) ) ; String txt = text . toString ( ) ; iterator . setText ( txt ) ; final Map < String , Integer > strings = new HashMap < String , Integer > ( ) ; int boundary = iterator . first ( ) ; int lastBoundary = iterator . first ( ) ; while ( boundary != BreakIterator . DONE ) { boundary = iterator . next ( ) ; if ( boundary != - <NUM_LIT:1> ) { String string = txt . substring ( lastBoundary , boundary ) . trim ( ) ; if ( string . length ( ) != <NUM_LIT:0> ) { if ( ! Character . isLetter ( string . charAt ( string . length ( ) - <NUM_LIT:1> ) ) ) { string = string . substring ( <NUM_LIT:0> , string . length ( ) - <NUM_LIT:1> ) ; } if ( stops . contains ( string . toLowerCase ( ) ) || string . trim ( ) . length ( ) <= <NUM_LIT:1> ) { lastBoundary = boundary ; continue ; } Integer count = strings . get ( string ) ; if ( count == null ) { strings . put ( string , <NUM_LIT:1> ) ; } else { count = count + <NUM_LIT:1> ; strings . put ( string , count ) ; } } } lastBoundary = boundary ; } return getMostImportantTypes ( strings ) ; } private static List < Type > getMostImportantTypes ( final Map < String , Integer > strings ) { List < Type > types = new ArrayList < Type > ( ) ; Iterator < Entry < String , Integer > > iterator = strings . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < String , Integer > entry = iterator . next ( ) ; Type type = new Type ( entry . getKey ( ) , entry . getValue ( ) ) ; types . add ( type ) ; } List < Type > sorted = new ArrayList < Type > ( types ) ; Collections . sort ( sorted , new Comparator < Type > ( ) { @ Override public int compare ( Type o1 , Type o2 ) { return o2 . getOccurrences ( ) - o1 . getOccurrences ( ) ; } } ) ; return sorted ; } public static void setStopwords ( String sourceFile ) { stopWords = sourceFile ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . ui ; import org . eclipse . ui . plugin . AbstractUIPlugin ; import org . osgi . framework . BundleContext ; public class CloudioApplicationPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "<STR_LIT>" ; private static CloudioApplicationPlugin plugin ; public CloudioApplicationPlugin ( ) { } public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; } public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; } public static CloudioApplicationPlugin getDefault ( ) { return plugin ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . ui ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Random ; import org . eclipse . jface . viewers . BaseLabelProvider ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . graphics . RGB ; import org . eclipse . swt . widgets . Display ; import org . eclipse . zest . cloudio . IEditableCloudLabelProvider ; import org . eclipse . zest . examples . cloudio . application . data . Type ; import org . eclipse . zest . examples . cloudio . application . ui . TypeLabelProvider . Scaling ; public class TypeLabelProvider extends BaseLabelProvider implements IEditableCloudLabelProvider { private double maxOccurrences ; private double minOccurrences ; public enum Scaling { LINEAR , LOGARITHMIC ; } private Map < Object , Color > colors = new HashMap < Object , Color > ( ) ; private Map < Object , FontData [ ] > fonts = new HashMap < Object , FontData [ ] > ( ) ; private Random random = new Random ( ) ; protected List < Color > colorList ; protected List < Font > fontList ; protected List < Float > angles ; private Scaling scaling = Scaling . LOGARITHMIC ; public TypeLabelProvider ( ) { colorList = new ArrayList < Color > ( ) ; fontList = new ArrayList < Font > ( ) ; angles = new ArrayList < Float > ( ) ; angles . add ( <NUM_LIT:0F> ) ; } @ Override public String getLabel ( Object element ) { return ( ( Type ) element ) . getString ( ) ; } @ Override public double getWeight ( Object element ) { switch ( scaling ) { case LINEAR : return ( ( Type ) element ) . getOccurrences ( ) / maxOccurrences ; case LOGARITHMIC : { double count = Math . log ( ( ( Type ) element ) . getOccurrences ( ) - minOccurrences + <NUM_LIT:1> ) ; count /= ( Math . log ( maxOccurrences ) ) ; return count ; } default : return <NUM_LIT:1> ; } } @ Override public Color getColor ( Object element ) { Color color = colors . get ( element ) ; if ( color == null ) { color = colorList . get ( random . nextInt ( colorList . size ( ) ) ) ; colors . put ( element , color ) ; } return color ; } public FontData [ ] getFontData ( Object element ) { FontData [ ] data = fonts . get ( element ) ; if ( data == null ) { data = fontList . get ( random . nextInt ( fontList . size ( ) ) ) . getFontData ( ) ; fonts . put ( element , data ) ; } return data ; } public void setMaxOccurrences ( int occurrences ) { this . maxOccurrences = occurrences ; } public void setMinOccurrences ( int occurrences ) { this . minOccurrences = occurrences ; } @ Override public void dispose ( ) { for ( Color color : colorList ) { color . dispose ( ) ; } for ( Font font : fontList ) { font . dispose ( ) ; } } public void setAngles ( List < Float > angles ) { this . angles = angles ; } @ Override public float getAngle ( Object element ) { float angle = angles . get ( random . nextInt ( angles . size ( ) ) ) ; return angle ; } public void setColors ( List < RGB > newColors ) { if ( newColors . isEmpty ( ) ) return ; for ( Color color : colorList ) { color . dispose ( ) ; } colorList . clear ( ) ; colors . clear ( ) ; for ( RGB color : newColors ) { Color c = new Color ( Display . getDefault ( ) , color ) ; colorList . add ( c ) ; } } public void setFonts ( List < FontData > newFonts ) { if ( newFonts . isEmpty ( ) ) return ; for ( Font font : fontList ) { font . dispose ( ) ; } fontList . clear ( ) ; fonts . clear ( ) ; for ( FontData data : newFonts ) { Font f = new Font ( Display . getDefault ( ) , data ) ; fontList . add ( f ) ; } } @ Override public String getToolTip ( Object element ) { return getLabel ( element ) ; } public void setScale ( Scaling scaling ) { this . scaling = scaling ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . ui ; import java . io . BufferedInputStream ; import java . io . File ; import java . io . FileInputStream ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . custom . SashForm ; import org . eclipse . swt . events . ControlEvent ; import org . eclipse . swt . events . ControlListener ; import org . eclipse . swt . events . SelectionEvent ; import org . eclipse . swt . events . SelectionListener ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . ImageLoader ; import org . eclipse . swt . layout . GridData ; import org . eclipse . swt . layout . GridLayout ; import org . eclipse . swt . widgets . Button ; import org . eclipse . swt . widgets . Combo ; import org . eclipse . swt . widgets . Composite ; import org . eclipse . swt . widgets . Event ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . swt . widgets . Group ; import org . eclipse . swt . widgets . Label ; import org . eclipse . swt . widgets . Listener ; import org . eclipse . ui . part . ViewPart ; import org . eclipse . zest . cloudio . CloudOptionsComposite ; import org . eclipse . zest . cloudio . TagCloud ; import org . eclipse . zest . cloudio . TagCloudViewer ; import org . eclipse . zest . cloudio . layout . DefaultLayouter ; import org . eclipse . zest . cloudio . layout . ILayouter ; import org . eclipse . zest . examples . cloudio . application . data . Type ; public class TagCloudViewPart extends ViewPart { private TagCloudViewer viewer ; private TypeLabelProvider labelProvider ; private CloudOptionsComposite options ; private ILayouter layouter ; public TagCloudViewPart ( ) { } @ Override public void createPartControl ( Composite parent ) { SashForm sash = new SashForm ( parent , SWT . HORIZONTAL ) ; sash . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; Composite cloudComp = new Composite ( sash , SWT . NONE ) ; cloudComp . setLayout ( new GridLayout ( ) ) ; cloudComp . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; TagCloud cloud = new TagCloud ( cloudComp , SWT . HORIZONTAL | SWT . VERTICAL ) ; cloud . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; viewer = new TagCloudViewer ( cloud ) ; layouter = new DefaultLayouter ( <NUM_LIT:20> , <NUM_LIT:10> ) ; viewer . setLayouter ( layouter ) ; labelProvider = new TypeLabelProvider ( ) ; viewer . setLabelProvider ( labelProvider ) ; viewer . setContentProvider ( new IStructuredContentProvider ( ) { @ Override public void inputChanged ( Viewer v , Object oldInput , Object newInput ) { List < ? > list = ( List < ? > ) newInput ; if ( list == null || list . size ( ) == <NUM_LIT:0> ) return ; labelProvider . setMaxOccurrences ( ( ( Type ) list . get ( <NUM_LIT:0> ) ) . getOccurrences ( ) ) ; int minIndex = Math . min ( list . size ( ) - <NUM_LIT:1> , viewer . getMaxWords ( ) ) ; labelProvider . setMinOccurrences ( ( ( Type ) list . get ( minIndex ) ) . getOccurrences ( ) ) ; } @ Override public void dispose ( ) { } @ Override public Object [ ] getElements ( Object inputElement ) { return ( ( List < ? > ) inputElement ) . toArray ( ) ; } } ) ; createSideTab ( sash ) ; cloud . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; viewer . getCloud ( ) . addControlListener ( new ControlListener ( ) { @ Override public void controlResized ( ControlEvent e ) { viewer . getCloud ( ) . zoomFit ( ) ; } @ Override public void controlMoved ( ControlEvent e ) { } } ) ; ArrayList < Type > types = new ArrayList < Type > ( ) ; types . add ( new Type ( "<STR_LIT>" , <NUM_LIT> ) ) ; types . add ( new Type ( "<STR_LIT>" , <NUM_LIT> ) ) ; types . add ( new Type ( "<STR_LIT>" , <NUM_LIT:100> ) ) ; types . add ( new Type ( "<STR_LIT>" , <NUM_LIT> ) ) ; int size = <NUM_LIT> ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { types . add ( new Type ( "<STR_LIT>" , size ) ) ; size -- ; } viewer . getCloud ( ) . setMaxFontSize ( <NUM_LIT:100> ) ; viewer . getCloud ( ) . setMinFontSize ( <NUM_LIT:15> ) ; labelProvider . setColors ( options . getColors ( ) ) ; labelProvider . setFonts ( options . getFonts ( ) ) ; sash . setWeights ( new int [ ] { <NUM_LIT> , <NUM_LIT> } ) ; viewer . setInput ( types ) ; } private void createSideTab ( SashForm form ) { Composite parent = new Composite ( form , SWT . NONE ) ; parent . setLayout ( new GridLayout ( ) ) ; parent . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; options = new CloudOptionsComposite ( parent , SWT . NONE , viewer ) { protected Group addMaskButton ( Composite parent ) { Group buttons = new Group ( parent , SWT . SHADOW_IN ) ; buttons . setLayout ( new GridLayout ( <NUM_LIT:2> , true ) ) ; buttons . setLayoutData ( new GridData ( SWT . FILL , SWT . TOP , true , false ) ) ; Label l = new Label ( buttons , SWT . NONE ) ; l . setLayoutData ( new GridData ( SWT . FILL , SWT . CENTER , true , false ) ) ; l . setText ( "<STR_LIT>" ) ; Button file = new Button ( buttons , SWT . FLAT ) ; file . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , false ) ) ; file . setText ( "<STR_LIT>" ) ; file . addListener ( SWT . Selection , new Listener ( ) { @ Override public void handleEvent ( Event event ) { FileDialog fd = new FileDialog ( getShell ( ) , SWT . OPEN ) ; fd . setText ( "<STR_LIT>" ) ; String sourceFile = fd . open ( ) ; if ( sourceFile == null ) return ; try { ImageLoader loader = new ImageLoader ( ) ; BufferedInputStream in = new BufferedInputStream ( new FileInputStream ( new File ( sourceFile ) ) ) ; ImageData [ ] data = loader . load ( in ) ; in . close ( ) ; viewer . getCloud ( ) . setBackgroundMask ( data [ <NUM_LIT:0> ] ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ) ; return buttons ; } protected void addGroups ( ) { addMaskButton ( this ) ; super . addGroups ( ) ; } protected Group addLayoutButtons ( Composite parent ) { Group buttons = super . addLayoutButtons ( parent ) ; Label l = new Label ( buttons , SWT . NONE ) ; l . setText ( "<STR_LIT>" ) ; final Combo scale = new Combo ( buttons , SWT . DROP_DOWN | SWT . READ_ONLY ) ; scale . setLayoutData ( new GridData ( SWT . FILL , SWT . TOP , true , false ) ) ; scale . setItems ( new String [ ] { "<STR_LIT>" , "<STR_LIT>" } ) ; scale . addSelectionListener ( new SelectionListener ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { switch ( scale . getSelectionIndex ( ) ) { case <NUM_LIT:0> : labelProvider . setScale ( TypeLabelProvider . Scaling . LINEAR ) ; break ; case <NUM_LIT:1> : labelProvider . setScale ( TypeLabelProvider . Scaling . LOGARITHMIC ) ; break ; default : break ; } } @ Override public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; scale . select ( <NUM_LIT:1> ) ; l = new Label ( buttons , SWT . NONE ) ; l . setText ( "<STR_LIT>" ) ; final Combo xAxis = new Combo ( buttons , SWT . DROP_DOWN | SWT . READ_ONLY ) ; xAxis . setLayoutData ( new GridData ( SWT . FILL , SWT . TOP , true , false ) ) ; xAxis . setItems ( new String [ ] { "<STR_LIT:0>" , "<STR_LIT:10>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ) ; xAxis . select ( <NUM_LIT:2> ) ; xAxis . addSelectionListener ( new SelectionListener ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { String item = xAxis . getItem ( xAxis . getSelectionIndex ( ) ) ; layouter . setOption ( DefaultLayouter . X_AXIS_VARIATION , Integer . parseInt ( item ) ) ; } @ Override public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; l = new Label ( buttons , SWT . NONE ) ; l . setText ( "<STR_LIT>" ) ; final Combo yAxis = new Combo ( buttons , SWT . DROP_DOWN | SWT . READ_ONLY ) ; yAxis . setLayoutData ( new GridData ( SWT . FILL , SWT . TOP , true , false ) ) ; yAxis . setItems ( new String [ ] { "<STR_LIT:0>" , "<STR_LIT:10>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ) ; yAxis . select ( <NUM_LIT:1> ) ; yAxis . addSelectionListener ( new SelectionListener ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { String item = yAxis . getItem ( yAxis . getSelectionIndex ( ) ) ; layouter . setOption ( DefaultLayouter . Y_AXIS_VARIATION , Integer . parseInt ( item ) ) ; } @ Override public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; Button run = new Button ( buttons , SWT . NONE ) ; run . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; run . setText ( "<STR_LIT>" ) ; run . addSelectionListener ( new SelectionListener ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { final ProgressMonitorDialog dialog = new ProgressMonitorDialog ( viewer . getControl ( ) . getShell ( ) ) ; dialog . setBlockOnOpen ( false ) ; dialog . open ( ) ; dialog . getProgressMonitor ( ) . beginTask ( "<STR_LIT>" , <NUM_LIT:100> ) ; viewer . reset ( dialog . getProgressMonitor ( ) , false ) ; dialog . close ( ) ; } @ Override public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; Button layout = new Button ( buttons , SWT . NONE ) ; layout . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; layout . setText ( "<STR_LIT>" ) ; layout . addSelectionListener ( new SelectionListener ( ) { @ Override public void widgetSelected ( SelectionEvent e ) { ProgressMonitorDialog dialog = new ProgressMonitorDialog ( viewer . getControl ( ) . getShell ( ) ) ; dialog . setBlockOnOpen ( false ) ; dialog . open ( ) ; dialog . getProgressMonitor ( ) . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; viewer . setInput ( viewer . getInput ( ) , dialog . getProgressMonitor ( ) ) ; dialog . close ( ) ; } @ Override public void widgetDefaultSelected ( SelectionEvent e ) { } } ) ; return buttons ; } ; } ; GridData gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; options . setLayoutData ( gd ) ; } @ Override public void setFocus ( ) { viewer . getCloud ( ) . setFocus ( ) ; } @ Override public void dispose ( ) { viewer . getCloud ( ) . dispose ( ) ; labelProvider . dispose ( ) ; } public TagCloudViewer getViewer ( ) { return viewer ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . ui . customization ; import org . eclipse . swt . graphics . Point ; import org . eclipse . swt . graphics . Rectangle ; import org . eclipse . zest . cloudio . Word ; import org . eclipse . zest . cloudio . layout . DefaultLayouter ; public class CharacterLayouter extends DefaultLayouter { public CharacterLayouter ( int x , int y ) { super ( x , y ) ; } public Point getInitialOffset ( Word word , Rectangle cloudArea ) { Point parentOffsets = super . getInitialOffset ( word , new Rectangle ( cloudArea . x , cloudArea . y , cloudArea . width / <NUM_LIT:4> , cloudArea . height / <NUM_LIT:4> ) ) ; char firstChar = Character . toLowerCase ( word . string . charAt ( <NUM_LIT:0> ) ) ; int x = cloudArea . width / <NUM_LIT:4> ; int y = cloudArea . height / <NUM_LIT:4> ; if ( firstChar < '<CHAR_LIT>' ) { x = <NUM_LIT:0> ; y = <NUM_LIT:0> ; } if ( firstChar < '<CHAR_LIT>' ) { x = cloudArea . width / <NUM_LIT:4> ; y = <NUM_LIT:0> ; } if ( firstChar < '<CHAR_LIT>' ) { x = <NUM_LIT:0> ; y = cloudArea . height / <NUM_LIT:4> ; } return new Point ( x + parentOffsets . x , y + parentOffsets . y ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . ui . customization ; import org . eclipse . swt . graphics . Color ; import org . eclipse . zest . examples . cloudio . application . data . Type ; import org . eclipse . zest . examples . cloudio . application . ui . TypeLabelProvider ; public class CharacterLabelProvider extends TypeLabelProvider { @ Override public Color getColor ( Object element ) { Type t = ( Type ) element ; char firstChar = Character . toLowerCase ( t . getString ( ) . charAt ( <NUM_LIT:0> ) ) ; if ( firstChar < '<CHAR_LIT>' ) { return colorList . get ( <NUM_LIT:2> ) ; } if ( firstChar < '<CHAR_LIT>' ) { return colorList . get ( <NUM_LIT:1> ) ; } if ( firstChar < '<CHAR_LIT>' ) { return colorList . get ( <NUM_LIT:0> ) ; } return colorList . get ( <NUM_LIT:3> ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application ; import org . eclipse . ui . IPageLayout ; import org . eclipse . ui . IPerspectiveFactory ; public class PerspectiveFactory implements IPerspectiveFactory { @ Override public void createInitialLayout ( IPageLayout layout ) { layout . addStandaloneView ( "<STR_LIT>" , false , IPageLayout . TOP , <NUM_LIT> , layout . getEditorArea ( ) ) ; layout . setFixed ( true ) ; layout . setEditorAreaVisible ( false ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import java . io . File ; import java . io . IOException ; import java . util . List ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . ProgressMonitorDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . zest . cloudio . TagCloudViewer ; import org . eclipse . zest . examples . cloudio . application . data . Type ; import org . eclipse . zest . examples . cloudio . application . data . TypeCollector ; public class LoadFileAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { FileDialog dialog = new FileDialog ( getShell ( ) , SWT . OPEN ) ; dialog . setText ( "<STR_LIT>" ) ; String sourceFile = dialog . open ( ) ; if ( sourceFile == null ) return ; ProgressMonitorDialog pd = new ProgressMonitorDialog ( getShell ( ) ) ; try { List < Type > types = TypeCollector . getData ( new File ( sourceFile ) , "<STR_LIT:UTF-8>" ) ; pd . setBlockOnOpen ( false ) ; pd . open ( ) ; pd . getProgressMonitor ( ) . beginTask ( "<STR_LIT>" , <NUM_LIT> ) ; TagCloudViewer viewer = getViewer ( ) ; viewer . setInput ( types , pd . getProgressMonitor ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { pd . close ( ) ; } } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; public class ZoomFitAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { getViewer ( ) . zoomFit ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; public class ZoomInAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { getViewer ( ) . zoomIn ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import java . io . File ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . dialogs . MessageDialog ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . ImageData ; import org . eclipse . swt . graphics . ImageLoader ; import org . eclipse . swt . widgets . FileDialog ; public class ExportImageAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { FileDialog dialog = new FileDialog ( getShell ( ) , SWT . SAVE ) ; dialog . setFileName ( "<STR_LIT>" ) ; dialog . setText ( "<STR_LIT>" ) ; String destFile = dialog . open ( ) ; if ( destFile == null ) return ; File f = new File ( destFile ) ; if ( f . exists ( ) ) { boolean confirmed = MessageDialog . openConfirm ( getShell ( ) , "<STR_LIT>" , "<STR_LIT>" + f . getName ( ) + "<STR_LIT>" ) ; if ( ! confirmed ) return ; } ImageLoader il = new ImageLoader ( ) ; try { il . data = new ImageData [ ] { getViewer ( ) . getCloud ( ) . getImageData ( ) } ; il . save ( destFile , SWT . IMAGE_PNG ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . StructuredSelection ; public class DeselectAllAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { StructuredSelection selection = new StructuredSelection ( ) ; getViewer ( ) . setSelection ( selection ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; public class ZoomOutAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { getViewer ( ) . zoomOut ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . FileDialog ; import org . eclipse . zest . examples . cloudio . application . data . TypeCollector ; public class LoadStopWordsAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { FileDialog dialog = new FileDialog ( getShell ( ) , SWT . OPEN ) ; dialog . setText ( "<STR_LIT>" ) ; String sourceFile = dialog . open ( ) ; if ( sourceFile == null ) return ; TypeCollector . setStopwords ( sourceFile ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . ISelection ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . ui . IWorkbenchWindow ; import org . eclipse . ui . IWorkbenchWindowActionDelegate ; import org . eclipse . zest . cloudio . TagCloudViewer ; import org . eclipse . zest . examples . cloudio . application . ui . TagCloudViewPart ; public abstract class AbstractTagCloudAction implements IWorkbenchWindowActionDelegate { private Shell shell ; private TagCloudViewPart tcViewPart ; @ Override public void selectionChanged ( IAction action , ISelection selection ) { } @ Override public void dispose ( ) { } @ Override public void init ( IWorkbenchWindow window ) { this . shell = window . getShell ( ) ; tcViewPart = ( TagCloudViewPart ) window . getActivePage ( ) . getActivePart ( ) ; } public Shell getShell ( ) { return shell ; } protected TagCloudViewer getViewer ( ) { return tcViewPart . getViewer ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . IAction ; public class ZoomResetAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { getViewer ( ) . zoomReset ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import java . util . List ; import org . eclipse . jface . action . IAction ; import org . eclipse . jface . viewers . StructuredSelection ; public class SelectAllAction extends AbstractTagCloudAction { @ Override public void run ( IAction action ) { StructuredSelection selection = new StructuredSelection ( ( List < ? > ) getViewer ( ) . getInput ( ) ) ; getViewer ( ) . setSelection ( selection ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . application . actions ; import org . eclipse . jface . action . Action ; import org . eclipse . swt . widgets . Display ; import org . eclipse . ui . actions . ActionFactory . IWorkbenchAction ; import org . eclipse . zest . examples . cloudio . application . about . AboutDialog ; public class AboutAction extends Action implements IWorkbenchAction { public AboutAction ( ) { super . setId ( "<STR_LIT>" ) ; setText ( "<STR_LIT>" ) ; } @ Override public void run ( ) { AboutDialog dialog = new AboutDialog ( Display . getCurrent ( ) . getActiveShell ( ) ) ; dialog . open ( ) ; } @ Override public void dispose ( ) { } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . snippets ; import java . util . ArrayList ; import java . util . List ; import org . eclipse . swt . SWT ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . zest . cloudio . TagCloud ; import org . eclipse . zest . cloudio . Word ; public class TagCloudSnippet { public static void main ( String [ ] args ) { final Display display = new Display ( ) ; final Shell shell = new Shell ( display ) ; TagCloud cloud = new TagCloud ( shell , SWT . NONE ) ; List < Word > words = new ArrayList < Word > ( ) ; Word w = new Word ( "<STR_LIT:Hello>" ) ; w . setColor ( display . getSystemColor ( SWT . COLOR_DARK_CYAN ) ) ; w . weight = <NUM_LIT:1> ; w . setFontData ( cloud . getFont ( ) . getFontData ( ) . clone ( ) ) ; words . add ( w ) ; w = new Word ( "<STR_LIT>" ) ; w . setColor ( display . getSystemColor ( SWT . COLOR_DARK_GREEN ) ) ; w . setFontData ( cloud . getFont ( ) . getFontData ( ) . clone ( ) ) ; w . weight = <NUM_LIT> ; w . angle = - <NUM_LIT> ; words . add ( w ) ; shell . setBounds ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ; cloud . setBounds ( <NUM_LIT:0> , <NUM_LIT:0> , shell . getBounds ( ) . width , shell . getBounds ( ) . height ) ; cloud . setWords ( words , null ) ; shell . open ( ) ; while ( ! shell . isDisposed ( ) ) { if ( ! display . readAndDispatch ( ) ) display . sleep ( ) ; } display . dispose ( ) ; } } </s>
|
<s> package org . eclipse . zest . examples . cloudio . snippets ; import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; import org . eclipse . jface . viewers . BaseLabelProvider ; import org . eclipse . jface . viewers . ISelectionChangedListener ; import org . eclipse . jface . viewers . IStructuredContentProvider ; import org . eclipse . jface . viewers . IStructuredSelection ; import org . eclipse . jface . viewers . SelectionChangedEvent ; import org . eclipse . jface . viewers . StructuredSelection ; import org . eclipse . jface . viewers . Viewer ; import org . eclipse . swt . SWT ; import org . eclipse . swt . graphics . Color ; import org . eclipse . swt . graphics . Font ; import org . eclipse . swt . graphics . FontData ; import org . eclipse . swt . widgets . Display ; import org . eclipse . swt . widgets . Shell ; import org . eclipse . zest . cloudio . ICloudLabelProvider ; import org . eclipse . zest . cloudio . TagCloud ; import org . eclipse . zest . cloudio . TagCloudViewer ; public class TagCloudViewerSnippet { static class CustomLabelProvider extends BaseLabelProvider implements ICloudLabelProvider { private Font font ; public CustomLabelProvider ( Font font ) { this . font = font ; } @ Override public String getLabel ( Object element ) { return element . toString ( ) ; } @ Override public double getWeight ( Object element ) { return Math . random ( ) ; } @ Override public Color getColor ( Object element ) { return Display . getDefault ( ) . getSystemColor ( SWT . COLOR_GREEN ) ; } @ Override public FontData [ ] getFontData ( Object element ) { return font . getFontData ( ) ; } @ Override public float getAngle ( Object element ) { return ( float ) ( - <NUM_LIT> + Math . random ( ) * <NUM_LIT> ) ; } @ Override public String getToolTip ( Object element ) { return element . toString ( ) ; } } public static void main ( String [ ] args ) { final Display display = new Display ( ) ; final Shell shell = new Shell ( display ) ; TagCloud cloud = new TagCloud ( shell , SWT . NONE ) ; final TagCloudViewer viewer = new TagCloudViewer ( cloud ) ; viewer . setContentProvider ( new IStructuredContentProvider ( ) { @ Override public void dispose ( ) { } @ Override public void inputChanged ( Viewer viewer , Object oldInput , Object newInput ) { } @ Override public Object [ ] getElements ( Object inputElement ) { return ( ( List < ? > ) inputElement ) . toArray ( ) ; } } ) ; viewer . setLabelProvider ( new CustomLabelProvider ( cloud . getFont ( ) ) ) ; viewer . addSelectionChangedListener ( new ISelectionChangedListener ( ) { @ Override public void selectionChanged ( SelectionChangedEvent event ) { IStructuredSelection selection = ( IStructuredSelection ) viewer . getSelection ( ) ; System . out . println ( "<STR_LIT>" + selection ) ; } } ) ; List < String > data = new ArrayList < String > ( ) ; data . add ( "<STR_LIT:Hello>" ) ; data . add ( "<STR_LIT>" ) ; data . add ( "<STR_LIT>" ) ; shell . setBounds ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ; cloud . setBounds ( <NUM_LIT:0> , <NUM_LIT:0> , shell . getBounds ( ) . width , shell . getBounds ( ) . height ) ; viewer . setInput ( data ) ; viewer . setSelection ( new StructuredSelection ( Arrays . asList ( "<STR_LIT>" ) ) ) ; shell . open ( ) ; while ( ! shell . isDisposed ( ) ) { if ( ! display . readAndDispatch ( ) ) display . sleep ( ) ; } display . dispose ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . commands ; import org . eclipse . osgi . framework . console . CommandProvider ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; public class CommandsActivator implements BundleActivator { public void start ( BundleContext context ) throws Exception { context . registerService ( CommandProvider . class . getName ( ) , new RabbitCommands ( context ) , null ) ; } public void stop ( BundleContext context ) throws Exception { } } </s>
|
<s> package com . rabbitmq . client . osgi . commands ; import java . io . IOException ; import org . eclipse . osgi . framework . console . CommandInterpreter ; import org . eclipse . osgi . framework . console . CommandProvider ; import org . osgi . framework . BundleContext ; import org . osgi . framework . InvalidSyntaxException ; import org . osgi . framework . ServiceReference ; import com . rabbitmq . client . Channel ; import com . rabbitmq . client . Connection ; import com . rabbitmq . client . GetResponse ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class RabbitCommands implements CommandProvider { public final String HELP_LIST_CONNS = "<STR_LIT>" ; public final String HELP_DECL_EXCHANGE = "<STR_LIT>" ; public final String HELP_DECL_QUEUE = "<STR_LIT>" ; public final String HELP_BIND_QUEUE = "<STR_LIT>" ; public final String HELP_PUBLISH = "<STR_LIT>" ; public final String HELP_RECEIVE = "<STR_LIT>" ; private final BundleContext context ; public RabbitCommands ( BundleContext context ) { this . context = context ; } public String getHelp ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "<STR_LIT>" ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_LIST_CONNS ) . append ( '<STR_LIT:\n>' ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_DECL_EXCHANGE ) . append ( '<STR_LIT:\n>' ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_DECL_QUEUE ) . append ( '<STR_LIT:\n>' ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_BIND_QUEUE ) . append ( '<STR_LIT:\n>' ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_PUBLISH ) . append ( '<STR_LIT:\n>' ) ; buf . append ( '<STR_LIT:\t>' ) . append ( HELP_RECEIVE ) . append ( '<STR_LIT:\n>' ) ; return buf . toString ( ) ; } public void _listConns ( CommandInterpreter ci ) throws InvalidSyntaxException { ServiceReference [ ] refs = context . getServiceReferences ( Connection . class . getName ( ) , null ) ; if ( refs != null ) { for ( ServiceReference ref : refs ) { String name = ( String ) ref . getProperty ( ServiceProperties . CONNECTION_NAME ) ; String host = ( String ) ref . getProperty ( ServiceProperties . CONNECTION_HOST ) ; ci . println ( "<STR_LIT:{>" + name + "<STR_LIT>" + ServiceProperties . CONNECTION_HOST + "<STR_LIT:=>" + host + "<STR_LIT:}>" ) ; ci . println ( "<STR_LIT:t>" + "<STR_LIT>" + ref . getBundle ( ) . getSymbolicName ( ) + "<STR_LIT:U+0020>" + ref . getBundle ( ) . getHeaders ( ) . get ( org . osgi . framework . Constants . BUNDLE_VERSION ) ) ; } } else { ci . println ( "<STR_LIT>" ) ; } } public void _declExchange ( final CommandInterpreter ci ) { String conn = ci . nextArgument ( ) ; final String exchange = ci . nextArgument ( ) ; final String type = ci . nextArgument ( ) ; if ( conn == null || exchange == null || type == null ) { ci . println ( "<STR_LIT>" + HELP_DECL_EXCHANGE ) ; return ; } withConnection ( conn , ci , new ChannelOp ( ) { public void execute ( Channel channel ) { try { channel . exchangeDeclare ( exchange , type ) ; ci . println ( "<STR_LIT>" ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } ) ; } public void _declQ ( final CommandInterpreter ci ) { String channelName = ci . nextArgument ( ) ; final String queueName = ci . nextArgument ( ) ; if ( channelName == null || queueName == null ) { ci . println ( "<STR_LIT>" + HELP_DECL_QUEUE ) ; return ; } withConnection ( channelName , ci , new ChannelOp ( ) { public void execute ( Channel channel ) { try { channel . queueDeclare ( queueName ) ; ci . println ( "<STR_LIT>" ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } ) ; } public void _bindQ ( final CommandInterpreter ci ) { String channelName = ci . nextArgument ( ) ; final String queueName = ci . nextArgument ( ) ; final String exchangeName = ci . nextArgument ( ) ; final String routingKey = ci . nextArgument ( ) ; if ( channelName == null || queueName == null || exchangeName == null || routingKey == null ) { ci . println ( "<STR_LIT>" + HELP_BIND_QUEUE ) ; } withConnection ( channelName , ci , new ChannelOp ( ) { public void execute ( Channel channel ) { try { channel . queueBind ( queueName , exchangeName , routingKey ) ; ci . println ( "<STR_LIT>" ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } ) ; } public void _publish ( final CommandInterpreter ci ) { String channelName = ci . nextArgument ( ) ; final String exchange = ci . nextArgument ( ) ; final String routingKey = ci . nextArgument ( ) ; final String message = ci . nextArgument ( ) ; if ( channelName == null || exchange == null || routingKey == null || message == null ) { ci . println ( "<STR_LIT>" + HELP_PUBLISH ) ; return ; } withConnection ( channelName , ci , new ChannelOp ( ) { public void execute ( Channel channel ) { try { channel . basicPublish ( exchange , routingKey , null , message . getBytes ( ) ) ; ci . println ( "<STR_LIT>" ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } ) ; } public void _receive ( final CommandInterpreter ci ) { String channelName = ci . nextArgument ( ) ; final String queue = ci . nextArgument ( ) ; if ( channelName == null || queue == null ) { ci . println ( "<STR_LIT>" + HELP_RECEIVE ) ; return ; } withConnection ( channelName , ci , new ChannelOp ( ) { public void execute ( Channel channel ) { try { GetResponse response = channel . basicGet ( queue , true ) ; if ( response == null ) { ci . println ( "<STR_LIT>" ) ; } else { ci . println ( "<STR_LIT>" ) ; byte [ ] body = response . getBody ( ) ; String message = new String ( body ) ; ci . println ( message ) ; } } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } ) ; } private ServiceReference getConnectionByName ( String name ) { ServiceReference result = null ; try { ServiceReference [ ] refs = context . getServiceReferences ( Connection . class . getName ( ) , String . format ( "<STR_LIT>" , ServiceProperties . CONNECTION_NAME , name ) ) ; if ( refs != null && refs . length > <NUM_LIT:0> ) { result = refs [ <NUM_LIT:0> ] ; } } catch ( InvalidSyntaxException e ) { e . printStackTrace ( ) ; } return result ; } private void withConnection ( String name , CommandInterpreter ci , ChannelOp op ) { ServiceReference ref = getConnectionByName ( name ) ; if ( ref == null ) { ci . println ( "<STR_LIT>" ) ; return ; } Connection conn = ( Connection ) context . getService ( ref ) ; if ( conn == null ) { ci . println ( "<STR_LIT>" ) ; return ; } Channel channel = null ; try { channel = conn . createChannel ( ) ; op . execute ( channel ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } finally { context . ungetService ( ref ) ; if ( channel != null ) { try { channel . close ( ) ; } catch ( IOException e ) { ci . println ( "<STR_LIT>" ) ; ci . printStackTrace ( e ) ; } } } } private interface ChannelOp { public void execute ( Channel channel ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . util . Dictionary ; import java . util . HashMap ; import java . util . Map ; import org . apache . log4j . Logger ; import org . osgi . framework . BundleContext ; import org . osgi . service . cm . ConfigurationException ; import org . osgi . service . cm . ManagedServiceFactory ; import com . rabbitmq . client . osgi . common . CMPropertyAccessor ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class ConnectionExchangeMSF implements ManagedServiceFactory { private static final String EXCHANGE_TYPE_DIRECT = "<STR_LIT>" ; private static final Logger LOG = Logger . getLogger ( ConnectionExchangeMSF . class ) ; private final BundleContext context ; private Map < String , ConnectionExchangeTracker > map = new HashMap < String , ConnectionExchangeTracker > ( ) ; public ConnectionExchangeMSF ( BundleContext context ) { this . context = context ; } public void deleted ( String pid ) { ConnectionExchangeTracker tracker = null ; synchronized ( map ) { tracker = map . remove ( pid ) ; } if ( tracker != null ) tracker . close ( ) ; LOG . debug ( "<STR_LIT>" + tracker . getConnectionName ( ) + "<STR_LIT>" + tracker . getExchangeName ( ) + "<STR_LIT>" ) ; } public String getName ( ) { return "<STR_LIT>" ; } public void updated ( String pid , @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Dictionary dict ) throws ConfigurationException { CMPropertyAccessor accessor = new CMPropertyAccessor ( dict ) ; String connName = accessor . getMandatoryString ( ServiceProperties . CONNECTION_NAME ) ; String exchangeName = accessor . getMandatoryString ( ServiceProperties . EXCHANGE_NAME ) ; String exchangeType = accessor . getString ( ServiceProperties . EXCHANGE_TYPE ) ; if ( exchangeType == null ) { exchangeType = EXCHANGE_TYPE_DIRECT ; } boolean passive = accessor . getBoolean ( ServiceProperties . EXCHANGE_PASSIVE , false ) ; boolean durable = accessor . getBoolean ( ServiceProperties . EXCHANGE_DURABLE , false ) ; boolean autoDelete = accessor . getBoolean ( ServiceProperties . EXCHANGE_AUTODELETE , false ) ; Map < String , Object > args = null ; LOG . debug ( "<STR_LIT>" + connName + "<STR_LIT>" + exchangeName + "<STR_LIT>" ) ; ConnectionExchangeTracker tracker = new ConnectionExchangeTracker ( context , connName , exchangeName , exchangeType , passive , durable , autoDelete , args ) ; tracker . open ( ) ; ConnectionExchangeTracker old = null ; synchronized ( map ) { old = map . put ( pid , tracker ) ; } if ( old != null ) old . close ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . util . Dictionary ; import java . util . HashMap ; import java . util . Map ; import org . apache . log4j . Logger ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Constants ; import org . osgi . service . cm . ConfigurationException ; import org . osgi . service . cm . ManagedServiceFactory ; import com . rabbitmq . client . AMQP ; import com . rabbitmq . client . osgi . common . CMPropertyAccessor ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class ExchangeWireEndpointMSF implements ManagedServiceFactory { private static Logger LOG = Logger . getLogger ( ExchangeWireEndpointMSF . class ) ; private final BundleContext context ; private Map < String , ExchangeWireEndpointTracker > map = new HashMap < String , ExchangeWireEndpointTracker > ( ) ; public ExchangeWireEndpointMSF ( BundleContext context ) { this . context = context ; } public void deleted ( String pid ) { ExchangeWireEndpointTracker tracker = null ; synchronized ( map ) { tracker = map . remove ( pid ) ; } if ( tracker != null ) tracker . close ( ) ; LOG . info ( "<STR_LIT>" + tracker . getExchangeName ( ) + "<STR_LIT>" ) ; } public String getName ( ) { return "<STR_LIT>" ; } public void updated ( String pid , @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Dictionary dict ) throws ConfigurationException { CMPropertyAccessor accessor = new CMPropertyAccessor ( dict ) ; String connection = accessor . getString ( ServiceProperties . CONNECTION_NAME ) ; String exchange = accessor . getMandatoryString ( ServiceProperties . EXCHANGE_NAME ) ; String routingKey = accessor . getMandatoryString ( ServiceProperties . PUBLISH_ROUTING_KEY ) ; String endpointPid = accessor . getMandatoryString ( ServiceProperties . ENDPOINT_SERVICE_PID ) ; boolean mandatory = accessor . getBoolean ( ServiceProperties . PUBLISH_MANDATORY , false ) ; boolean immediate = accessor . getBoolean ( ServiceProperties . PUBLISH_IMMEDIATE , false ) ; AMQP . BasicProperties props = null ; LOG . debug ( "<STR_LIT>" + exchange + "<STR_LIT>" ) ; ExchangeWireEndpointTracker tracker = new ExchangeWireEndpointTracker ( context , exchange , connection , routingKey , endpointPid , mandatory , immediate , props ) ; tracker . open ( ) ; ExchangeWireEndpointTracker old = null ; synchronized ( map ) { old = map . put ( pid , tracker ) ; } if ( old != null ) old . close ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . io . IOException ; import java . util . Map ; import java . util . Properties ; import org . apache . log4j . Logger ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Filter ; import org . osgi . framework . FrameworkUtil ; import org . osgi . framework . InvalidSyntaxException ; import org . osgi . framework . ServiceReference ; import org . osgi . framework . ServiceRegistration ; import org . osgi . util . tracker . ServiceTracker ; import com . rabbitmq . client . Channel ; import com . rabbitmq . client . Connection ; import com . rabbitmq . client . ShutdownSignalException ; import com . rabbitmq . client . osgi . api . Exchange ; import com . rabbitmq . client . osgi . common . Pair ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class ConnectionExchangeTracker extends ServiceTracker { private static final Logger LOG = Logger . getLogger ( ConnectionExchangeTracker . class ) ; private final String connName ; private final String exchangeName ; private final String type ; private final boolean passive ; private final boolean durable ; private final boolean autoDelete ; private final Map < String , Object > arguments ; public ConnectionExchangeTracker ( BundleContext context , String connName , String exchangeName , String type , boolean passive , boolean durable , boolean autoDelete , Map < String , Object > arguments ) { super ( context , createFilter ( connName ) , null ) ; this . connName = connName ; this . exchangeName = exchangeName ; this . type = type ; this . passive = passive ; this . durable = durable ; this . autoDelete = autoDelete ; this . arguments = arguments ; } private static Filter createFilter ( String connName ) { String filterStr = String . format ( "<STR_LIT>" , ServiceProperties . CONNECTION_NAME , connName ) ; try { return FrameworkUtil . createFilter ( filterStr ) ; } catch ( InvalidSyntaxException e ) { throw new RuntimeException ( e ) ; } } @ Override public Object addingService ( ServiceReference reference ) { Connection conn = ( Connection ) context . getService ( reference ) ; Channel channel = null ; try { channel = conn . createChannel ( ) ; LOG . debug ( "<STR_LIT>" + connName + "<STR_LIT>" + exchangeName + "<STR_LIT:'>" ) ; channel . exchangeDeclare ( exchangeName , type , passive , durable , autoDelete , arguments ) ; ChannelExchange exchange = new ChannelExchange ( exchangeName , channel ) ; Properties props = new Properties ( ) ; props . put ( ServiceProperties . EXCHANGE_NAME , exchangeName ) ; props . put ( ServiceProperties . EXCHANGE_CONNECTION , connName ) ; props . put ( ServiceProperties . EXCHANGE_TYPE , type ) ; ServiceRegistration reg = context . registerService ( Exchange . class . getName ( ) , exchange , props ) ; Pair < Channel , ServiceRegistration > pair = new Pair < Channel , ServiceRegistration > ( channel , reg ) ; return pair ; } catch ( IOException e ) { LOG . error ( "<STR_LIT>" , e ) ; return null ; } finally { try { channel . close ( ) ; } catch ( IOException e ) { LOG . error ( "<STR_LIT>" , e ) ; } } } @ Override public void removedService ( ServiceReference reference , Object service ) { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Pair < Channel , ServiceRegistration > pair = ( Pair < Channel , ServiceRegistration > ) service ; LOG . debug ( "<STR_LIT>" + connName + "<STR_LIT>" + exchangeName + "<STR_LIT:'>" ) ; pair . getSnd ( ) . unregister ( ) ; try { pair . getFst ( ) . close ( ) ; } catch ( IOException e ) { LOG . error ( "<STR_LIT>" , e ) ; } catch ( ShutdownSignalException e ) { LOG . warn ( "<STR_LIT>" ) ; } context . ungetService ( reference ) ; } public String getConnectionName ( ) { return connName ; } public String getExchangeName ( ) { return exchangeName ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . io . IOException ; import org . osgi . service . wireadmin . Consumer ; import org . osgi . service . wireadmin . Wire ; import com . rabbitmq . client . AMQP . BasicProperties ; import com . rabbitmq . client . osgi . api . Exchange ; public class ExchangeWireEndpoint implements Consumer { private final Exchange exchange ; private final String routingKey ; private final boolean mandatory ; private final boolean immediate ; private final BasicProperties props ; public ExchangeWireEndpoint ( Exchange exchange , String routingKey , boolean mandatory , boolean immediate , BasicProperties props ) { this . exchange = exchange ; this . routingKey = routingKey ; this . mandatory = mandatory ; this . immediate = immediate ; this . props = props ; } public void producersConnected ( Wire [ ] wires ) { } public void updated ( Wire wire , Object value ) { byte [ ] body = ( byte [ ] ) value ; try { exchange . basicPublish ( routingKey , mandatory , immediate , props , body ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . io . IOException ; import com . rabbitmq . client . Channel ; import com . rabbitmq . client . AMQP . BasicProperties ; import com . rabbitmq . client . osgi . api . Exchange ; public class ChannelExchange implements Exchange { private final String name ; private final Channel channel ; public ChannelExchange ( String name , Channel channel ) { this . name = name ; this . channel = channel ; } public void basicPublish ( String routingKey , BasicProperties props , byte [ ] body ) throws IOException { channel . basicPublish ( name , routingKey , props , body ) ; } public void basicPublish ( String routingKey , boolean mandatory , boolean immediate , BasicProperties props , byte [ ] body ) throws IOException { channel . basicPublish ( name , routingKey , mandatory , immediate , props , body ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . util . Properties ; import org . apache . log4j . Logger ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Constants ; import org . osgi . framework . Filter ; import org . osgi . framework . FrameworkUtil ; import org . osgi . framework . InvalidSyntaxException ; import org . osgi . framework . ServiceReference ; import org . osgi . framework . ServiceRegistration ; import org . osgi . service . wireadmin . Consumer ; import org . osgi . service . wireadmin . WireConstants ; import org . osgi . util . tracker . ServiceTracker ; import com . rabbitmq . client . AMQP . BasicProperties ; import com . rabbitmq . client . osgi . api . Exchange ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class ExchangeWireEndpointTracker extends ServiceTracker { private static final Class < ? extends byte [ ] > CLASS_BYTE_ARRAY = ( new byte [ ] { } ) . getClass ( ) ; private static final Logger LOG = Logger . getLogger ( ExchangeWireEndpointTracker . class ) ; private final String endpointPid ; private final String exchangeName ; private final String routingKey ; private final boolean mandatory ; private final boolean immediate ; private final BasicProperties props ; public ExchangeWireEndpointTracker ( BundleContext context , String exchangeName , String connection , String routingKey , String endpointPid , boolean mandatory , boolean immediate , BasicProperties props ) { super ( context , createFilter ( exchangeName , connection ) , null ) ; this . exchangeName = exchangeName ; this . routingKey = routingKey ; this . endpointPid = endpointPid ; this . mandatory = mandatory ; this . immediate = immediate ; this . props = props ; } private static Filter createFilter ( String exchange , String connection ) { String filterStr ; if ( connection != null ) { filterStr = String . format ( "<STR_LIT>" , ServiceProperties . EXCHANGE_NAME , exchange , ServiceProperties . CONNECTION_NAME , connection ) ; } else { filterStr = String . format ( "<STR_LIT>" , ServiceProperties . EXCHANGE_NAME , exchange ) ; } try { return FrameworkUtil . createFilter ( filterStr ) ; } catch ( InvalidSyntaxException e ) { throw new RuntimeException ( e ) ; } } @ Override public Object addingService ( ServiceReference reference ) { Exchange exchange = ( Exchange ) context . getService ( reference ) ; ExchangeWireEndpoint endpoint = new ExchangeWireEndpoint ( exchange , routingKey , mandatory , immediate , props ) ; Properties svcProps = new Properties ( ) ; svcProps . put ( Constants . SERVICE_PID , endpointPid ) ; svcProps . put ( WireConstants . WIREADMIN_CONSUMER_FLAVORS , new Class < ? > [ ] { CLASS_BYTE_ARRAY } ) ; LOG . debug ( "<STR_LIT>" + exchangeName + "<STR_LIT>" + endpointPid + "<STR_LIT>" ) ; return context . registerService ( Consumer . class . getName ( ) , endpoint , svcProps ) ; } @ Override public void removedService ( ServiceReference reference , Object service ) { LOG . debug ( "<STR_LIT>" + exchangeName + "<STR_LIT>" + endpointPid + "<STR_LIT>" ) ; ServiceRegistration registration = ( ServiceRegistration ) service ; registration . unregister ( ) ; context . ungetService ( reference ) ; } public String getExchangeName ( ) { return exchangeName ; } } </s>
|
<s> package com . rabbitmq . client . osgi . exchange ; import java . util . Properties ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Constants ; import org . osgi . framework . ServiceRegistration ; import org . osgi . service . cm . ManagedServiceFactory ; import com . rabbitmq . client . osgi . common . LogTracker ; public class ExchangesActivator implements BundleActivator { private LogTracker logTracker ; private ServiceRegistration connectionExchangeMsfReg ; private ServiceRegistration endpointMsfReg ; public void start ( BundleContext context ) throws Exception { Properties svcProps ; ConnectionExchangeMSF connectionExchangeMSF = new ConnectionExchangeMSF ( context ) ; svcProps = new Properties ( ) ; svcProps . put ( Constants . SERVICE_PID , "<STR_LIT>" ) ; connectionExchangeMsfReg = context . registerService ( ManagedServiceFactory . class . getName ( ) , connectionExchangeMSF , svcProps ) ; ExchangeWireEndpointMSF endpointMSF = new ExchangeWireEndpointMSF ( context ) ; svcProps = new Properties ( ) ; svcProps . put ( Constants . SERVICE_PID , "<STR_LIT>" ) ; endpointMsfReg = context . registerService ( ManagedServiceFactory . class . getName ( ) , endpointMSF , svcProps ) ; } public void stop ( BundleContext context ) throws Exception { endpointMsfReg . unregister ( ) ; connectionExchangeMsfReg . unregister ( ) ; logTracker . close ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . api ; public class PushbackException extends Exception { private static final long serialVersionUID = <NUM_LIT:1L> ; public PushbackException ( String message ) { super ( message ) ; } public PushbackException ( Throwable cause ) { super ( cause ) ; } public PushbackException ( String message , Throwable cause ) { super ( message , cause ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . api ; public interface MessageReceiver { public void receive ( Object message ) throws PushbackException , PermanentFailureException ; } </s>
|
<s> package com . rabbitmq . client . osgi . api ; public class PermanentFailureException extends Exception { private static final long serialVersionUID = <NUM_LIT:1L> ; public PermanentFailureException ( String message ) { super ( message ) ; } public PermanentFailureException ( Throwable cause ) { super ( cause ) ; } public PermanentFailureException ( String message , Throwable cause ) { super ( message , cause ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . api ; import java . io . IOException ; import com . rabbitmq . client . AMQP . BasicProperties ; public interface Exchange { void basicPublish ( String routingKey , BasicProperties props , byte [ ] body ) throws IOException ; void basicPublish ( String routingKey , boolean mandatory , boolean immediate , BasicProperties props , byte [ ] body ) throws IOException ; } </s>
|
<s> package com . rabbitmq . client . osgi . consumer ; import java . io . IOException ; import com . rabbitmq . client . Channel ; import com . rabbitmq . client . DefaultConsumer ; import com . rabbitmq . client . Envelope ; import com . rabbitmq . client . AMQP . BasicProperties ; public class ConsoleOutputConsumer extends DefaultConsumer { public ConsoleOutputConsumer ( Channel channel ) { super ( channel ) ; } @ Override public void handleDelivery ( String consumerTag , Envelope envelope , BasicProperties properties , byte [ ] body ) throws IOException { long deliveryTag = envelope . getDeliveryTag ( ) ; String message = new String ( body ) ; System . out . println ( "<STR_LIT>" ) ; System . out . println ( message ) ; getChannel ( ) . basicAck ( deliveryTag , false ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . consumer ; import java . io . IOException ; import org . osgi . framework . BundleContext ; import org . osgi . framework . ServiceReference ; import org . osgi . util . tracker . ServiceTracker ; import com . rabbitmq . client . Channel ; import com . rabbitmq . client . Connection ; public class ChannelConsumerTracker extends ServiceTracker { private final String queueName ; public ChannelConsumerTracker ( BundleContext context , String queueName ) { super ( context , Connection . class . getName ( ) , null ) ; this . queueName = queueName ; } @ Override public Object addingService ( ServiceReference reference ) { Connection conn = ( Connection ) context . getService ( reference ) ; String consumerTag = null ; Channel channel = null ; try { channel = conn . createChannel ( ) ; ConsoleOutputConsumer consumer = new ConsoleOutputConsumer ( channel ) ; channel . queueDeclare ( queueName ) ; consumerTag = channel . basicConsume ( queueName , false , consumer ) ; return new Pair < Channel , String > ( channel , consumerTag ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; return null ; } } @ Override public void removedService ( ServiceReference reference , Object service ) { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Pair < Channel , String > pair = ( Pair < Channel , String > ) service ; try { pair . getFst ( ) . basicCancel ( pair . getSnd ( ) ) ; pair . getFst ( ) . close ( ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } context . ungetService ( reference ) ; } } class Pair < A , B > { private final A fst ; private final B snd ; public Pair ( A fst , B snd ) { this . fst = fst ; this . snd = snd ; } public A getFst ( ) { return fst ; } public B getSnd ( ) { return snd ; } } </s>
|
<s> package com . rabbitmq . client . osgi . consumer ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; public class ConsumerActivator implements BundleActivator { private ChannelConsumerTracker tracker ; public void start ( BundleContext context ) throws Exception { tracker = new ChannelConsumerTracker ( context , "<STR_LIT>" ) ; tracker . open ( ) ; } public void stop ( BundleContext context ) throws Exception { tracker . close ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . connection ; import java . util . Properties ; import org . osgi . framework . BundleActivator ; import org . osgi . framework . BundleContext ; import org . osgi . framework . Constants ; import org . osgi . service . cm . ManagedServiceFactory ; public class ConnectionServiceFactoryActivator implements BundleActivator { public void start ( BundleContext context ) throws Exception { Properties props = new Properties ( ) ; props . put ( Constants . SERVICE_PID , "<STR_LIT>" ) ; context . registerService ( ManagedServiceFactory . class . getName ( ) , new ConnectionServiceFactory ( context ) , props ) ; } public void stop ( BundleContext context ) throws Exception { } } </s>
|
<s> package com . rabbitmq . client . osgi . connection ; import java . io . IOException ; import java . util . Dictionary ; import java . util . HashMap ; import java . util . Map ; import java . util . Properties ; import org . osgi . framework . BundleContext ; import org . osgi . framework . ServiceRegistration ; import org . osgi . service . cm . ConfigurationException ; import org . osgi . service . cm . ManagedServiceFactory ; import com . rabbitmq . client . Connection ; import com . rabbitmq . client . ConnectionFactory ; import com . rabbitmq . client . ConnectionParameters ; import com . rabbitmq . client . osgi . common . CMPropertyAccessor ; import com . rabbitmq . client . osgi . common . Pair ; import com . rabbitmq . client . osgi . common . ServiceProperties ; public class ConnectionServiceFactory implements ManagedServiceFactory { private static final String PROP_NAME = "<STR_LIT:name>" ; private static final String PROP_HOST = "<STR_LIT>" ; private static final String PROP_PORT = "<STR_LIT>" ; private static final String PROP_USERNAME = "<STR_LIT:username>" ; private static final String PROP_PASSWORD = "<STR_LIT:password>" ; private static final String PROP_VIRTUAL_HOST = "<STR_LIT>" ; private static final String PROP_REQ_HEARTBEAT = "<STR_LIT>" ; private final Map < String , Pair < Connection , ServiceRegistration > > map = new HashMap < String , Pair < Connection , ServiceRegistration > > ( ) ; private final BundleContext context ; public ConnectionServiceFactory ( BundleContext context ) { this . context = context ; } public void deleted ( String pid ) { Pair < Connection , ServiceRegistration > pair = null ; synchronized ( map ) { pair = map . remove ( pid ) ; } if ( pair != null ) { pair . getSnd ( ) . unregister ( ) ; try { pair . getFst ( ) . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } public String getName ( ) { return "<STR_LIT>" ; } public void updated ( String pid , @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Dictionary props ) throws ConfigurationException { CMPropertyAccessor accessor = new CMPropertyAccessor ( props ) ; String host = accessor . getMandatoryString ( PROP_HOST ) ; Integer portObj = accessor . getInteger ( PROP_PORT ) ; ConnectionParameters params = new ConnectionParameters ( ) ; params . setUsername ( accessor . getMandatoryString ( PROP_USERNAME ) ) ; params . setPassword ( accessor . getMandatoryString ( PROP_PASSWORD ) ) ; params . setVirtualHost ( accessor . getMandatoryString ( PROP_VIRTUAL_HOST ) ) ; Integer reqHeartbeat = accessor . getInteger ( PROP_REQ_HEARTBEAT ) ; if ( reqHeartbeat != null ) { params . setRequestedHeartbeat ( reqHeartbeat . intValue ( ) ) ; } String name = accessor . getString ( PROP_NAME ) ; if ( name == null ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( params . getUserName ( ) ) . append ( params . getUserName ( ) ) . append ( '<CHAR_LIT>' ) . append ( host ) ; if ( portObj != null ) { buf . append ( '<CHAR_LIT::>' ) . append ( portObj . intValue ( ) ) ; } name = buf . toString ( ) ; } Pair < Connection , ServiceRegistration > connPair = null ; try { ConnectionFactory connFactory = new ConnectionFactory ( params ) ; Connection conn = connFactory . newConnection ( host , portObj == null ? - <NUM_LIT:1> : portObj . intValue ( ) ) ; Properties svcProps = new Properties ( ) ; svcProps . put ( ServiceProperties . CONNECTION_NAME , name ) ; svcProps . put ( ServiceProperties . CONNECTION_HOST , host ) ; ServiceRegistration reg = context . registerService ( Connection . class . getName ( ) , conn , svcProps ) ; connPair = new Pair < Connection , ServiceRegistration > ( conn , reg ) ; } catch ( IOException e ) { throw new ConfigurationException ( null , "<STR_LIT>" , e ) ; } Pair < Connection , ServiceRegistration > old = null ; synchronized ( map ) { old = map . put ( pid , connPair ) ; } if ( old != null ) { old . getSnd ( ) . unregister ( ) ; try { old . getFst ( ) . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } </s>
|
<s> package com . rabbitmq . client . osgi . common ; public final class ServiceProperties { public static final String CONNECTION_NAME = "<STR_LIT>" ; public static final String CONNECTION_HOST = "<STR_LIT>" ; public static final String EXCHANGE_NAME = "<STR_LIT>" ; public static final String EXCHANGE_CONNECTION = "<STR_LIT>" ; public static final String EXCHANGE_TYPE = "<STR_LIT>" ; public static final String EXCHANGE_PASSIVE = "<STR_LIT>" ; public static final String EXCHANGE_DURABLE = "<STR_LIT>" ; public static final String EXCHANGE_AUTODELETE = "<STR_LIT>" ; public static final String PUBLISH_ROUTING_KEY = "<STR_LIT>" ; public static final String PUBLISH_MANDATORY = "<STR_LIT>" ; public static final String PUBLISH_IMMEDIATE = "<STR_LIT>" ; public static final String ENDPOINT_SERVICE_PID = "<STR_LIT>" ; private ServiceProperties ( ) { } } </s>
|
<s> package com . rabbitmq . client . osgi . common ; public class Pair < A , B > { private final A fst ; private final B snd ; public Pair ( A fst , B snd ) { this . fst = fst ; this . snd = snd ; } public A getFst ( ) { return fst ; } public B getSnd ( ) { return snd ; } @ Override public int hashCode ( ) { final int prime = <NUM_LIT:31> ; int result = <NUM_LIT:1> ; result = prime * result + ( ( fst == null ) ? <NUM_LIT:0> : fst . hashCode ( ) ) ; result = prime * result + ( ( snd == null ) ? <NUM_LIT:0> : snd . hashCode ( ) ) ; return result ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; Pair < ? , ? > other = ( Pair < ? , ? > ) obj ; if ( fst == null ) { if ( other . fst != null ) return false ; } else if ( ! fst . equals ( other . fst ) ) return false ; if ( snd == null ) { if ( other . snd != null ) return false ; } else if ( ! snd . equals ( other . snd ) ) return false ; return true ; } @ Override public String toString ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '<CHAR_LIT:(>' ) . append ( fst ) . append ( '<CHAR_LIT:U+002C>' ) . append ( snd ) . append ( '<CHAR_LIT:)>' ) ; return buf . toString ( ) ; } } </s>
|
<s> package com . rabbitmq . client . osgi . common ; import java . io . PrintStream ; import org . osgi . framework . BundleContext ; import org . osgi . framework . ServiceReference ; import org . osgi . service . log . LogService ; import org . osgi . util . tracker . ServiceTracker ; public class LogTracker extends ServiceTracker implements LogService { public LogTracker ( BundleContext context ) { super ( context , LogService . class . getName ( ) , null ) ; } public void log ( int level , String message ) { log ( null , level , message , null ) ; } public void log ( int level , String message , Throwable exception ) { log ( null , level , message , exception ) ; } public void log ( ServiceReference sr , int level , String message ) { log ( sr , level , message , null ) ; } public void log ( ServiceReference sr , int level , String message , Throwable exception ) { LogService log = ( LogService ) getService ( ) ; if ( log != null ) { log . log ( sr , level , message , exception ) ; } else { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( getLvlString ( level ) ) . append ( "<STR_LIT::U+0020>" ) . append ( message ) ; if ( sr != null ) { buffer . append ( "<STR_LIT>" ) . append ( sr ) . append ( "<STR_LIT:]>" ) ; } if ( exception != null ) { buffer . append ( "<STR_LIT>" ) . append ( exception . getMessage ( ) ) . append ( "<STR_LIT:U+0020(>" ) . append ( exception . getClass ( ) . getName ( ) ) . append ( "<STR_LIT:)>" ) ; } PrintStream ps = ( level == LogService . LOG_ERROR ) ? System . err : System . out ; ps . println ( buffer . toString ( ) ) ; if ( exception != null ) { exception . printStackTrace ( ps ) ; } } } private static String getLvlString ( int level ) { String result ; switch ( level ) { case LogService . LOG_DEBUG : result = "<STR_LIT>" ; break ; case LogService . LOG_INFO : result = "<STR_LIT>" ; break ; case LogService . LOG_WARNING : result = "<STR_LIT>" ; break ; case LogService . LOG_ERROR : result = "<STR_LIT>" ; break ; default : result = "<STR_LIT>" ; } return result ; } } </s>
|
<s> package com . rabbitmq . client . osgi . common ; import java . util . Dictionary ; import org . osgi . service . cm . ConfigurationException ; public class CMPropertyAccessor { @ SuppressWarnings ( "<STR_LIT:unchecked>" ) private final Dictionary props ; public CMPropertyAccessor ( @ SuppressWarnings ( "<STR_LIT:unchecked>" ) Dictionary props ) { this . props = props ; } public String getString ( String name ) throws ConfigurationException { Object result = props . get ( name ) ; if ( result != null && ! ( result instanceof String ) ) { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } return ( String ) result ; } public String getMandatoryString ( String name ) throws ConfigurationException { String result = getString ( name ) ; if ( result == null ) { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } return result ; } public Integer getInteger ( String name ) throws ConfigurationException { Integer result = null ; Object obj = props . get ( name ) ; if ( obj != null ) { if ( obj instanceof String ) { try { result = new Integer ( ( String ) obj ) ; } catch ( NumberFormatException e ) { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } } else if ( obj instanceof Integer ) { result = ( Integer ) obj ; } else { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } } return result ; } public Integer getMandatoryInteger ( String name ) throws ConfigurationException { Integer result = getInteger ( name ) ; if ( result == null ) { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } return result ; } public Boolean getBoolean ( String name ) throws ConfigurationException { Boolean result = null ; Object obj = props . get ( name ) ; if ( obj != null ) { if ( obj instanceof String ) { result = Boolean . parseBoolean ( ( String ) obj ) ; } else if ( obj instanceof Boolean ) { result = ( Boolean ) obj ; } else { throw new ConfigurationException ( name , "<STR_LIT>" ) ; } } return result ; } public boolean getBoolean ( String name , boolean defaultValue ) throws ConfigurationException { Boolean b = getBoolean ( name ) ; return ( b != null ) ? b . booleanValue ( ) : defaultValue ; } } </s>
|
<s> package edu . uestc . activities ; public final class R { public static final class anim { public static final int fadein = <NUM_LIT> ; public static final int fadeout = <NUM_LIT> ; public static final int slideleft = <NUM_LIT> ; public static final int slideright = <NUM_LIT> ; } public static final class attr { } public static final class drawable { public static final int bk_menu_img_tst_big = <NUM_LIT> ; public static final int bk_scene_img_tst_big = <NUM_LIT> ; public static final int bk_splash_img_tst_big = <NUM_LIT> ; public static final int ic_launcher = <NUM_LIT> ; public static final int selector_exit_btn = <NUM_LIT> ; public static final int selector_start_btn = <NUM_LIT> ; } public static final class id { public static final int btn_back = <NUM_LIT> ; public static final int btn_exit = <NUM_LIT> ; public static final int btn_start = <NUM_LIT> ; public static final int btn_sure = <NUM_LIT> ; public static final int creditsText = <NUM_LIT> ; public static final int login_edit = <NUM_LIT> ; public static final int menu_surfaceview = <NUM_LIT> ; public static final int scenebtn1 = <NUM_LIT> ; public static final int scenebtn2 = <NUM_LIT> ; public static final int scenebtn3 = <NUM_LIT> ; public static final int splash = <NUM_LIT> ; } public static final class layout { public static final int logindialog = <NUM_LIT> ; public static final int menu = <NUM_LIT> ; public static final int sceneselect = <NUM_LIT> ; public static final int splash = <NUM_LIT> ; } public static final class raw { public static final int bgm_scene_select_tst = <NUM_LIT> ; public static final int bgm_start_tst = <NUM_LIT> ; } public static final class string { public static final int app_name = <NUM_LIT> ; public static final int credits = <NUM_LIT> ; public static final int exit_game = <NUM_LIT> ; public static final int hello = <NUM_LIT> ; public static final int logintext = <NUM_LIT> ; public static final int menuactivity = <NUM_LIT> ; public static final int start_game = <NUM_LIT> ; } } </s>
|
<s> package edu . uestc . activities ; import edu . uestc . ikaros . engine . IkarosEngine ; import edu . uestc . services . NewMusicService ; import edu . uestc . utl . ActivityUtl ; import android . app . Activity ; import android . content . Intent ; import android . content . res . Configuration ; import android . os . Bundle ; import android . os . Handler ; import android . util . Log ; import android . view . View ; import android . widget . Button ; public class LoginActivity extends Activity { private static final String LOGIN_TAG = "<STR_LIT>" ; private Button btnBack ; private Button btnLogin ; private IkarosEngine ikarosEngine ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; ActivityUtl . setNoTitle ( this ) ; setContentView ( R . layout . logindialog ) ; ikarosEngine = IkarosEngine . getInstance ( ) ; btnBack = ( Button ) findViewById ( R . id . btn_back ) ; btnLogin = ( Button ) findViewById ( R . id . btn_sure ) ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { try { super . onConfigurationChanged ( newConfig ) ; if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_LANDSCAPE ) { Log . v ( LOGIN_TAG , "<STR_LIT>" ) ; } else if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_PORTRAIT ) { Log . v ( LOGIN_TAG , "<STR_LIT>" ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } public void onLoginButton ( View view ) { Log . v ( LOGIN_TAG , "<STR_LIT>" ) ; ikarosEngine . stopAndStartNewMusic ( NewMusicService . MUSIC_TYPE_GAME ) ; Intent intent = new Intent ( this , SceneSelectActivity . class ) ; startActivity ( intent ) ; this . finish ( ) ; } public void onBackButton ( View view ) { Log . v ( LOGIN_TAG , "<STR_LIT>" ) ; this . finish ( ) ; } } </s>
|
<s> package edu . uestc . activities ; import android . app . Activity ; import android . content . res . Configuration ; import android . os . Bundle ; import android . os . Handler ; import android . util . Log ; import android . view . View ; import android . widget . Button ; import edu . uestc . ikaros . engine . IkarosEngine ; import edu . uestc . services . NewMusicService ; import edu . uestc . utl . ActivityUtl ; public class MenuActivity extends Activity { private final static String MENUACTIVITY_TAG = "<STR_LIT>" ; private Button startBtn ; private Button exitBtn ; private IkarosEngine engine ; { engine = IkarosEngine . getInstance ( ) ; } @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; ActivityUtl . setNoTitle ( this ) ; setContentView ( R . layout . menu ) ; IkarosEngine . context = getApplicationContext ( ) ; engine . setupMusicService ( ) ; startBtn = ( Button ) findViewById ( R . id . btn_start ) ; exitBtn = ( Button ) findViewById ( R . id . btn_exit ) ; startBtn . getBackground ( ) . setAlpha ( IkarosEngine . MENU_BUTTON_ALPHA ) ; startBtn . setHapticFeedbackEnabled ( IkarosEngine . HAPTIC_BUTTON_FEEDBACK ) ; exitBtn . getBackground ( ) . setAlpha ( IkarosEngine . MENU_BUTTON_ALPHA ) ; exitBtn . setHapticFeedbackEnabled ( IkarosEngine . HAPTIC_BUTTON_FEEDBACK ) ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { try { super . onConfigurationChanged ( newConfig ) ; if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_LANDSCAPE ) { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; } else if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_PORTRAIT ) { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } public void onStartButton ( View view ) { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; ActivityUtl . startActivityNoAnime ( new Handler ( ) , this , LoginActivity . class , false , <NUM_LIT:100> ) ; } public void onExitButton ( View view ) { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; boolean clean = false ; clean = engine . onExit ( view ) ; if ( clean ) { int pid = android . os . Process . myPid ( ) ; android . os . Process . killProcess ( pid ) ; } else { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; } } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; boolean clean = false ; clean = engine . onExit ( null ) ; if ( clean ) { int pid = android . os . Process . myPid ( ) ; android . os . Process . killProcess ( pid ) ; } else { Log . v ( MENUACTIVITY_TAG , "<STR_LIT>" ) ; } } } </s>
|
<s> package edu . uestc . activities ; import android . app . Activity ; import android . app . ActivityManager ; import android . content . Context ; import android . content . res . Configuration ; import android . os . Bundle ; import android . os . Handler ; import android . util . Log ; import edu . uestc . ikaros . engine . IkarosEngine ; import edu . uestc . utl . ActivityUtl ; public class MainActivity extends Activity { private final static String MAINACTIVITY_TAG = "<STR_LIT>" ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; ActivityUtl . setNoTitle ( this ) ; setContentView ( R . layout . splash ) ; ActivityUtl . startActivityWithFadeEffect ( new Handler ( ) , this , MenuActivity . class , true , IkarosEngine . GAME_THREAD_DELAY ) ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { try { super . onConfigurationChanged ( newConfig ) ; if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_LANDSCAPE ) { Log . v ( MAINACTIVITY_TAG , "<STR_LIT>" ) ; } else if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_PORTRAIT ) { Log . v ( MAINACTIVITY_TAG , "<STR_LIT>" ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } @ Override protected void onDestroy ( ) { super . onDestroy ( ) ; Log . v ( MAINACTIVITY_TAG , "<STR_LIT>" ) ; } @ Deprecated private void forceStop ( ) { ActivityManager manager = ( ActivityManager ) getSystemService ( Context . ACTIVITY_SERVICE ) ; manager . restartPackage ( getPackageName ( ) ) ; } } </s>
|
<s> package edu . uestc . activities ; import edu . uestc . ikaros . engine . IkarosEngine ; import edu . uestc . services . NewMusicService ; import edu . uestc . utl . ActivityUtl ; import android . app . Activity ; import android . content . res . Configuration ; import android . os . Bundle ; import android . util . Log ; import android . view . View ; import android . view . View . OnClickListener ; import android . widget . Button ; public class SceneSelectActivity extends Activity implements OnClickListener { private static final String SCENESELECT_TAG = "<STR_LIT>" ; private IkarosEngine ikarosEngine ; private Button sceneButton1 ; private Button sceneButton2 ; private Button sceneButton3 ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; ActivityUtl . setNoTitle ( this ) ; setContentView ( R . layout . sceneselect ) ; sceneButton1 = ( Button ) findViewById ( R . id . scenebtn1 ) ; sceneButton1 . setOnClickListener ( this ) ; sceneButton2 = ( Button ) findViewById ( R . id . scenebtn2 ) ; sceneButton2 . setOnClickListener ( this ) ; sceneButton3 = ( Button ) findViewById ( R . id . scenebtn3 ) ; sceneButton3 . setOnClickListener ( this ) ; ikarosEngine = IkarosEngine . getInstance ( ) ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { try { super . onConfigurationChanged ( newConfig ) ; if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_LANDSCAPE ) { Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; } else if ( this . getResources ( ) . getConfiguration ( ) . orientation == Configuration . ORIENTATION_PORTRAIT ) { Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } @ Override protected void onDestroy ( ) { Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; super . onDestroy ( ) ; ikarosEngine . stopMusic ( ) ; ikarosEngine . startMusic ( NewMusicService . MUSIC_TYPE_MENU ) ; } @ Override public void onClick ( View v ) { switch ( v . getId ( ) ) { case R . id . scenebtn1 : Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; break ; case R . id . scenebtn2 : Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; break ; case R . id . scenebtn3 : Log . v ( SCENESELECT_TAG , "<STR_LIT>" ) ; break ; default : break ; } } } </s>
|
<s> package edu . uestc . services ; import edu . uestc . activities . R ; import android . app . Service ; import android . content . BroadcastReceiver ; import android . content . Context ; import android . content . Intent ; import android . content . IntentFilter ; import android . media . MediaPlayer ; import android . os . Binder ; import android . os . IBinder ; import android . util . Log ; public class NewMusicService extends Service { public static final String MUSICSERVICE_TAG = "<STR_LIT>" ; public static final String MUSICSTART = "<STR_LIT>" ; public static final String MUSICPAUSE = "<STR_LIT>" ; public static final String MUSICSTOP = "<STR_LIT>" ; public static final String MUSICCONTINUAL = "<STR_LIT>" ; public static final String MUSICRELEASE = "<STR_LIT>" ; public static final String SETMUSICTYPE = "<STR_LIT>" ; public static final int MUSIC_TYPE_MENU = <NUM_LIT:11> ; public static final int MUSIC_TYPE_GAME = <NUM_LIT:12> ; public static final int MUSIC_TYPE_OPTIONVIEW = <NUM_LIT> ; private int musicType = MUSIC_TYPE_MENU ; private MediaPlayer mediaPlayer ; private MusicBroadcasReceiver receiver = new MusicBroadcasReceiver ( ) ; private class MusicBroadcasReceiver extends BroadcastReceiver { @ Override public void onReceive ( Context con , Intent intent ) { Log . v ( MUSICSERVICE_TAG , intent . getAction ( ) . equals ( MUSICSTART ) + "<STR_LIT>" ) ; if ( intent . getAction ( ) . equals ( MUSICSTART ) ) { int type = intent . getIntExtra ( SETMUSICTYPE , MUSIC_TYPE_MENU ) ; setMusicType ( type ) ; startMusic ( ) ; } else if ( intent . getAction ( ) . equals ( MUSICPAUSE ) ) { pauseMusic ( ) ; } else if ( intent . getAction ( ) . equals ( MUSICSTOP ) ) { stopMusic ( ) ; } else if ( intent . getAction ( ) . equals ( MUSICCONTINUAL ) ) { continualMusic ( ) ; } else if ( intent . getAction ( ) . equals ( MUSICRELEASE ) ) { releaseMusic ( ) ; } else { } } } private class MusicServiceBinder extends Binder { @ SuppressWarnings ( "<STR_LIT:unused>" ) NewMusicService getService ( ) { return NewMusicService . this ; } } @ Override public void onCreate ( ) { Log . v ( MUSICSERVICE_TAG , "<STR_LIT>" ) ; super . onCreate ( ) ; IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( MUSICSTART ) ; filter . addAction ( MUSICPAUSE ) ; filter . addAction ( MUSICSTOP ) ; filter . addAction ( MUSICCONTINUAL ) ; filter . addAction ( MUSICRELEASE ) ; registerReceiver ( receiver , filter ) ; } @ Override public int onStartCommand ( Intent intent , int flags , int startId ) { Log . v ( MUSICSERVICE_TAG , "<STR_LIT>" ) ; return super . onStartCommand ( intent , flags , startId ) ; } @ Override public void onDestroy ( ) { receiver = null ; mediaPlayer = null ; super . onDestroy ( ) ; } @ Override public IBinder onBind ( Intent intent ) { return new MusicServiceBinder ( ) ; } public void startMusic ( ) { if ( mediaPlayer != null ) { mediaPlayer . reset ( ) ; } switch ( this . musicType ) { case MUSIC_TYPE_MENU : mediaPlayer = MediaPlayer . create ( getApplicationContext ( ) , R . raw . bgm_start_tst ) ; break ; case MUSIC_TYPE_GAME : mediaPlayer = MediaPlayer . create ( getApplicationContext ( ) , R . raw . bgm_scene_select_tst ) ; break ; case MUSIC_TYPE_OPTIONVIEW : break ; default : Log . v ( MUSICSERVICE_TAG , "<STR_LIT>" ) ; } mediaPlayer . setLooping ( true ) ; mediaPlayer . start ( ) ; } public void pauseMusic ( ) { if ( mediaPlayer . isPlaying ( ) ) { mediaPlayer . pause ( ) ; } } public void stopMusic ( ) { mediaPlayer . reset ( ) ; } public void continualMusic ( ) { if ( ! mediaPlayer . isPlaying ( ) ) { mediaPlayer . start ( ) ; } } public void releaseMusic ( ) { mediaPlayer . release ( ) ; mediaPlayer = null ; unregisterReceiver ( receiver ) ; stopSelf ( ) ; } public int getMusicType ( ) { return musicType ; } public void setMusicType ( int musicType ) { this . musicType = musicType ; } } </s>
|
<s> package edu . uestc . layout ; import android . content . Context ; import android . util . AttributeSet ; import android . view . MotionEvent ; import android . view . VelocityTracker ; import android . view . View ; import android . view . ViewConfiguration ; import android . view . ViewGroup ; import android . widget . Scroller ; public class ScrollLayout extends ViewGroup { private static final String TAG = "<STR_LIT>" ; private Scroller mScroller ; private VelocityTracker mVelocityTracker ; private int mCurScreen ; private int mDefaultScreen = <NUM_LIT:0> ; private static final int TOUCH_STATE_REST = <NUM_LIT:0> ; private static final int TOUCH_STATE_SCROLLING = <NUM_LIT:1> ; private static final int SNAP_VELOCITY = <NUM_LIT> ; private int mTouchState = TOUCH_STATE_REST ; private int mTouchSlop ; private float mLastMotionX ; private float mLastMotionY ; public ScrollLayout ( Context context , AttributeSet attrs ) { this ( context , attrs , <NUM_LIT:0> ) ; } public ScrollLayout ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; mScroller = new Scroller ( context ) ; mCurScreen = mDefaultScreen ; mTouchSlop = ViewConfiguration . get ( getContext ( ) ) . getScaledTouchSlop ( ) ; } @ Override protected void onLayout ( boolean changed , int l , int t , int r , int b ) { if ( changed ) { int childLeft = <NUM_LIT:0> ; final int childCount = getChildCount ( ) ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View childView = getChildAt ( i ) ; if ( childView . getVisibility ( ) != View . GONE ) { final int childWidth = childView . getMeasuredWidth ( ) ; childView . layout ( childLeft , <NUM_LIT:0> , childLeft + childWidth , childView . getMeasuredHeight ( ) ) ; childLeft += childWidth ; } } } } @ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { super . onMeasure ( widthMeasureSpec , heightMeasureSpec ) ; final int width = MeasureSpec . getSize ( widthMeasureSpec ) ; final int widthMode = MeasureSpec . getMode ( widthMeasureSpec ) ; if ( widthMode != MeasureSpec . EXACTLY ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } final int heightMode = MeasureSpec . getMode ( heightMeasureSpec ) ; if ( heightMode != MeasureSpec . EXACTLY ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } final int count = getChildCount ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { getChildAt ( i ) . measure ( widthMeasureSpec , heightMeasureSpec ) ; } scrollTo ( mCurScreen * width , <NUM_LIT:0> ) ; } public void snapToDestination ( ) { final int screenWidth = getWidth ( ) ; final int destScreen = ( getScrollX ( ) + screenWidth / <NUM_LIT:2> ) / screenWidth ; snapToScreen ( destScreen ) ; } public void snapToScreen ( int whichScreen ) { whichScreen = Math . max ( <NUM_LIT:0> , Math . min ( whichScreen , getChildCount ( ) - <NUM_LIT:1> ) ) ; if ( getScrollX ( ) != ( whichScreen * getWidth ( ) ) ) { final int delta = whichScreen * getWidth ( ) - getScrollX ( ) ; mScroller . startScroll ( getScrollX ( ) , <NUM_LIT:0> , delta , <NUM_LIT:0> , Math . abs ( delta ) * <NUM_LIT:2> ) ; mCurScreen = whichScreen ; invalidate ( ) ; } } public void setToScreen ( int whichScreen ) { whichScreen = Math . max ( <NUM_LIT:0> , Math . min ( whichScreen , getChildCount ( ) - <NUM_LIT:1> ) ) ; mCurScreen = whichScreen ; scrollTo ( whichScreen * getWidth ( ) , <NUM_LIT:0> ) ; } public int getCurScreen ( ) { return mCurScreen ; } @ Override public void computeScroll ( ) { if ( mScroller . computeScrollOffset ( ) ) { scrollTo ( mScroller . getCurrX ( ) , mScroller . getCurrY ( ) ) ; postInvalidate ( ) ; } } @ Override public boolean onTouchEvent ( MotionEvent event ) { if ( mVelocityTracker == null ) { mVelocityTracker = VelocityTracker . obtain ( ) ; } mVelocityTracker . addMovement ( event ) ; final int action = event . getAction ( ) ; final float x = event . getX ( ) ; final float y = event . getY ( ) ; switch ( action ) { case MotionEvent . ACTION_DOWN : if ( ! mScroller . isFinished ( ) ) { mScroller . abortAnimation ( ) ; } mLastMotionX = x ; break ; case MotionEvent . ACTION_MOVE : int deltaX = ( int ) ( mLastMotionX - x ) ; mLastMotionX = x ; scrollBy ( deltaX , <NUM_LIT:0> ) ; break ; case MotionEvent . ACTION_UP : final VelocityTracker velocityTracker = mVelocityTracker ; velocityTracker . computeCurrentVelocity ( <NUM_LIT:1000> ) ; int velocityX = ( int ) velocityTracker . getXVelocity ( ) ; if ( velocityX > SNAP_VELOCITY && mCurScreen > <NUM_LIT:0> ) { snapToScreen ( mCurScreen - <NUM_LIT:1> ) ; } else if ( velocityX < - SNAP_VELOCITY && mCurScreen < getChildCount ( ) - <NUM_LIT:1> ) { snapToScreen ( mCurScreen + <NUM_LIT:1> ) ; } else { snapToDestination ( ) ; } if ( mVelocityTracker != null ) { mVelocityTracker . recycle ( ) ; mVelocityTracker = null ; } mTouchState = TOUCH_STATE_REST ; break ; case MotionEvent . ACTION_CANCEL : mTouchState = TOUCH_STATE_REST ; break ; } return true ; } @ Override public boolean onInterceptTouchEvent ( MotionEvent ev ) { final int action = ev . getAction ( ) ; if ( ( action == MotionEvent . ACTION_MOVE ) && ( mTouchState != TOUCH_STATE_REST ) ) { return true ; } final float x = ev . getX ( ) ; final float y = ev . getY ( ) ; switch ( action ) { case MotionEvent . ACTION_MOVE : final int xDiff = ( int ) Math . abs ( mLastMotionX - x ) ; if ( xDiff > mTouchSlop ) { mTouchState = TOUCH_STATE_SCROLLING ; } break ; case MotionEvent . ACTION_DOWN : mLastMotionX = x ; mLastMotionY = y ; mTouchState = mScroller . isFinished ( ) ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING ; break ; case MotionEvent . ACTION_CANCEL : case MotionEvent . ACTION_UP : mTouchState = TOUCH_STATE_REST ; break ; } return mTouchState != TOUCH_STATE_REST ; } } </s>
|
<s> package edu . uestc . utl ; import android . graphics . Canvas ; import android . graphics . Paint ; public class SurfaceViewUtl { public static void refreshCanvas ( Canvas canvas , Paint paint , int width , int height ) { canvas . drawRect ( <NUM_LIT:0> , <NUM_LIT:0> , width , height , paint ) ; } } </s>
|
<s> package edu . uestc . utl ; import android . app . Activity ; import android . content . Intent ; import android . os . Handler ; import android . view . Window ; import android . view . WindowManager ; import edu . uestc . activities . R ; public class ActivityUtl { public static void setNoTitle ( Activity activity ) { activity . requestWindowFeature ( Window . FEATURE_NO_TITLE ) ; activity . getWindow ( ) . setFlags ( WindowManager . LayoutParams . FLAG_FULLSCREEN , WindowManager . LayoutParams . FLAG_FULLSCREEN ) ; } public static void startActivityWithFadeEffect ( Handler handler , final Activity thisActivity , @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) final Class toActivityClass , final boolean exit , int timeout ) { handler . postDelayed ( new Thread ( ) { @ Override public void run ( ) { Intent intent = new Intent ( thisActivity , toActivityClass ) ; thisActivity . startActivity ( intent ) ; if ( exit ) { thisActivity . finish ( ) ; } thisActivity . overridePendingTransition ( R . anim . fadein , R . anim . fadeout ) ; } } , timeout ) ; } public static void startActivityWithMoving ( Handler handler , final Activity thisActivity , @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) final Class toActivityClass , final boolean exit , int timeout ) { handler . postDelayed ( new Thread ( ) { @ Override public void run ( ) { Intent intent = new Intent ( thisActivity , toActivityClass ) ; thisActivity . startActivity ( intent ) ; if ( exit ) { thisActivity . finish ( ) ; } thisActivity . overridePendingTransition ( R . anim . slideleft , R . anim . slideright ) ; } } , timeout ) ; } public static void startActivityNoAnime ( Handler handler , final Activity thisActivity , @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) final Class toActivityClass , final boolean exit , int timeout ) { handler . postDelayed ( new Thread ( ) { @ Override public void run ( ) { Intent intent = new Intent ( thisActivity , toActivityClass ) ; thisActivity . startActivity ( intent ) ; if ( exit ) { thisActivity . finish ( ) ; } } } , timeout ) ; } } </s>
|
<s> package edu . uestc . surfaceview ; import java . util . concurrent . TimeUnit ; import edu . uestc . utl . SurfaceViewUtl ; import android . content . Context ; import android . graphics . Canvas ; import android . graphics . Color ; import android . graphics . Paint ; import android . util . AttributeSet ; import android . view . SurfaceHolder ; import android . view . SurfaceView ; import android . view . SurfaceHolder . Callback ; public class MenuSurfaceView extends SurfaceView implements Callback , Runnable { private static final String MENUSURFACEVIEW_TAG = "<STR_LIT>" ; protected Canvas canvas ; protected SurfaceHolder surfaceHolder ; protected Thread mainThread ; protected Paint paint ; protected int rate ; protected boolean threadFlag ; protected int screenHeight = <NUM_LIT:0> ; protected int screenWidth = <NUM_LIT:0> ; private int frame = <NUM_LIT:0> ; private Paint paint2 ; private int [ ] colors = { Color . BLACK , Color . BLUE , Color . CYAN , Color . DKGRAY , Color . GRAY , Color . GREEN , Color . LTGRAY , Color . MAGENTA , Color . RED , Color . TRANSPARENT , Color . WHITE , Color . YELLOW } ; public MenuSurfaceView ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; surfaceHolder = this . getHolder ( ) ; surfaceHolder . addCallback ( this ) ; paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; paint2 = new Paint ( ) ; paint2 . setAntiAlias ( true ) ; paint2 . setColor ( colors [ <NUM_LIT:0> ] ) ; } @ Override public void surfaceChanged ( SurfaceHolder holder , int format , int width , int height ) { } @ Override public void surfaceCreated ( SurfaceHolder holder ) { mainThread = new Thread ( this ) ; threadFlag = true ; screenHeight = this . getHeight ( ) ; screenWidth = this . getWidth ( ) ; mainThread . start ( ) ; } @ Override public void surfaceDestroyed ( SurfaceHolder holder ) { threadFlag = false ; } @ Override public void run ( ) { while ( threadFlag ) { paint2 . setColor ( colors [ frame ] ) ; draw ( ) ; frame ++ ; if ( frame == colors . length - <NUM_LIT:1> ) { frame = <NUM_LIT:0> ; } try { TimeUnit . SECONDS . sleep ( <NUM_LIT:1> ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } protected void draw ( ) { try { canvas = surfaceHolder . lockCanvas ( ) ; SurfaceViewUtl . refreshCanvas ( canvas , paint , screenWidth , screenHeight ) ; canvas . drawRect ( <NUM_LIT:0> , <NUM_LIT:0> , screenWidth , screenHeight , paint2 ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( canvas != null ) { surfaceHolder . unlockCanvasAndPost ( canvas ) ; } } } } </s>
|
<s> package edu . uestc . surfaceview ; import java . util . concurrent . TimeUnit ; import edu . uestc . activities . R ; import edu . uestc . utl . SurfaceViewUtl ; import android . content . Context ; import android . graphics . Bitmap ; import android . graphics . BitmapFactory ; import android . graphics . Canvas ; import android . graphics . Paint ; import android . util . AttributeSet ; import android . view . SurfaceHolder ; import android . view . SurfaceView ; import android . view . SurfaceHolder . Callback ; public class SceneSelectSurfaceView extends SurfaceView implements Callback , Runnable { private SurfaceHolder surfaceHolder ; private Thread mainThread ; private Paint paint ; private Canvas canvas ; private boolean threadFlag = false ; private Bitmap backgroundBitmap ; public int screenWidth ; public int screenHeight ; public SceneSelectSurfaceView ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; surfaceHolder = this . getHolder ( ) ; surfaceHolder . addCallback ( this ) ; paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; init_bitmap ( ) ; } @ Override public void surfaceChanged ( SurfaceHolder holder , int format , int width , int height ) { } @ Override public void surfaceCreated ( SurfaceHolder holder ) { screenWidth = this . getWidth ( ) ; screenHeight = this . getHeight ( ) ; threadFlag = true ; mainThread = new Thread ( this ) ; mainThread . start ( ) ; } @ Override public void surfaceDestroyed ( SurfaceHolder holder ) { threadFlag = false ; } @ Override public void run ( ) { while ( threadFlag ) { draw ( ) ; try { TimeUnit . MILLISECONDS . sleep ( <NUM_LIT> ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } private void init_bitmap ( ) { backgroundBitmap = BitmapFactory . decodeResource ( getResources ( ) , R . drawable . bk_scene_img_tst_big ) ; } private void draw ( ) { try { canvas = surfaceHolder . lockCanvas ( ) ; SurfaceViewUtl . refreshCanvas ( canvas , paint , screenWidth , screenHeight ) ; canvas . drawBitmap ( backgroundBitmap , screenWidth / <NUM_LIT:2> - backgroundBitmap . getWidth ( ) / <NUM_LIT:2> , <NUM_LIT:0> , paint ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( canvas != null ) { surfaceHolder . unlockCanvasAndPost ( canvas ) ; } } } } </s>
|
<s> package edu . uestc . ikaros . engine ; import edu . uestc . services . NewMusicService ; import android . content . ComponentName ; import android . content . Context ; import android . content . Intent ; import android . content . ServiceConnection ; import android . os . IBinder ; import android . util . Log ; import android . view . View ; public class IkarosEngine { public static final String ENGINE_TAG = "<STR_LIT>" ; public static final int GAME_THREAD_DELAY = <NUM_LIT> ; public static final int MENU_BUTTON_ALPHA = <NUM_LIT:0> ; public static final boolean HAPTIC_BUTTON_FEEDBACK = true ; public static Context context ; private static final IkarosEngine singleton = new IkarosEngine ( ) ; private IkarosEngine ( ) { } public static IkarosEngine getInstance ( ) { return singleton ; } public boolean onExit ( View view ) { try { stopMusic ( ) ; releaseMusic ( ) ; Intent intent = new Intent ( context , NewMusicService . class ) ; context . stopService ( intent ) ; return true ; } catch ( Exception e ) { return false ; } } public void setupMusicService ( ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( context , NewMusicService . class ) ; context . startService ( intent ) ; ServiceConnection sc = new ServiceConnection ( ) { @ Override public void onServiceConnected ( ComponentName name , IBinder service ) { startMusic ( NewMusicService . MUSIC_TYPE_MENU ) ; context . unbindService ( this ) ; } @ Override public void onServiceDisconnected ( ComponentName name ) { } } ; context . bindService ( intent , sc , <NUM_LIT:0> ) ; } public void startMusic ( int musicType ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( NewMusicService . MUSICSTART ) ; intent . putExtra ( NewMusicService . SETMUSICTYPE , musicType ) ; context . sendBroadcast ( intent ) ; } public void stopMusic ( ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( NewMusicService . MUSICSTOP ) ; context . sendBroadcast ( intent ) ; } public void pauseMusic ( ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( NewMusicService . MUSICPAUSE ) ; context . sendBroadcast ( intent ) ; } public void continueMusc ( ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( NewMusicService . MUSICCONTINUAL ) ; context . sendBroadcast ( intent ) ; } public void stopAndStartNewMusic ( int musicType ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; stopMusic ( ) ; startMusic ( musicType ) ; } public void releaseMusic ( ) { Log . v ( ENGINE_TAG , "<STR_LIT>" ) ; Intent intent = new Intent ( NewMusicService . MUSICRELEASE ) ; context . sendBroadcast ( intent ) ; } } </s>
|
<s> package com . example . sunsing . manager ; import java . util . BitSet ; import java . util . Iterator ; import java . util . LinkedList ; import com . example . sunsing . animal . enemy ; import com . example . sunsing . animal . protecter ; import com . example . sunsing . rescourse . allrescource ; import android . graphics . Canvas ; public class manager { private LinkedList < enemy > allenemy ; private boolean is_enemy_use ; private boolean is_protecter_use ; private LinkedList < protecter > allprotecter ; private static int number_allenemy = <NUM_LIT:10> ; private LinkedList < protecter > kd_protecter ; private Canvas canvas ; private int event_x , event_y ; private int event_state ; private static BitSet screen_bit = new BitSet ( <NUM_LIT> ) ; private int nb_of_block_of_line ; private protecter p_temp ; public manager ( ) { allenemy = new LinkedList < enemy > ( ) ; this . allenemy . addLast ( new enemy ( ) ) ; allprotecter = new LinkedList < protecter > ( ) ; kd_protecter = new LinkedList < protecter > ( ) ; this . p_temp = new protecter ( ) ; this . p_temp . setXY ( <NUM_LIT:0> , allrescource . screen_h - allrescource . mywapoon . geth ( ) - <NUM_LIT:2> ) ; this . kd_protecter . addLast ( this . p_temp ) ; this . p_temp = null ; this . is_enemy_use = false ; this . is_protecter_use = false ; this . nb_of_block_of_line = allrescource . screen_w / allrescource . mywapoon . getw ( ) ; } public void update ( ) { if ( this . event_state == <NUM_LIT:0> ) { if ( ( this . event_y >= allrescource . screen_h - allrescource . mywapoon . geth ( ) - <NUM_LIT:5> ) && ( this . event_x <= allrescource . mywapoon . getw ( ) ) ) { this . p_temp = new protecter ( ) ; this . p_temp . setState ( <NUM_LIT:1> ) ; this . p_temp . setXY ( <NUM_LIT:10> , allrescource . screen_h - allrescource . mywapoon . geth ( ) / <NUM_LIT:2> - <NUM_LIT:1> ) ; this . p_temp . draw ( canvas ) ; } return ; } else if ( this . event_state == <NUM_LIT:1> ) { if ( ( this . event_y <= allrescource . screen_h - allrescource . mywapoon . geth ( ) - <NUM_LIT:5> ) ) { int index_t = find_bit_index ( event_x , event_y ) ; if ( ( this . p_temp != null ) && ! screen_bit . get ( index_t ) ) { this . p_temp . setState ( <NUM_LIT:0> ) ; this . p_temp . setXY ( event_x - event_x % allrescource . mywapoon . getw ( ) , event_y - event_y % allrescource . mywapoon . geth ( ) ) ; this . p_temp . draw ( canvas ) ; screen_bit . set ( index_t ) ; } else { this . p_temp = null ; return ; } } else { this . p_temp = null ; return ; } } else { if ( this . p_temp != null ) { this . p_temp . setXY ( event_x - event_x % allrescource . mywapoon . getw ( ) , event_y - event_y % allrescource . mywapoon . geth ( ) ) ; this . p_temp . draw ( canvas ) ; } return ; } if ( ! this . is_protecter_use ) { this . is_protecter_use = true ; my_update ( ) ; } else { while ( this . is_protecter_use ) { ; } this . is_protecter_use = true ; my_update ( ) ; } this . is_protecter_use = false ; return ; } public void my_update ( ) { allprotecter . addLast ( p_temp ) ; this . p_temp = null ; } public void draw ( ) { boolean do_enemy = false ; boolean do_protect = false ; Iterator < protecter > it = kd_protecter . iterator ( ) ; while ( it . hasNext ( ) ) { protecter temp = it . next ( ) ; temp . draw ( canvas ) ; } while ( ( ! do_enemy ) || ( ! do_protect ) ) { if ( ( ! this . is_protecter_use ) && ( ! do_protect ) ) { this . is_protecter_use = true ; do_protect = true ; draw_protect ( ) ; this . is_protecter_use = false ; } if ( ( ! this . is_enemy_use ) && ( ! do_enemy ) ) { this . is_enemy_use = true ; do_enemy = true ; draw_enemy ( ) ; this . is_enemy_use = false ; } } } public void draw_protect ( ) { Iterator < protecter > it = allprotecter . iterator ( ) ; while ( it . hasNext ( ) ) { protecter temp = it . next ( ) ; temp . draw ( canvas ) ; } } public void draw_enemy ( ) { Iterator < enemy > it = allenemy . iterator ( ) ; while ( it . hasNext ( ) ) { enemy temp = it . next ( ) ; if ( temp . getX ( ) > allrescource . screen_w ) { it . remove ( ) ; } else { temp . draw ( canvas ) ; } } } public boolean make_enemy ( ) { if ( number_allenemy < <NUM_LIT:1> ) return false ; if ( ! this . is_enemy_use ) { this . is_enemy_use = true ; my_make_enemy ( ) ; } else { while ( this . is_enemy_use ) { ; } this . is_enemy_use = true ; my_make_enemy ( ) ; } this . is_enemy_use = false ; return true ; } public void my_make_enemy ( ) { this . allenemy . addLast ( new enemy ( ) ) ; number_allenemy -- ; } public void setCanvas ( Canvas canvas ) { this . canvas = canvas ; } public void setXYandState ( int xx , int yy , int sstate ) { this . event_x = xx ; this . event_y = yy ; this . event_state = sstate ; } public int find_bit_index ( int x , int y ) { int nb_of_height_block = y / allrescource . mywapoon . getw ( ) ; if ( ( ( y % allrescource . mywapoon . geth ( ) ) == <NUM_LIT:0> ) && ( y != <NUM_LIT:0> ) ) -- nb_of_height_block ; int bit_index = this . nb_of_block_of_line * nb_of_height_block + x / allrescource . mywapoon . getw ( ) ; if ( ( ( x % allrescource . mywapoon . getw ( ) ) == <NUM_LIT:0> ) && ( x != <NUM_LIT:0> ) ) -- bit_index ; return bit_index ; } } </s>
|
<s> package com . example . sunsing . main ; import com . example . sunsing . demo . R ; import com . example . sunsing . demo . R . id ; import com . example . sunsing . demo . R . layout ; import android . app . Activity ; import android . content . Intent ; import android . os . Bundle ; import android . view . View ; import android . widget . Button ; public class DemoActivity extends Activity { private Button start ; private Button quit ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . main ) ; start = ( Button ) findViewById ( R . id . start ) ; quit = ( Button ) findViewById ( R . id . quit ) ; start . setOnClickListener ( new Button . OnClickListener ( ) { @ Override public void onClick ( View v ) { Intent showNextPage_Intent = new Intent ( ) ; showNextPage_Intent . setClass ( DemoActivity . this , start . class ) ; startActivity ( showNextPage_Intent ) ; } } ) ; quit . setOnClickListener ( new Button . OnClickListener ( ) { @ Override public void onClick ( View v ) { System . exit ( <NUM_LIT:0> ) ; } } ) ; } } </s>
|
<s> package com . example . sunsing . main ; import com . example . sunsing . demo . mysurfaceview ; import android . app . Activity ; import android . content . pm . ActivityInfo ; import android . os . Bundle ; import android . view . Window ; import android . view . WindowManager ; public class start extends Activity { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; requestWindowFeature ( Window . FEATURE_NO_TITLE ) ; getWindow ( ) . setFlags ( WindowManager . LayoutParams . FLAG_FULLSCREEN , WindowManager . LayoutParams . FLAG_FULLSCREEN ) ; setContentView ( new mysurfaceview ( this ) ) ; } } </s>
|
<s> package com . example . sunsing . rescourse ; public final class allrescource { public static resource myenemy = new resource ( ) ; public static resource mywapoon = new resource ( ) ; public static resource myzidan = new resource ( ) ; public static int screen_w ; public static int screen_h ; } </s>
|
<s> package com . example . sunsing . rescourse ; import android . graphics . Bitmap ; public final class resource { private Bitmap bitmap ; private int width ; private int height ; public void setresource ( Bitmap bitmap1 ) { bitmap = bitmap1 ; width = bitmap . getWidth ( ) ; height = bitmap . getHeight ( ) ; } public Bitmap getBitmap ( ) { return bitmap ; } public int getw ( ) { return width ; } public int geth ( ) { return height ; } } </s>
|
<s> package com . example . sunsing . demo ; import com . example . sunsing . demo . R ; import com . example . sunsing . demo . R . drawable ; import com . example . sunsing . manager . manager ; import com . example . sunsing . rescourse . allrescource ; import android . content . Context ; import android . graphics . BitmapFactory ; import android . graphics . Canvas ; import android . graphics . Color ; import android . graphics . Paint ; import android . view . MotionEvent ; import android . view . SurfaceHolder ; import android . view . SurfaceHolder . Callback ; import android . view . SurfaceView ; public class mysurfaceview extends SurfaceView implements Callback , Runnable { private SurfaceHolder sfh ; private Paint paint ; private Canvas canvas ; private boolean nostop ; private boolean m_e_stop ; protected Thread mainThread ; private manager mymanager ; public mysurfaceview ( Context context ) { super ( context ) ; sfh = this . getHolder ( ) ; sfh . addCallback ( this ) ; paint = new Paint ( ) ; } @ Override public void run ( ) { while ( nostop ) { long start = System . currentTimeMillis ( ) ; myDraw ( ) ; long end = System . currentTimeMillis ( ) ; try { if ( end - start < <NUM_LIT:30> ) { Thread . sleep ( <NUM_LIT:30> - ( end - start ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public void myDraw ( ) { try { canvas = sfh . lockCanvas ( ) ; paint . setColor ( Color . BLUE ) ; canvas . drawRect ( <NUM_LIT:0> , <NUM_LIT:0> , allrescource . screen_w , allrescource . screen_h , paint ) ; int yy = allrescource . screen_h - allrescource . mywapoon . geth ( ) - <NUM_LIT:5> ; int xx = allrescource . screen_w ; paint . setColor ( Color . RED ) ; canvas . drawLine ( <NUM_LIT:0> , yy , xx , yy , paint ) ; canvas . drawLine ( <NUM_LIT:0> , yy - <NUM_LIT:1> , xx , yy - <NUM_LIT:1> , paint ) ; mymanager . setCanvas ( canvas ) ; mymanager . draw ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( canvas != null ) { sfh . unlockCanvasAndPost ( canvas ) ; } } } @ Override public boolean onTouchEvent ( MotionEvent event ) { int x = ( int ) event . getX ( ) ; int y = ( int ) event . getY ( ) ; if ( event . getAction ( ) == MotionEvent . ACTION_DOWN ) { mymanager . setXYandState ( x , y , <NUM_LIT:0> ) ; } else if ( event . getAction ( ) == MotionEvent . ACTION_MOVE ) { mymanager . setXYandState ( x , y , <NUM_LIT:2> ) ; } else if ( event . getAction ( ) == MotionEvent . ACTION_UP ) { mymanager . setXYandState ( x , y , <NUM_LIT:1> ) ; } mymanager . update ( ) ; return true ; } @ Override public void surfaceChanged ( SurfaceHolder holder , int format , int width , int height ) { } @ Override public void surfaceCreated ( SurfaceHolder holder ) { allrescource . myenemy . setresource ( BitmapFactory . decodeResource ( this . getResources ( ) , R . drawable . monster ) ) ; allrescource . mywapoon . setresource ( BitmapFactory . decodeResource ( this . getResources ( ) , R . drawable . wapoon ) ) ; allrescource . myzidan . setresource ( BitmapFactory . decodeResource ( this . getResources ( ) , R . drawable . zidan ) ) ; allrescource . screen_h = this . getHeight ( ) ; allrescource . screen_w = this . getWidth ( ) ; mymanager = new manager ( ) ; nostop = true ; mainThread = new Thread ( this ) ; mainThread . start ( ) ; this . m_e_stop = true ; new Thread ( ) { @ Override public void run ( ) { while ( m_e_stop ) { long start = System . currentTimeMillis ( ) ; if ( ! mymanager . make_enemy ( ) ) m_e_stop = false ; long end = System . currentTimeMillis ( ) ; try { if ( end - start < <NUM_LIT> ) { Thread . sleep ( <NUM_LIT> - ( end - start ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } . start ( ) ; } @ Override public void surfaceDestroyed ( SurfaceHolder holder ) { nostop = false ; } } </s>
|
<s> package com . example . sunsing . animal ; import java . util . Random ; import com . example . sunsing . rescourse . allrescource ; import android . graphics . Bitmap ; import android . graphics . Canvas ; import android . graphics . Paint ; public class enemy { private Bitmap bitmap ; private Paint paint ; private int width ; private int height ; private int current_x ; private int current_y ; private final static int [ ] yy = { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> } ; private int state ; private int life ; private boolean ischanged ; public enemy ( ) { paint = new Paint ( ) ; bitmap = allrescource . myenemy . getBitmap ( ) ; width = allrescource . myenemy . getw ( ) ; height = allrescource . myenemy . geth ( ) ; life = <NUM_LIT:100> ; current_x = <NUM_LIT:0> ; current_y = yy [ ( new Random ( ) . nextInt ( <NUM_LIT:10> ) ) % <NUM_LIT:3> ] ; } public void draw ( Canvas canvas ) { canvas . drawBitmap ( bitmap , current_x , current_y , paint ) ; current_x += <NUM_LIT:1> ; } public int getX ( ) { return this . current_x ; } public int getY ( ) { return this . current_y ; } public int getState ( ) { return this . state ; } } </s>
|
<s> package com . example . sunsing . animal ; import com . example . sunsing . rescourse . allrescource ; import android . graphics . Bitmap ; import android . graphics . Canvas ; import android . graphics . Color ; import android . graphics . Paint ; public class protecter { private Bitmap bitmap ; private Paint paint ; private int width ; private int height ; private final float radius = <NUM_LIT> ; private int state ; private int current_x , current_y ; private boolean ischanged ; public protecter ( ) { bitmap = allrescource . mywapoon . getBitmap ( ) ; width = allrescource . mywapoon . getw ( ) ; height = allrescource . mywapoon . geth ( ) ; this . state = <NUM_LIT:0> ; } public void draw ( Canvas canvas ) { if ( state == <NUM_LIT:0> ) { paint = new Paint ( ) ; canvas . drawBitmap ( bitmap , this . current_x , this . current_y , paint ) ; } else { paint = new Paint ( ) ; paint . setColor ( Color . RED ) ; paint . setAlpha ( <NUM_LIT:100> ) ; canvas . drawCircle ( this . current_x , this . current_x , radius , paint ) ; paint = new Paint ( ) ; paint . setAlpha ( <NUM_LIT> ) ; canvas . drawBitmap ( bitmap , this . current_x , this . current_y , paint ) ; } } public void setXY ( int xx , int yy ) { this . current_x = xx ; this . current_y = yy ; } public void setState ( int stat ) { this . state = stat ; } public int getState ( ) { return this . state ; } public int getX ( ) { return this . current_x ; } public int getY ( ) { return this . current_y ; } } </s>
|
<s> package com . example . sunsing . demo ; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher = <NUM_LIT> ; public static final int monster = <NUM_LIT> ; public static final int wapoon = <NUM_LIT> ; public static final int zidan = <NUM_LIT> ; } public static final class id { public static final int quit = <NUM_LIT> ; public static final int start = <NUM_LIT> ; } public static final class layout { public static final int main = <NUM_LIT> ; } public static final class string { public static final int app_name = <NUM_LIT> ; public static final int hello = <NUM_LIT> ; public static final int quit = <NUM_LIT> ; public static final int start = <NUM_LIT> ; } } </s>
|
<s> package com . example . sunsing . demo ; public final class BuildConfig { public final static boolean DEBUG = true ; } </s>
|
<s> package edu . uestc . project . cycle . alg . basic ; import java . util . Vector ; import android . graphics . Rect ; public class LinePath { Vector < Line > vector ; private float startX , startY ; private float currentX , currentY ; private float maxRightX , maxRightY ; private int minLineLength ; private boolean isClosed ; private int pathLength ; public static final int ALL_POINTS = <NUM_LIT:0> ; public static final int ONE_POINT = <NUM_LIT:1> ; public static final int TWO_POINTS = <NUM_LIT:2> ; public static final int THREE_POINTS = <NUM_LIT:3> ; public LinePath ( int minLineLength ) { this . vector = new Vector < Line > ( ) ; this . startX = - <NUM_LIT:1> ; this . startY = - <NUM_LIT:1> ; this . currentX = - <NUM_LIT:1> ; this . currentY = - <NUM_LIT:1> ; this . maxRightX = - <NUM_LIT:1> ; this . maxRightY = - <NUM_LIT:1> ; this . pathLength = <NUM_LIT:0> ; this . minLineLength = minLineLength ; } public LinePath ( ) { this . vector = new Vector < Line > ( ) ; this . startX = - <NUM_LIT:1> ; this . startY = - <NUM_LIT:1> ; this . currentX = - <NUM_LIT:1> ; this . currentY = - <NUM_LIT:1> ; this . minLineLength = <NUM_LIT:10> ; this . isClosed = false ; } private boolean runContainAlgorithm ( int x , int y , int offset ) { int counter = <NUM_LIT:0> ; Line l = new Line ( x , y , this . maxRightX + offset , this . maxRightY ) ; for ( int i = <NUM_LIT:0> ; i < vector . size ( ) ; i ++ ) { Line line = vector . get ( i ) ; switch ( Line . isCrossed ( l , line ) ) { case Line . CROSSED_NOEND : counter ++ ; break ; case Line . CROSSED_LINE2WITHEND : i ++ ; counter ++ ; break ; } } if ( counter % <NUM_LIT:2> == <NUM_LIT:0> ) { return false ; } return true ; } public boolean isContainsPoint ( int x , int y ) { if ( this . isEmpty ( ) ) { return false ; } if ( ! this . isClosed ) { this . close ( ) ; } boolean resultA , resultB ; resultA = this . runContainAlgorithm ( x , y , <NUM_LIT:10> ) ; resultB = this . runContainAlgorithm ( x , y , <NUM_LIT:100> ) ; if ( resultA == resultB ) { return resultA ; } else { return this . runContainAlgorithm ( x , y , <NUM_LIT> ) ; } } public boolean isContainsRect ( Rect r , int method ) { int trueCounter = <NUM_LIT:0> ; if ( this . isEmpty ( ) ) { return false ; } if ( ! this . isClosed ) { this . close ( ) ; } if ( this . isContainsPoint ( r . left , r . top ) ) { trueCounter ++ ; } if ( this . isContainsPoint ( r . left , r . bottom ) ) { trueCounter ++ ; } if ( this . isContainsPoint ( r . right , r . top ) ) { trueCounter ++ ; } if ( this . isContainsPoint ( r . right , r . bottom ) ) { trueCounter ++ ; } switch ( method ) { case ALL_POINTS : if ( trueCounter == <NUM_LIT:4> ) { return true ; } break ; case ONE_POINT : if ( trueCounter >= <NUM_LIT:1> ) { return true ; } break ; case TWO_POINTS : if ( trueCounter >= <NUM_LIT:2> ) { return true ; } break ; case THREE_POINTS : if ( trueCounter >= <NUM_LIT:3> ) { return true ; } break ; default : } return false ; } public void moveToStart ( float x , float y ) { this . reset ( ) ; this . startX = x ; this . startY = y ; this . currentX = x ; this . currentY = y ; this . maxRightX = x ; this . maxRightY = y ; } public boolean isClosed ( ) { return this . isClosed ; } public void lineTo ( float x , float y ) { if ( this . isClosed ) { return ; } if ( this . vector != null ) { if ( Math . abs ( x - this . currentX ) > this . minLineLength || Math . abs ( y - this . currentY ) > this . minLineLength ) { this . vector . add ( new Line ( this . currentX , this . currentY , x , y ) ) ; this . pathLength += ( int ) Math . sqrt ( ( this . currentX - x ) * ( this . currentX - x ) + ( this . currentY - y ) * ( this . currentY - y ) ) ; this . currentX = x ; this . currentY = y ; } if ( x >= this . maxRightX ) { this . maxRightX = x ; this . maxRightY = y ; } } } public int getMinLineLength ( ) { return this . minLineLength ; } public void setMinLineLength ( int minLineLength ) { this . minLineLength = minLineLength ; } public void close ( ) { if ( ! this . isEmpty ( ) ) { this . lineTo ( this . startX , this . startY ) ; this . isClosed = true ; } } public boolean isEmpty ( ) { if ( this . vector == null ) { return true ; } if ( this . startX != - <NUM_LIT:1> || this . startY != - <NUM_LIT:1> ) { return false ; } return this . vector . isEmpty ( ) ; } public void reset ( ) { this . startX = - <NUM_LIT:1> ; this . startY = - <NUM_LIT:1> ; this . currentX = - <NUM_LIT:1> ; this . currentY = - <NUM_LIT:1> ; this . minLineLength = <NUM_LIT:10> ; this . maxRightX = - <NUM_LIT:1> ; this . maxRightY = - <NUM_LIT:1> ; this . pathLength = <NUM_LIT:0> ; this . isClosed = false ; if ( this . vector != null && ! this . vector . isEmpty ( ) ) { this . vector . clear ( ) ; } } public int getPathLenght ( ) { return this . pathLength ; } } </s>
|
<s> package edu . uestc . project . cycle . alg . basic ; public class Line { private float startX , startY ; private float endX , endY ; private float pa = <NUM_LIT:0.0f> , pb = <NUM_LIT:0.0f> , pc = <NUM_LIT:0.0f> ; public static final int UNCROSSED = <NUM_LIT:0> ; public static final int CROSSED_LINE1WITHEND = <NUM_LIT:1> ; public static final int CROSSED_LINE2WITHEND = <NUM_LIT:2> ; public static final int CROSSED_NOEND = <NUM_LIT:3> ; public Line ( float x1 , float y1 , float x2 , float y2 ) { if ( x1 == x2 ) { this . pc = <NUM_LIT:0> ; this . pb = - x1 ; this . pa = <NUM_LIT:1> ; } else if ( y1 == y2 ) { this . pa = <NUM_LIT:0> ; this . pc = <NUM_LIT:1> ; this . pb = y1 ; } else { this . pc = <NUM_LIT:1> ; this . pb = ( x1 * y2 - y1 * x2 ) / ( x1 - x2 ) ; this . pa = ( y1 - y2 ) / ( x1 - x2 ) ; } this . startX = x1 ; this . startY = y1 ; this . endX = x2 ; this . endY = y2 ; } public static int isCrossed ( Line line1 , Line line2 ) { float item1 = ( line1 . getPc ( ) * line2 . getPa ( ) - line1 . getPa ( ) * line2 . getPc ( ) ) ; float item2 , item3 , x , y ; if ( item1 != <NUM_LIT:0> ) { item2 = ( line1 . getPb ( ) * line2 . getPa ( ) - line1 . getPa ( ) * line2 . getPb ( ) ) ; item3 = ( line1 . getPb ( ) * line2 . getPc ( ) - line1 . getPc ( ) * line2 . getPb ( ) ) ; y = item2 / item1 ; x = item3 / item1 ; if ( x <= Math . max ( line1 . getStartX ( ) , line1 . getEndX ( ) ) && x >= Math . min ( line1 . getStartX ( ) , line1 . getEndX ( ) ) && x <= Math . max ( line2 . getStartX ( ) , line2 . getEndX ( ) ) && x >= Math . min ( line2 . getStartX ( ) , line2 . getEndX ( ) ) && y <= Math . max ( line1 . getStartY ( ) , line1 . getEndY ( ) ) && y >= Math . min ( line1 . getStartY ( ) , line1 . getEndY ( ) ) && y <= Math . max ( line2 . getStartY ( ) , line2 . getEndY ( ) ) && y >= Math . min ( line2 . getStartY ( ) , line2 . getEndY ( ) ) ) { if ( Math . abs ( ( x - Math . max ( line1 . getStartX ( ) , line1 . getEndX ( ) ) ) ) <= <NUM_LIT:1.0f> || Math . abs ( ( x - Math . min ( line1 . getStartX ( ) , line1 . getEndX ( ) ) ) ) <= <NUM_LIT:1.0f> ) { return CROSSED_LINE1WITHEND ; } if ( Math . abs ( ( x - Math . max ( line2 . getStartX ( ) , line2 . getEndX ( ) ) ) ) <= <NUM_LIT:1.0f> || Math . abs ( ( x - Math . min ( line2 . getStartX ( ) , line2 . getEndX ( ) ) ) ) <= <NUM_LIT:1.0f> ) { return CROSSED_LINE2WITHEND ; } return CROSSED_NOEND ; } } return UNCROSSED ; } public float getStartX ( ) { return startX ; } public float getStartY ( ) { return startY ; } public float getEndX ( ) { return endX ; } public float getEndY ( ) { return endY ; } public float getPa ( ) { return pa ; } public float getPb ( ) { return pb ; } public float getPc ( ) { return pc ; } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; public class SpiritState { public static final int INIT_STATE = <NUM_LIT:1> ; public static final int SELECTED_STATE = <NUM_LIT:2> ; private int state = <NUM_LIT:0> ; boolean isSelected = false ; public int getState ( ) { return state ; } public void resetState ( ) { state = <NUM_LIT:0> ; } public void unmountState ( int state ) { this . state &= ~ state ; } public void mountState ( int state ) { this . state |= state ; } public static boolean equals ( SpiritState state1 , SpiritState state2 ) { if ( state1 . getState ( ) == state2 . getState ( ) ) { return true ; } else { return false ; } } public boolean containsState ( int state ) { if ( ( this . state & state ) != <NUM_LIT:0> ) { return true ; } else { return false ; } } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; import java . util . Iterator ; import java . util . Vector ; public class SpiritGroup { private Vector < SpiritObject > vector ; public SpiritGroup ( ) { this . vector = new Vector < SpiritObject > ( ) ; } public int size ( ) { return this . vector . size ( ) ; } protected void addSpiritObject ( SpiritObject object ) { this . vector . add ( object ) ; } protected void removeSpiritIndex ( int location ) { this . vector . remove ( location ) ; } protected void removeSpiritIndex ( SpiritObject object ) { this . vector . remove ( object ) ; } public Iterator < SpiritObject > iterator ( ) { return new SpiritGrouprIterator ( this . vector ) ; } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; import java . util . Iterator ; import java . util . Vector ; public class SpiritManager { private Vector < SpiritObject > spiritElements ; public SpiritManager ( ) { this . spiritElements = new Vector < SpiritObject > ( ) ; } public void registerSpirit ( SpiritObject object ) { this . spiritElements . add ( object ) ; } public void unRegisterSpirit ( int location ) { this . spiritElements . remove ( location ) ; } public void unRegisterSpirit ( SpiritObject object ) { this . spiritElements . remove ( object ) ; } public int size ( ) { return this . spiritElements . size ( ) ; } public Iterator < SpiritObject > iterator ( ) { return new SpiritManagerIterator ( this . spiritElements ) ; } public SpiritGroup getGroupByState ( SpiritState state ) { Iterator < SpiritObject > iterator = this . iterator ( ) ; SpiritGroup sg = new SpiritGroup ( ) ; while ( iterator . hasNext ( ) ) { SpiritObject object = iterator . next ( ) ; if ( SpiritState . equals ( state , object . getState ( ) ) ) { sg . addSpiritObject ( object ) ; } } return sg ; } public SpiritGroup getGroupByState ( int state ) { Iterator < SpiritObject > iterator = this . iterator ( ) ; SpiritGroup sg = new SpiritGroup ( ) ; while ( iterator . hasNext ( ) ) { SpiritObject object = iterator . next ( ) ; if ( object . getState ( ) . containsState ( state ) ) { sg . addSpiritObject ( object ) ; } } return sg ; } public boolean removeByGroup ( SpiritGroup group ) { Iterator < SpiritObject > iterator = group . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( ! this . spiritElements . contains ( iterator . next ( ) ) ) { return false ; } } iterator = group . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( this . spiritElements . remove ( iterator . next ( ) ) ) { continue ; } else { return false ; } } group = null ; return true ; } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; import android . graphics . Bitmap ; import android . graphics . Rect ; public class SpiritObject { private SpiritState state ; private Bitmap bitmap ; private int startX , startY ; private int oldestX , oldestY ; public boolean isSelected ( ) { if ( this . state . containsState ( SpiritState . SELECTED_STATE ) ) { return true ; } else { return false ; } } public int getOldestX ( ) { return oldestX ; } public void setOldestX ( int oldestX ) { this . oldestX = oldestX ; } public int getOldestY ( ) { return oldestY ; } public void setOldestY ( int oldestY ) { this . oldestY = oldestY ; } public void setSelected ( boolean isSelected ) { if ( isSelected ) { this . state . mountState ( SpiritState . SELECTED_STATE ) ; } else { this . state . unmountState ( SpiritState . SELECTED_STATE ) ; } } public SpiritState getState ( ) { return state ; } public void setState ( SpiritState state ) { this . state = state ; } public SpiritObject ( int x , int y ) { this . state = new SpiritState ( ) ; this . state . mountState ( SpiritState . INIT_STATE ) ; this . oldestX = x ; this . oldestY = y ; this . startX = x ; this . startY = y ; } public SpiritObject ( ) { this . state = new SpiritState ( ) ; this . state . mountState ( SpiritState . INIT_STATE ) ; } public Bitmap getBitmap ( ) { return bitmap ; } public void setBitmap ( Bitmap bitmap ) { this . bitmap = bitmap ; } public int getStartX ( ) { return startX ; } public void setStartX ( int startX ) { this . startX = startX ; } public int getStartY ( ) { return startY ; } public void setStartY ( int startY ) { this . startY = startY ; } public Rect getRect ( ) { Rect rect = new Rect ( ) ; rect . set ( getStartX ( ) , getStartY ( ) , getStartX ( ) + getBitmap ( ) . getWidth ( ) , getStartY ( ) + getBitmap ( ) . getHeight ( ) ) ; return rect ; } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; import java . util . Vector ; public class SpiritManagerIterator implements java . util . Iterator < SpiritObject > { private Vector < SpiritObject > vector ; private int cur = <NUM_LIT:0> ; public SpiritManagerIterator ( Vector < SpiritObject > v ) { this . vector = v ; } public boolean hasNext ( ) { if ( this . cur == this . vector . size ( ) ) { return false ; } return true ; } public SpiritObject next ( ) { if ( this . hasNext ( ) ) { return this . vector . get ( this . cur ++ ) ; } else { return null ; } } public void remove ( ) { this . vector . remove ( this . cur ) ; } } </s>
|
<s> package edu . uestc . project . cycle . spirit ; import java . util . Vector ; public class SpiritGrouprIterator implements java . util . Iterator < SpiritObject > { private Vector < SpiritObject > vector ; private int cur = <NUM_LIT:0> ; public SpiritGrouprIterator ( Vector < SpiritObject > v ) { this . vector = v ; } public boolean hasNext ( ) { if ( this . cur == this . vector . size ( ) ) { return false ; } return true ; } public SpiritObject next ( ) { if ( this . hasNext ( ) ) { return this . vector . get ( this . cur ++ ) ; } else { return null ; } } public void remove ( ) { } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.