idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
138,600
public SceneBlock getBlock ( int tx , int ty ) { int bx = MathUtil . floorDiv ( tx , _metrics . blockwid ) ; int by = MathUtil . floorDiv ( ty , _metrics . blockhei ) ; return _blocks . get ( compose ( bx , by ) ) ; }
Returns the resolved block that contains the specified tile coordinate or null if no block is resolved for that coordinate .
70
21
138,601
public Path getPath ( Sprite sprite , int x , int y , boolean loose ) { // sanity check if ( sprite == null ) { throw new IllegalArgumentException ( "Can't get path for null sprite [x=" + x + ", y=" + y + "." ) ; } // get the destination tile coordinates Point src = MisoUtil . screenToTile ( _metrics , sprite . getX ( ) , sprite . getY ( ) , new Point ( ) ) ; Point dest = MisoUtil . screenToTile ( _metrics , x , y , new Point ( ) ) ; // compute our longest path from the screen size int longestPath = 3 * ( getWidth ( ) / _metrics . tilewid ) ; // get a reasonable tile path through the scene long start = System . currentTimeMillis ( ) ; List < Point > points = AStarPathUtil . getPath ( this , sprite , longestPath , src . x , src . y , dest . x , dest . y , loose ) ; long duration = System . currentTimeMillis ( ) - start ; // sanity check the number of nodes searched so that we can keep an eye out for bogosity if ( duration > 500L ) { int considered = AStarPathUtil . getConsidered ( ) ; log . warning ( "Considered " + considered + " nodes for path from " + StringUtil . toString ( src ) + " to " + StringUtil . toString ( dest ) + " [duration=" + duration + "]." ) ; } // construct a path object to guide the sprite on its merry way return ( points == null ) ? null : new TilePath ( _metrics , sprite , points , x , y ) ; }
Computes a path for the specified sprite to the specified tile coordinates .
369
14
138,602
public Point getScreenCoords ( int x , int y ) { return MisoUtil . fullToScreen ( _metrics , x , y , new Point ( ) ) ; }
Converts the supplied full coordinates to screen coordinates .
39
10
138,603
public Point getFullCoords ( int x , int y ) { return MisoUtil . screenToFull ( _metrics , x , y , new Point ( ) ) ; }
Converts the supplied screen coordinates to full coordinates .
39
10
138,604
public Point getTileCoords ( int x , int y ) { return MisoUtil . screenToTile ( _metrics , x , y , new Point ( ) ) ; }
Converts the supplied screen coordinates to tile coordinates .
39
10
138,605
public void reportMemoryUsage ( ) { Map < Tile . Key , BaseTile > base = Maps . newHashMap ( ) ; Set < BaseTile > fringe = Sets . newHashSet ( ) ; Map < Tile . Key , ObjectTile > object = Maps . newHashMap ( ) ; long [ ] usage = new long [ 3 ] ; for ( SceneBlock block : _blocks . values ( ) ) { block . computeMemoryUsage ( base , fringe , object , usage ) ; } log . info ( "Scene tile memory usage" , "scene" , StringUtil . shortClassName ( this ) , "base" , base . size ( ) + "->" + ( usage [ 0 ] / 1024 ) + "k" , "fringe" , fringe . size ( ) + "->" + ( usage [ 1 ] / 1024 ) + "k" , "obj" , object . size ( ) + "->" + ( usage [ 2 ] / 1024 ) + "k" ) ; }
Reports the memory usage of the resolved tiles in the current scene block .
212
14
138,606
protected void handleObjectPressed ( final SceneObject scobj , int mx , int my ) { String action = scobj . info . action ; final ObjectActionHandler handler = ObjectActionHandler . lookup ( action ) ; // if there's no handler, just fire the action immediately if ( handler == null ) { fireObjectAction ( null , scobj , new SceneObjectActionEvent ( this , 0 , action , 0 , scobj ) ) ; return ; } // if the action's not allowed, pretend like we handled it if ( ! handler . actionAllowed ( action ) ) { return ; } // if there's no menu for this object, fire the action immediately RadialMenu menu = handler . handlePressed ( scobj ) ; if ( menu == null ) { fireObjectAction ( handler , scobj , new SceneObjectActionEvent ( this , 0 , action , 0 , scobj ) ) ; return ; } // make the menu surround the clicked object, but with consistent size Rectangle mbounds = getRadialMenuBounds ( scobj ) ; _activeMenu = menu ; _activeMenu . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { if ( e instanceof CommandEvent ) { fireObjectAction ( handler , scobj , e ) ; } else { SceneObjectActionEvent event = new SceneObjectActionEvent ( e . getSource ( ) , e . getID ( ) , e . getActionCommand ( ) , e . getModifiers ( ) , scobj ) ; fireObjectAction ( handler , scobj , event ) ; } } } ) ; _activeMenu . activate ( this , mbounds , scobj ) ; }
Called when the user presses the mouse button over an object .
357
13
138,607
protected void fireObjectAction ( ObjectActionHandler handler , SceneObject scobj , ActionEvent event ) { if ( handler == null ) { Controller . postAction ( event ) ; } else { handler . handleAction ( scobj , event ) ; } }
Called when an object or object menu item has been clicked .
52
13
138,608
protected void appendDirtySprite ( DirtyItemList list , Sprite sprite ) { MisoUtil . screenToTile ( _metrics , sprite . getX ( ) , sprite . getY ( ) , _tcoords ) ; list . appendDirtySprite ( sprite , _tcoords . x , _tcoords . y ) ; }
Computes the tile coordinates of the supplied sprite and appends it to the supplied dirty item list .
76
20
138,609
protected void blockAbandoned ( SceneBlock block ) { if ( _dpanel != null ) { _dpanel . blockCleared ( block ) ; } blockFinished ( block ) ; }
Called by the scene block if it has come up for resolution but is no longer influential .
41
19
138,610
protected void blockResolved ( SceneBlock block ) { if ( _dpanel != null ) { _dpanel . resolvedBlock ( block ) ; } Rectangle sbounds = block . getScreenBounds ( ) ; if ( ! _delayRepaint && sbounds != null && sbounds . intersects ( _vbounds ) ) { // warnVisible(block, sbounds); // if we have yet further blocks to resolve, queue up a repaint now so that we get these // data onscreen as quickly as possible if ( _pendingBlocks > 1 ) { recomputeVisible ( ) ; _remgr . invalidateRegion ( sbounds ) ; } } blockFinished ( block ) ; }
Called by a scene block when it has completed its resolution process .
154
14
138,611
protected void blockFinished ( SceneBlock block ) { -- _pendingBlocks ; // once all the visible pending blocks have completed their // resolution, recompute our visible object set and show ourselves if ( _visiBlocks . remove ( block ) && _visiBlocks . size ( ) == 0 ) { allBlocksFinished ( ) ; } }
Called whenever a block is done resolving whether it was successfully resolved or if it was abandoned .
72
19
138,612
protected void allBlocksFinished ( ) { recomputeVisible ( ) ; log . info ( "Restoring repaint... " , "left" , _pendingBlocks , "view" , StringUtil . toString ( _vbounds ) ) ; _delayRepaint = false ; // Need to restore visibility as it may have been turned of as a result of the delay setVisible ( true ) ; _remgr . invalidateRegion ( _vbounds ) ; }
Called to handle the proceedings once our last resolving block has been finished .
102
15
138,613
protected void warnVisible ( SceneBlock block , Rectangle sbounds ) { log . warning ( "Block visible during resolution " + block + " sbounds:" + StringUtil . toString ( sbounds ) + " vbounds:" + StringUtil . toString ( _vbounds ) + "." ) ; }
Issues a warning to the error log that the specified block became visible prior to being resolved . Derived classes may wish to augment or inhibit this warning .
72
31
138,614
protected void recomputeVisible ( ) { // flush our visible object set which we'll recreate later _vizobjs . clear ( ) ; Rectangle vbounds = new Rectangle ( _vbounds . x - _metrics . tilewid , _vbounds . y - _metrics . tilehei , _vbounds . width + 2 * _metrics . tilewid , _vbounds . height + 2 * _metrics . tilehei ) ; for ( SceneBlock block : _blocks . values ( ) ) { if ( ! block . isResolved ( ) ) { continue ; } // links this block to its neighbors; computes coverage block . update ( _blocks ) ; // see which of this block's objects are visible SceneObject [ ] objs = block . getObjects ( ) ; for ( SceneObject obj : objs ) { if ( obj . bounds != null && vbounds . intersects ( obj . bounds ) ) { _vizobjs . add ( obj ) ; } } } // recompute our object indicators computeIndicators ( ) ; // Log.info("Computed " + _vizobjs.size() + " visible objects from " + // _blocks.size() + " blocks."); // Log.info(StringUtil.listToString(_vizobjs, new StringUtil.Formatter() { // public String toString (Object object) { // SceneObject scobj = (SceneObject)object; // return (TileUtil.getTileSetId(scobj.info.tileId) + ":" + // TileUtil.getTileIndex(scobj.info.tileId)); // } // })); }
Recomputes our set of visible objects and their indicators .
362
12
138,615
public void computeIndicators ( ) { Map < SceneObject , SceneObjectIndicator > _unupdated = Maps . newHashMap ( _indicators ) ; for ( int ii = 0 , nn = _vizobjs . size ( ) ; ii < nn ; ii ++ ) { SceneObject scobj = _vizobjs . get ( ii ) ; String action = scobj . info . action ; // if the object has no action, skip it if ( StringUtil . isBlank ( action ) ) { continue ; } // if we have an object action handler, possibly let them veto // the display of this tooltip and action ObjectActionHandler oah = ObjectActionHandler . lookup ( action ) ; if ( oah != null && ! oah . isVisible ( action ) ) { continue ; } String tiptext = getTipText ( scobj , action ) ; if ( tiptext != null ) { Icon icon = getTipIcon ( scobj , action ) ; SceneObjectIndicator indic = _unupdated . remove ( scobj ) ; if ( indic == null ) { // let the object action handler create the indicator if it exists, otherwise // just use a regular tip if ( oah != null ) { indic = oah . createIndicator ( this , tiptext , icon ) ; } else { indic = new SceneObjectTip ( tiptext , icon ) ; } _indicators . put ( scobj , indic ) ; } else { indic . update ( icon , tiptext ) ; } dirtyIndicator ( indic ) ; } } // clear out any no longer used indicators for ( SceneObject toremove : _unupdated . keySet ( ) ) { SceneObjectIndicator indic = _indicators . remove ( toremove ) ; indic . removed ( ) ; dirtyIndicator ( indic ) ; } _indicatorsLaidOut = false ; }
Compute the indicators for any objects in the scene .
398
11
138,616
protected String getTipText ( SceneObject scobj , String action ) { ObjectActionHandler oah = ObjectActionHandler . lookup ( action ) ; return ( oah == null ) ? action : oah . getTipText ( action ) ; }
Derived classes can provide human readable object tips via this method .
51
13
138,617
protected Icon getTipIcon ( SceneObject scobj , String action ) { ObjectActionHandler oah = ObjectActionHandler . lookup ( action ) ; return ( oah == null ) ? null : oah . getTipIcon ( action ) ; }
Provides an icon for this tooltip the default looks up an object action handler for the action and requests the icon from it .
51
25
138,618
protected void dirtyIndicator ( SceneObjectIndicator indic ) { if ( indic != null ) { Rectangle r = indic . getBounds ( ) ; if ( r != null ) { _remgr . invalidateRegion ( r ) ; } } }
Dirties the specified indicator .
53
7
138,619
protected void changeHoverObject ( Object newHover ) { if ( newHover == _hobject ) { return ; } Object oldHover = _hobject ; _hobject = newHover ; hoverObjectChanged ( oldHover , newHover ) ; }
Change the hover object to the new object .
58
9
138,620
protected void hoverObjectChanged ( Object oldHover , Object newHover ) { // deal with objects that care about being hovered over if ( oldHover instanceof SceneObject ) { SceneObject oldhov = ( SceneObject ) oldHover ; if ( oldhov . setHovered ( false ) ) { _remgr . invalidateRegion ( oldhov . bounds ) ; } } if ( newHover instanceof SceneObject ) { SceneObject newhov = ( SceneObject ) newHover ; if ( newhov . setHovered ( true ) ) { _remgr . invalidateRegion ( newhov . bounds ) ; } } // dirty the indicators associated with the hover objects dirtyIndicator ( _indicators . get ( oldHover ) ) ; dirtyIndicator ( _indicators . get ( newHover ) ) ; }
A place for subclasses to react to the hover object changing . One of the supplied arguments may be null .
176
22
138,621
protected void getHitObjects ( DirtyItemList list , int x , int y ) { for ( SceneObject scobj : _vizobjs ) { Rectangle pbounds = scobj . bounds ; if ( ! pbounds . contains ( x , y ) ) { continue ; } // see if we should skip it if ( skipHitObject ( scobj ) ) { continue ; } // now check that the pixel in the tile image is non-transparent at that point if ( ! scobj . tile . hitTest ( x - pbounds . x , y - pbounds . y ) ) { continue ; } // we've passed the test, add the object to the list list . appendDirtyObject ( scobj ) ; } }
Adds to the supplied dirty item list all of the object tiles that are hit by the specified point ( meaning the point is contained within their bounds and intersects a non - transparent pixel in the actual object image .
159
42
138,622
@ Override protected void paintBits ( Graphics2D gfx , int layer , Rectangle dirty ) { _animmgr . paint ( gfx , layer , dirty ) ; }
We don t want sprites rendered using the standard mechanism because we intersperse them with objects in our scene and need to manage their z - order .
39
30
138,623
protected void paintDirtyItems ( Graphics2D gfx , Rectangle clip ) { // add any sprites impacted by the dirty rectangle _dirtySprites . clear ( ) ; _spritemgr . getIntersectingSprites ( _dirtySprites , clip ) ; int size = _dirtySprites . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { Sprite sprite = _dirtySprites . get ( ii ) ; Rectangle bounds = sprite . getBounds ( ) ; if ( ! bounds . intersects ( clip ) ) { continue ; } appendDirtySprite ( _dirtyItems , sprite ) ; // Log.info("Dirtied item: " + sprite); } // add any objects impacted by the dirty rectangle for ( SceneObject scobj : _vizobjs ) { if ( ! scobj . bounds . intersects ( clip ) ) { continue ; } _dirtyItems . appendDirtyObject ( scobj ) ; // Log.info("Dirtied item: " + scobj); } // Log.info("paintDirtyItems [items=" + _dirtyItems.size() + "]."); // sort the dirty items so that we can paint them back-to-front _dirtyItems . sort ( ) ; _dirtyItems . paintAndClear ( gfx ) ; }
Renders the dirty sprites and objects in the scene to the given graphics context .
283
16
138,624
protected void paintIndicators ( Graphics2D gfx , Rectangle clip ) { // make sure the indicators are ready if ( ! _indicatorsLaidOut ) { for ( Map . Entry < SceneObject , SceneObjectIndicator > entry : _indicators . entrySet ( ) ) { SceneObjectIndicator indic = entry . getValue ( ) ; if ( ! indic . isLaidOut ( ) ) { indic . layout ( gfx , entry . getKey ( ) , _vbounds ) ; dirtyIndicator ( indic ) ; } } _indicatorsLaidOut = true ; } if ( checkShowFlag ( SHOW_TIPS ) ) { // show all the indicators for ( SceneObjectIndicator indic : _indicators . values ( ) ) { paintIndicator ( gfx , clip , indic ) ; } } else { // show maybe one indicator SceneObjectIndicator indic = _indicators . get ( _hobject ) ; if ( indic != null ) { paintIndicator ( gfx , clip , indic ) ; } } }
Paint all the appropriate indicators for our scene objects .
221
11
138,625
protected void paintIndicator ( Graphics2D gfx , Rectangle clip , SceneObjectIndicator tip ) { if ( clip . intersects ( tip . getBounds ( ) ) ) { tip . paint ( gfx ) ; } }
Paint the specified indicator if it intersects the clipping rectangle .
50
13
138,626
protected void paintTiles ( Graphics2D gfx , Rectangle clip ) { // go through rendering our tiles _paintOp . setGraphics ( gfx ) ; _applicator . applyToTiles ( clip , _paintOp ) ; _paintOp . setGraphics ( null ) ; }
Renders the base and fringe layer tiles that intersect the specified clipping rectangle .
65
15
138,627
protected void fillTile ( Graphics2D gfx , int tx , int ty , Color color ) { Composite ocomp = gfx . getComposite ( ) ; gfx . setComposite ( ALPHA_FILL_TILE ) ; Polygon poly = MisoUtil . getTilePolygon ( _metrics , tx , ty ) ; gfx . setColor ( color ) ; gfx . fill ( poly ) ; gfx . setComposite ( ocomp ) ; }
Fills the specified tile with the given color at 50% alpha . Intended for debug - only tile highlighting purposes .
106
24
138,628
protected BaseTile getBaseTile ( int tx , int ty ) { SceneBlock block = getBlock ( tx , ty ) ; return ( block == null ) ? null : block . getBaseTile ( tx , ty ) ; }
Returns the base tile for the specified tile coordinate .
47
10
138,629
protected BaseTile getFringeTile ( int tx , int ty ) { SceneBlock block = getBlock ( tx , ty ) ; return ( block == null ) ? null : block . getFringeTile ( tx , ty ) ; }
Returns the fringe tile for the specified tile coordinate .
49
10
138,630
protected void notifyListeners ( int event ) { int size = _listeners . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { _listeners . get ( ii ) . modelChanged ( event ) ; } }
Notifies all model listeners that the builder model has changed .
53
12
138,631
public List < Integer > getComponents ( ComponentClass cclass ) { List < Integer > list = _components . get ( cclass ) ; if ( list == null ) { list = Lists . newArrayList ( ) ; } return list ; }
Returns the list of components available in the specified class .
53
11
138,632
public int [ ] getSelectedComponents ( ) { int [ ] values = new int [ _selected . size ( ) ] ; Iterator < Integer > iter = _selected . values ( ) . iterator ( ) ; for ( int ii = 0 ; iter . hasNext ( ) ; ii ++ ) { values [ ii ] = iter . next ( ) . intValue ( ) ; } return values ; }
Returns the selected components in an array .
85
8
138,633
public void setSelectedComponent ( ComponentClass cclass , int cid ) { _selected . put ( cclass , Integer . valueOf ( cid ) ) ; notifyListeners ( BuilderModelListener . COMPONENT_CHANGED ) ; }
Sets the selected component for the given component class .
53
11
138,634
protected void gatherComponentInfo ( ComponentRepository crepo ) { // get the list of all component classes Iterators . addAll ( _classes , crepo . enumerateComponentClasses ( ) ) ; for ( int ii = 0 ; ii < _classes . size ( ) ; ii ++ ) { // get the list of components available for this class ComponentClass cclass = _classes . get ( ii ) ; Iterator < Integer > iter = crepo . enumerateComponentIds ( cclass ) ; while ( iter . hasNext ( ) ) { Integer cid = iter . next ( ) ; ArrayList < Integer > clist = _components . get ( cclass ) ; if ( clist == null ) { _components . put ( cclass , clist = Lists . newArrayList ( ) ) ; } clist . add ( cid ) ; } } }
Gathers component class and component information from the character manager for later reference by others .
185
18
138,635
public static long getOldestLastModified ( File dir ) { long oldest = dir . lastModified ( ) ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { oldest = Math . min ( oldest , getOldestLastModified ( file ) ) ; } else { oldest = Math . min ( oldest , file . lastModified ( ) ) ; } } } return oldest ; }
Returns the timestamp of the oldest modification date of any file within the directory .
108
15
138,636
public Set < Integer > intKeySet ( ) { return data . keySet ( ) . stream ( ) . map ( Any2 :: getLeft ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . collect ( Collectors . toSet ( ) ) ; }
The numeric set of keys held by the resolver map .
68
12
138,637
public Set < String > stringKeySet ( ) { return data . keySet ( ) . stream ( ) . map ( Any2 :: getRight ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . collect ( Collectors . toSet ( ) ) ; }
The string set of keys held by the resolver map .
68
12
138,638
public Map < Any2 < Integer , String > , Any3 < Boolean , Integer , String > > getRawMap ( ) { return unmodifiableMap ( data ) ; }
Get the underlying map of data .
37
7
138,639
public Map < Any2 < Integer , String > , String > getStringMap ( ) { return data . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( Map . Entry :: getKey , entry -> entry . getValue ( ) . mapCombine ( Object :: toString , Object :: toString , Object :: toString ) ) ) ; }
Get the underlying map but with all values converted to string .
78
12
138,640
protected void generateSprite ( ) { int components [ ] = _model . getSelectedComponents ( ) ; CharacterDescriptor desc = new CharacterDescriptor ( components , null ) ; CharacterSprite sprite = _charmgr . getCharacter ( desc ) ; setSprite ( sprite ) ; }
Generates a new character sprite for display to reflect the currently selected character components .
65
16
138,641
protected void setSprite ( CharacterSprite sprite ) { sprite . setActionSequence ( StandardActions . STANDING ) ; sprite . setOrientation ( WEST ) ; _sprite = sprite ; centerSprite ( ) ; repaint ( ) ; }
Sets the sprite to be displayed .
56
8
138,642
protected void centerSprite ( ) { if ( _sprite != null ) { Dimension d = getSize ( ) ; int shei = _sprite . getHeight ( ) ; int x = d . width / 2 , y = ( d . height + shei ) / 2 ; _sprite . setLocation ( x , y ) ; } }
Sets the sprite s location to render it centered within the panel .
74
14
138,643
public SimpleMisoSceneModel parseScene ( InputStream in ) throws IOException , SAXException { _model = null ; _digester . push ( this ) ; _digester . parse ( in ) ; return _model ; }
Parses the XML file on the supplied input stream into a scene model instance .
49
17
138,644
public void setGain ( float gain ) { _gain = gain ; if ( _fadeMode == FadeMode . NONE ) { _source . setGain ( _gain ) ; } }
Sets the base gain of the stream .
43
9
138,645
public void play ( ) { if ( _state == AL10 . AL_PLAYING ) { log . warning ( "Tried to play stream already playing." ) ; return ; } if ( _state == AL10 . AL_INITIAL ) { _qidx = _qlen = 0 ; queueBuffers ( _buffers . length ) ; } _source . play ( ) ; _state = AL10 . AL_PLAYING ; }
Starts playing this stream .
95
6
138,646
public void pause ( ) { if ( _state != AL10 . AL_PLAYING ) { log . warning ( "Tried to pause stream that wasn't playing." ) ; return ; } _source . pause ( ) ; _state = AL10 . AL_PAUSED ; }
Pauses this stream .
60
5
138,647
public void stop ( ) { if ( _state == AL10 . AL_STOPPED ) { log . warning ( "Tried to stop stream that was already stopped." ) ; return ; } _source . stop ( ) ; _state = AL10 . AL_STOPPED ; }
Stops this stream .
63
5
138,648
public void fadeIn ( float interval ) { if ( _state != AL10 . AL_PLAYING ) { play ( ) ; } _source . setGain ( 0f ) ; _fadeMode = FadeMode . IN ; _fadeInterval = interval ; _fadeElapsed = 0f ; }
Fades this stream in over the specified interval . If the stream isn t playing it will be started .
68
21
138,649
public void fadeOut ( float interval , boolean dispose ) { _fadeMode = dispose ? FadeMode . OUT_DISPOSE : FadeMode . OUT ; _fadeInterval = interval ; _fadeElapsed = 0f ; }
Fades this stream out over the specified interval .
52
10
138,650
public void dispose ( ) { // make sure the stream is stopped if ( _state != AL10 . AL_STOPPED ) { stop ( ) ; } // delete the source and buffers _source . delete ( ) ; for ( Buffer buffer : _buffers ) { buffer . delete ( ) ; } // remove from manager _soundmgr . removeStream ( this ) ; }
Releases the resources held by this stream and removes it from the manager .
80
15
138,651
protected void updateFade ( float time ) { if ( _fadeMode == FadeMode . NONE ) { return ; } float alpha = Math . min ( ( _fadeElapsed += time ) / _fadeInterval , 1f ) ; _source . setGain ( _gain * ( _fadeMode == FadeMode . IN ? alpha : ( 1f - alpha ) ) ) ; if ( alpha == 1f ) { if ( _fadeMode == FadeMode . OUT ) { stop ( ) ; } else if ( _fadeMode == FadeMode . OUT_DISPOSE ) { dispose ( ) ; } _fadeMode = FadeMode . NONE ; } }
Updates the gain of the stream according to the fade state .
152
13
138,652
protected boolean populateBuffer ( Buffer buffer ) { if ( _abuf == null ) { _abuf = ByteBuffer . allocateDirect ( getBufferSize ( ) ) . order ( ByteOrder . nativeOrder ( ) ) ; } _abuf . clear ( ) ; int read = 0 ; try { read = Math . max ( populateBuffer ( _abuf ) , 0 ) ; } catch ( IOException e ) { log . warning ( "Error reading audio stream [error=" + e + "]." ) ; } if ( read <= 0 ) { return false ; } _abuf . rewind ( ) . limit ( read ) ; buffer . setData ( getFormat ( ) , _abuf , getFrequency ( ) ) ; return true ; }
Populates the identified buffer with as much data as it can hold .
157
14
138,653
private Map < MetricName , MetricValue > get_metrics_ ( DateTime now , Context ctx ) { final Consumer < Alert > alert_manager = ctx . getAlertManager ( ) ; final long failed_collections = registry_ . getFailedCollections ( ) ; final boolean has_config = registry_ . hasConfig ( ) ; final Optional < Duration > scrape_duration = registry_ . getScrapeDuration ( ) ; final Optional < Duration > rule_eval_duration = registry_ . getRuleEvalDuration ( ) ; final Optional < Duration > processor_duration = registry_ . getProcessorDuration ( ) ; first_scrape_ts_ . compareAndSet ( null , now ) ; // First time, register the timestamp. final Duration uptime = new Duration ( first_scrape_ts_ . get ( ) , now ) ; final Optional < DateTime > last_scrape = last_scrape_ ; last_scrape_ = Optional . of ( now ) ; final long metric_count = ctx . getTSData ( ) . getCurrentCollection ( ) . getTSValues ( ) . stream ( ) . map ( TimeSeriesValue :: getMetrics ) . collect ( Collectors . summingLong ( Map :: size ) ) ; alert_manager . accept ( new Alert ( now , MONITOR_FAIL_ALERT , ( ) -> "builtin rule" , Optional . of ( failed_collections != 0 ) , MON_ALERT_DURATION , "builtin rule: some collectors failed" , EMPTY_MAP ) ) ; alert_manager . accept ( new Alert ( now , HAS_CONFIG_ALERT , ( ) -> "builtin rule" , Optional . of ( ! has_config ) , Duration . ZERO , "builtin rule: monitor has no configuration file" , EMPTY_MAP ) ) ; Map < MetricName , MetricValue > result = new HashMap <> ( ) ; result . put ( FAILED_COLLECTIONS_METRIC , MetricValue . fromIntValue ( failed_collections ) ) ; result . put ( GROUP_COUNT_METRIC , MetricValue . fromIntValue ( ctx . getTSData ( ) . getCurrentCollection ( ) . getGroups ( x -> true ) . size ( ) ) ) ; result . put ( METRIC_COUNT_METRIC , MetricValue . fromIntValue ( metric_count ) ) ; result . put ( CONFIG_PRESENT_METRIC , MetricValue . fromBoolean ( has_config ) ) ; result . put ( SCRAPE_DURATION , opt_duration_to_metricvalue_ ( scrape_duration ) ) ; result . put ( RULE_EVAL_DURATION , opt_duration_to_metricvalue_ ( rule_eval_duration ) ) ; result . put ( PROCESSOR_DURATION , opt_duration_to_metricvalue_ ( processor_duration ) ) ; result . put ( UPTIME_DURATION , duration_to_metricvalue_ ( uptime ) ) ; result . put ( SCRAPE_COUNT , MetricValue . fromIntValue ( ++ scrape_count_ ) ) ; result . put ( SCRAPE_INTERVAL , opt_duration_to_metricvalue_ ( last_scrape . map ( prev -> new Duration ( prev , now ) ) ) ) ; result . put ( SCRAPE_TS , MetricValue . fromIntValue ( now . getMillis ( ) ) ) ; return result ; }
Get metrics for the monitor .
772
6
138,654
@ Override public void transform ( Context < MutableTimeSeriesCollectionPair > ctx ) { DateTime now = ctx . getTSData ( ) . getCurrentCollection ( ) . getTimestamp ( ) ; ctx . getTSData ( ) . getCurrentCollection ( ) . addMetrics ( MONITOR_GROUP , get_metrics_ ( now , ctx ) ) ; ctx . getAlertManager ( ) . accept ( new Alert ( now , MONITOR_DOWN_ALERT , ( ) -> "builtin rule" , Optional . of ( false ) , Duration . ZERO , "builtin rule: monitor is not running for some time" , EMPTY_MAP ) ) ; }
Emit an alert monitor . down which is in the OK state .
152
14
138,655
private static MetricValue opt_duration_to_metricvalue_ ( Optional < Duration > duration ) { return duration . map ( MonitorMonitor :: duration_to_metricvalue_ ) . orElse ( MetricValue . EMPTY ) ; }
Convert an optional duration to a metric value .
53
10
138,656
private void validate ( ) { try { DateTime ts ; ts = current . getTimestamp ( ) ; for ( TimeSeriesCollection b : backward ) { if ( b . getTimestamp ( ) . isAfter ( ts ) ) throw new IllegalArgumentException ( "backwards collection must be before current and be ordered in reverse chronological order" ) ; ts = b . getTimestamp ( ) ; } ts = current . getTimestamp ( ) ; for ( TimeSeriesCollection f : forward ) { if ( f . getTimestamp ( ) . isBefore ( ts ) ) throw new IllegalArgumentException ( "forwards collection must be after current and be ordered in chronological order" ) ; ts = f . getTimestamp ( ) ; } } catch ( IllegalArgumentException ex ) { LOG . log ( Level . SEVERE , "programmer error in creating interpolated TimeSeriesCollection" , ex ) ; final List < DateTime > backward_ts = backward . stream ( ) . map ( TimeSeriesCollection :: getTimestamp ) . collect ( Collectors . toList ( ) ) ; final List < DateTime > forward_ts = forward . stream ( ) . map ( TimeSeriesCollection :: getTimestamp ) . collect ( Collectors . toList ( ) ) ; LOG . log ( Level . INFO , "current = {0}, backward = {1}, forward = {2}" , new Object [ ] { current . getTimestamp ( ) , backward_ts , forward_ts } ) ; throw ex ; } }
Check the forward and backward invariants .
320
8
138,657
private static Set < GroupName > calculateNames ( TimeSeriesCollection current , Collection < TimeSeriesCollection > backward , Collection < TimeSeriesCollection > forward ) { final Set < GroupName > names = backward . stream ( ) . flatMap ( tsc -> tsc . getGroups ( x -> true ) . stream ( ) ) . collect ( Collectors . toCollection ( THashSet :: new ) ) ; names . retainAll ( forward . stream ( ) . flatMap ( tsc -> tsc . getGroups ( x -> true ) . stream ( ) ) . collect ( Collectors . toSet ( ) ) ) ; names . removeAll ( current . getGroups ( x -> true ) ) ; return names ; }
Calculate all names that can be interpolated . The returned set will not have any names present in the current collection .
152
25
138,658
private TimeSeriesValue interpolateTSV ( GroupName name ) { final Map . Entry < DateTime , TimeSeriesValue > backTSV = findName ( backward , name ) , forwTSV = findName ( forward , name ) ; final long backMillis = max ( new Duration ( backTSV . getKey ( ) , getTimestamp ( ) ) . getMillis ( ) , 0 ) , forwMillis = max ( new Duration ( getTimestamp ( ) , forwTSV . getKey ( ) ) . getMillis ( ) , 0 ) ; final double totalMillis = forwMillis + backMillis ; final double backWeight = forwMillis / totalMillis ; final double forwWeight = backMillis / totalMillis ; return new InterpolatedTSV ( name , backTSV . getValue ( ) . getMetrics ( ) , forwTSV . getValue ( ) . getMetrics ( ) , backWeight , forwWeight ) ; }
Interpolates a group name based on the most recent backward and oldest forward occurence .
216
19
138,659
private static Map . Entry < DateTime , TimeSeriesValue > findName ( List < TimeSeriesCollection > c , GroupName name ) { ListIterator < TimeSeriesCollection > iter = c . listIterator ( ) ; while ( iter . hasNext ( ) ) { final int idx = iter . nextIndex ( ) ; final TimeSeriesCollection tsdata = iter . next ( ) ; final Optional < TimeSeriesValue > found = tsdata . get ( name ) ; if ( found . isPresent ( ) ) return SimpleMapEntry . create ( tsdata . getTimestamp ( ) , found . get ( ) ) ; } throw new IllegalStateException ( "name not present in list of time series collections" ) ; }
Finds the first resolution of name in the given TimeSeriesCollections . The cache is used and updated to skip the linear search phase .
150
28
138,660
protected void createBackBuffer ( GraphicsConfiguration gc ) { // if we have an old image, clear it out if ( _backimg != null ) { _backimg . flush ( ) ; _bgfx . dispose ( ) ; } // create the offscreen buffer int width = _window . getWidth ( ) , height = _window . getHeight ( ) ; _backimg = gc . createCompatibleVolatileImage ( width , height ) ; // fill the back buffer with white _bgfx = ( Graphics2D ) _backimg . getGraphics ( ) ; _bgfx . fillRect ( 0 , 0 , width , height ) ; // clear out our frame graphics in case that became invalid for // the same reasons our back buffer became invalid if ( _fgfx != null ) { _fgfx . dispose ( ) ; _fgfx = null ; } // Log.info("Created back buffer [" + width + "x" + height + "]."); }
Creates the off - screen buffer used to perform double buffered rendering of the animated panel .
203
19
138,661
public static void trimTileSet ( TileSet source , OutputStream destImage , TrimMetricsReceiver tmr ) throws IOException { trimTileSet ( source , destImage , tmr , FastImageIO . FILE_SUFFIX ) ; }
Convenience function to trim the tile set using FastImageIO to save the result .
53
18
138,662
public static void setRegisterWithVM ( final boolean registerWithVM ) { if ( Converters . registerWithVM != registerWithVM ) { Converters . registerWithVM = registerWithVM ; // register all converters with the VM if ( registerWithVM ) { for ( Entry < Class , Converter > entry : REGISTRY . entrySet ( ) ) { Class type = entry . getKey ( ) ; Converter converter = entry . getValue ( ) ; PropertyEditorManager . registerEditor ( type , converter . getClass ( ) ) ; } } } }
Sets if converters registered with the VM PropertyEditorManager . If the new value is true all currently registered converters are immediately registered with the VM .
118
31
138,663
private static PropertyEditor findEditor ( final Type type ) { assert type != null ; Class clazz = toClass ( type ) ; // try to locate this directly from the editor manager first. PropertyEditor editor = PropertyEditorManager . findEditor ( clazz ) ; // we're outta here if we got one. if ( editor != null ) { return editor ; } // it's possible this was a request for an array class. We might not // recognize the array type directly, but the component type might be // resolvable if ( clazz . isArray ( ) && ! clazz . getComponentType ( ) . isArray ( ) ) { // do a recursive lookup on the base type editor = findEditor ( clazz . getComponentType ( ) ) ; // if we found a suitable editor for the base component type, // wrapper this in an array adaptor for real use if ( editor != null ) { return new ArrayConverter ( clazz , editor ) ; } } // nothing found return null ; }
Locate a property editor for given class of object .
212
11
138,664
public static int [ ] quantizeImage ( int pixels [ ] [ ] , int max_colors ) { Cube cube = new Cube ( pixels , max_colors ) ; cube . classification ( ) ; cube . reduction ( ) ; cube . assignment ( ) ; return cube . colormap ; }
Reduce the image to the given number of colors .
63
11
138,665
public void paint ( Graphics2D gfx , int layer , Shape clip ) { for ( int ii = 0 , nn = _media . size ( ) ; ii < nn ; ii ++ ) { AbstractMedia media = _media . get ( ii ) ; int order = media . getRenderOrder ( ) ; try { if ( ( ( layer == ALL ) || ( layer == FRONT && order >= 0 ) || ( layer == BACK && order < 0 ) ) && clip . intersects ( media . getBounds ( ) ) ) { media . paint ( gfx ) ; } } catch ( Exception e ) { log . warning ( "Failed to render media" , "media" , media , e ) ; } } }
Renders all registered media in the given layer that intersect the supplied clipping rectangle to the given graphics context .
154
21
138,666
public void fastForward ( long timeDelta ) { if ( _tickStamp > 0 ) { log . warning ( "Egads! Asked to fastForward() during a tick." , new Exception ( ) ) ; } for ( int ii = 0 , nn = _media . size ( ) ; ii < nn ; ii ++ ) { _media . get ( ii ) . fastForward ( timeDelta ) ; } }
If the manager is paused for some length of time it should be fast forwarded by the appropriate number of milliseconds . This allows media to smoothly pick up where they left off rather than abruptly jumping into the future thinking that some outrageous amount of time passed since their last tick .
89
53
138,667
protected boolean insertMedia ( AbstractMedia media ) { if ( _media . contains ( media ) ) { log . warning ( "Attempt to insert media more than once [media=" + media + "]." , new Exception ( ) ) ; return false ; } media . init ( this ) ; int ipos = _media . insertSorted ( media , RENDER_ORDER ) ; // if we've started our tick but have not yet painted our media, we need to take care that // this newly added media will be ticked before our upcoming render if ( _tickStamp > 0L ) { if ( _tickpos == - 1 ) { // if we're done with our own call to tick(), we need to tick this new media tickMedia ( media , _tickStamp ) ; } else if ( ipos <= _tickpos ) { // otherwise, we're in the middle of our call to tick() and we only need to tick // this guy if he's being inserted before our current tick position (if he's // inserted after our current position, we'll get to him as part of this tick // iteration) _tickpos ++ ; tickMedia ( media , _tickStamp ) ; } } return true ; }
Inserts the specified media into this manager return true on success .
256
13
138,668
protected boolean removeMedia ( AbstractMedia media ) { int mpos = _media . indexOf ( media ) ; if ( mpos != - 1 ) { _media . remove ( mpos ) ; media . invalidate ( ) ; media . shutdown ( ) ; // if we're in the middle of ticking, we need to adjust the _tickpos if necessary if ( mpos <= _tickpos ) { _tickpos -- ; } return true ; } log . warning ( "Attempt to remove media that wasn't inserted [media=" + media + "]." ) ; return false ; }
Removes the specified media from this manager return true on success .
121
13
138,669
public void queueNotification ( ObserverList < Object > observers , ObserverOp < Object > event ) { _notify . add ( new Tuple < ObserverList < Object > , ObserverOp < Object > > ( observers , event ) ) ; }
Queues the notification for dispatching after we ve ticked all the media .
51
16
138,670
protected void dispatchNotifications ( ) { for ( int ii = 0 , nn = _notify . size ( ) ; ii < nn ; ii ++ ) { Tuple < ObserverList < Object > , ObserverOp < Object > > tuple = _notify . get ( ii ) ; tuple . left . apply ( tuple . right ) ; } _notify . clear ( ) ; }
Dispatches all queued media notifications .
82
9
138,671
public static < T > void addArrayIfNotNull ( JSONWriter writer , String field , Collection < T > items , JsonObjectWriter < T > objWriter ) throws JSONException { if ( items == null ) return ; addCollection ( writer , field , items , objWriter ) ; }
Adds a list .
61
4
138,672
protected void startAnimation ( Animation anim , long tickStamp ) { // account for any view scrolling that happened before this animation // was actually added to the view if ( _vdx != 0 || _vdy != 0 ) { anim . viewLocationDidChange ( _vdx , _vdy ) ; } _animmgr . registerAnimation ( anim ) ; }
Called when the time comes to start an animation . Derived classes may override this method and pass the animation on to their animation manager and do whatever else they need to do with operating animations . The default implementation simply adds them to the media panel supplied when we were constructed .
76
55
138,673
public void setScrollableArea ( int x , int y , int width , int height ) { Rectangle vb = _panel . getViewBounds ( ) ; int hmax = x + width , vmax = y + height , value ; if ( width > vb . width ) { value = MathUtil . bound ( x , _hrange . getValue ( ) , hmax - vb . width ) ; _hrange . setRangeProperties ( value , vb . width , x , hmax , false ) ; } else { // Let's center it and lock it down. int newx = x - ( vb . width - width ) / 2 ; _hrange . setRangeProperties ( newx , 0 , newx , newx , false ) ; } if ( height > vb . height ) { value = MathUtil . bound ( y , _vrange . getValue ( ) , vmax - vb . height ) ; _vrange . setRangeProperties ( value , vb . height , y , vmax , false ) ; } else { // Let's center it and lock it down. int newy = y - ( vb . height - height ) / 2 ; _vrange . setRangeProperties ( newy , 0 , newy , newy , false ) ; } }
Informs the virtual range model the extent of the area over which we can scroll .
285
17
138,674
public BufferedImage createImage ( int width , int height , int transparency ) { return _icreator . createImage ( width , height , transparency ) ; }
Creates a buffered image optimized for display on our graphics device .
34
14
138,675
public ImageKey getImageKey ( String rset , String path ) { return getImageKey ( getDataProvider ( rset ) , path ) ; }
Returns an image key that can be used to fetch the image identified by the specified resource set and image path .
32
22
138,676
public BufferedImage getImage ( ImageKey key , Colorization [ ] zations ) { CacheRecord crec = null ; synchronized ( _ccache ) { crec = _ccache . get ( key ) ; } if ( crec != null ) { // log.info("Cache hit", "key", key, "crec", crec); return crec . getImage ( zations , _ccache ) ; } // log.info("Cache miss", "key", key, "crec", crec); // load up the raw image BufferedImage image = loadImage ( key ) ; if ( image == null ) { log . warning ( "Failed to load image " + key + "." ) ; // create a blank image instead image = new BufferedImage ( 10 , 10 , BufferedImage . TYPE_BYTE_INDEXED ) ; } // log.info("Loaded Image", "path", key.path, "image", image, // "size", ImageUtil.getEstimatedMemoryUsage(image)); // create a cache record crec = new CacheRecord ( key , image ) ; synchronized ( _ccache ) { _ccache . put ( key , crec ) ; } _keySet . add ( key ) ; // periodically report our image cache performance reportCachePerformance ( ) ; return crec . getImage ( zations , _ccache ) ; }
Obtains the image identified by the specified key caching if possible . The image will be recolored using the supplied colorizations if requested .
296
27
138,677
public Mirage getMirage ( String rsrcPath ) { return getMirage ( getImageKey ( _defaultProvider , rsrcPath ) , null , null ) ; }
Creates a mirage which is an image optimized for display on our current display device and which will be stored into video memory if possible .
36
28
138,678
protected ImageDataProvider getDataProvider ( final String rset ) { if ( rset == null ) { return _defaultProvider ; } ImageDataProvider dprov = _providers . get ( rset ) ; if ( dprov == null ) { dprov = new ImageDataProvider ( ) { public BufferedImage loadImage ( String path ) throws IOException { // first attempt to load the image from the specified resource set try { return _rmgr . getImageResource ( rset , path ) ; } catch ( FileNotFoundException fnfe ) { // fall back to trying the classpath return _rmgr . getImageResource ( path ) ; } } public String getIdent ( ) { return "rmgr:" + rset ; } } ; _providers . put ( rset , dprov ) ; } return dprov ; }
Returns the data provider configured to obtain image data from the specified resource set .
176
15
138,679
protected BufferedImage loadImage ( ImageKey key ) { // if (EventQueue.isDispatchThread()) { // Log.info("Loading image on AWT thread " + key + "."); // } BufferedImage image = null ; try { log . debug ( "Loading image " + key + "." ) ; image = key . daprov . loadImage ( key . path ) ; if ( image == null ) { log . warning ( "ImageDataProvider.loadImage(" + key + ") returned null." ) ; } } catch ( Exception e ) { log . warning ( "Unable to load image '" + key + "'." , e ) ; // create a blank image in its stead image = createImage ( 1 , 1 , Transparency . OPAQUE ) ; } return image ; }
Loads and returns the image with the specified key from the supplied data provider .
171
16
138,680
public void setPosition ( float x , float y , float z ) { if ( _source != null ) { _source . setPosition ( x , y , z ) ; } _px = x ; _py = y ; _pz = z ; }
Sets the position of the sound .
54
8
138,681
public void setVelocity ( float x , float y , float z ) { if ( _source != null ) { _source . setVelocity ( x , y , z ) ; } _vx = x ; _vy = y ; _vz = z ; }
Sets the velocity of the sound .
57
8
138,682
public void setDirection ( float x , float y , float z ) { if ( _source != null ) { _source . setDirection ( x , y , z ) ; } _dx = x ; _dy = y ; _dz = z ; }
Sets the direction of the sound .
56
8
138,683
public static MediaTimer createTimer ( ) { MediaTimer timer = null ; for ( String timerClass : PERF_TIMERS ) { try { timer = ( MediaTimer ) Class . forName ( timerClass ) . newInstance ( ) ; break ; } catch ( Throwable t ) { // try the next one } } if ( timer == null ) { log . info ( "Can't use high performance timer, reverting to " + "System.currentTimeMillis() based timer." ) ; timer = new MillisTimer ( ) ; } return timer ; }
Attempts to create a high resolution timer but if that isn t possible uses a System . currentTimeMillis based timer .
119
24
138,684
public static FrameManager newInstance ( ManagedRoot root , MediaTimer timer ) { FrameManager fmgr = ( root instanceof ManagedJFrame && _useFlip . getValue ( ) ) ? new FlipFrameManager ( ) : new BackFrameManager ( ) ; fmgr . init ( root , timer ) ; return fmgr ; }
Constructs a frame manager that will do its rendering to the supplied root and use the supplied media timer for timing information .
74
24
138,685
public void registerFrameParticipant ( FrameParticipant participant ) { Object [ ] nparts = ListUtil . testAndAddRef ( _participants , participant ) ; if ( nparts == null ) { log . warning ( "Refusing to add duplicate frame participant! " + participant ) ; } else { _participants = nparts ; } }
Registers a frame participant . The participant will be given the opportunity to do processing and rendering on each frame .
73
22
138,686
public TrailingAverage [ ] getPerfMetrics ( ) { if ( _metrics == null ) { _metrics = new TrailingAverage [ ] { new TrailingAverage ( 150 ) , new TrailingAverage ( 150 ) , new TrailingAverage ( 150 ) } ; } return _metrics ; }
Returns debug performance metrics .
66
5
138,687
public static Component getRoot ( Component comp , Rectangle rect ) { for ( Component c = comp ; c != null ; c = c . getParent ( ) ) { if ( ! c . isVisible ( ) || ! c . isDisplayable ( ) ) { return null ; } if ( c instanceof Window || c instanceof Applet ) { return c ; } rect . x += c . getX ( ) ; rect . y += c . getY ( ) ; } return null ; }
Returns the root component for the supplied component or null if it is not part of a rooted hierarchy or if any parent along the way is found to be hidden or without a peer . Along the way it adjusts the supplied component - relative rectangle to be relative to the returned root component .
105
56
138,688
protected void init ( ManagedRoot root , MediaTimer timer ) { _window = root . getWindow ( ) ; _root = root ; _root . init ( this ) ; _timer = timer ; // set up our custom repaint manager _repainter = new ActiveRepaintManager ( ( _root instanceof Component ) ? ( Component ) _root : _window ) ; RepaintManager . setCurrentManager ( _repainter ) ; // turn off double buffering for the whole business because we handle repaints _repainter . setDoubleBufferingEnabled ( false ) ; }
Initializes this frame manager and prepares it for operation .
123
11
138,689
protected void tick ( long tickStamp ) { long start = 0L , paint = 0L ; if ( _perfDebug . getValue ( ) ) { start = paint = _timer . getElapsedMicros ( ) ; } // if our frame is not showing (or is impossibly sized), don't try rendering anything if ( _window . isShowing ( ) && _window . getWidth ( ) > 0 && _window . getHeight ( ) > 0 ) { // tick our participants tickParticipants ( tickStamp ) ; paint = _timer . getElapsedMicros ( ) ; // repaint our participants and components paint ( tickStamp ) ; } if ( _perfDebug . getValue ( ) ) { long end = _timer . getElapsedMicros ( ) ; getPerfMetrics ( ) [ 1 ] . record ( ( int ) ( paint - start ) / 100 ) ; getPerfMetrics ( ) [ 2 ] . record ( ( int ) ( end - paint ) / 100 ) ; } }
Called to perform the frame processing and rendering .
221
10
138,690
protected boolean paint ( Graphics2D gfx ) { // paint our frame participants (which want to be handled specially) int painted = 0 ; for ( Object participant : _participants ) { FrameParticipant part = ( FrameParticipant ) participant ; if ( part == null ) { continue ; } Component pcomp = part . getComponent ( ) ; if ( pcomp == null || ! part . needsPaint ( ) ) { continue ; } long start = 0L ; if ( HANG_DEBUG ) { start = System . currentTimeMillis ( ) ; } // get the bounds of this component pcomp . getBounds ( _tbounds ) ; // the bounds adjustment we're about to call will add in the components initial bounds // offsets, so we remove them here _tbounds . setLocation ( 0 , 0 ) ; // convert them into top-level coordinates; also note that if this component does not // have a valid or visible root, we don't want to paint it either if ( getRoot ( pcomp , _tbounds ) == null ) { continue ; } try { // render this participant; we don't set the clip because frame participants are // expected to handle clipping themselves; otherwise we might pointlessly set the // clip here, creating a few Rectangle objects in the process, only to have the // frame participant immediately set the clip to something more sensible gfx . translate ( _tbounds . x , _tbounds . y ) ; pcomp . paint ( gfx ) ; gfx . translate ( - _tbounds . x , - _tbounds . y ) ; painted ++ ; } catch ( Throwable t ) { String ptos = StringUtil . safeToString ( part ) ; log . warning ( "Frame participant choked during paint [part=" + ptos + "]." , t ) ; } // render any components in our layered pane that are not in the default layer _clipped [ 0 ] = false ; renderLayers ( gfx , pcomp , _tbounds , _clipped , _tbounds ) ; if ( HANG_DEBUG ) { long delay = ( System . currentTimeMillis ( ) - start ) ; if ( delay > HANG_GAP ) { log . warning ( "Whoa nelly! Painter took a long time" , "part" , part , "time" , delay + "ms" ) ; } } } // if we have a media overlay, give that a chance to propagate its dirty regions to the // active repaint manager for areas it dirtied during this tick if ( _overlay != null ) { _overlay . propagateDirtyRegions ( _repainter , _root . getRootPane ( ) ) ; } // repaint any widgets that have declared they need to be repainted since the last tick boolean pcomp = _repainter . paintComponents ( gfx , this ) ; // if we have a media overlay, give it a chance to paint on top of everything if ( _overlay != null ) { pcomp |= _overlay . paint ( gfx ) ; } // let the caller know if anybody painted anything return ( ( painted > 0 ) || pcomp ) ; }
Paints our frame participants and any dirty components via the repaint manager .
679
15
138,691
protected void renderLayer ( Graphics2D g , Rectangle bounds , JLayeredPane pane , boolean [ ] clipped , Integer layer ) { // stop now if there are no components in that layer int ccount = pane . getComponentCountInLayer ( layer . intValue ( ) ) ; if ( ccount == 0 ) { return ; } // render them up Component [ ] comps = pane . getComponentsInLayer ( layer . intValue ( ) ) ; for ( int ii = 0 ; ii < ccount ; ii ++ ) { Component comp = comps [ ii ] ; if ( ! comp . isVisible ( ) || comp instanceof SafeLayerComponent ) { continue ; } // if this overlay does not intersect the component we just rendered, we don't need to // repaint it Rectangle compBounds = new Rectangle ( 0 , 0 , comp . getWidth ( ) , comp . getHeight ( ) ) ; getRoot ( comp , compBounds ) ; if ( ! compBounds . intersects ( bounds ) ) { continue ; } // if the clipping region has not yet been set during this render pass, the time has // come to do so if ( ! clipped [ 0 ] ) { g . setClip ( bounds ) ; clipped [ 0 ] = true ; } // translate into the components coordinate system and render g . translate ( compBounds . x , compBounds . y ) ; try { comp . paint ( g ) ; } catch ( Exception e ) { log . warning ( "Component choked while rendering." , e ) ; } g . translate ( - compBounds . x , - compBounds . y ) ; } }
Renders all components in the specified layer of the supplied layered pane that intersect the supplied bounds .
350
19
138,692
public static < T > Iterator < T > distinct ( final Iterator < T > iterator ) { requireNonNull ( iterator ) ; return new AbstractIterator < T > ( ) { private final PeekingIterator < T > peekingIterator = peekingIterator ( iterator ) ; private T curr = null ; @ Override protected T computeNext ( ) { while ( peekingIterator . hasNext ( ) && Objects . equals ( curr , peekingIterator . peek ( ) ) ) { peekingIterator . next ( ) ; } if ( ! peekingIterator . hasNext ( ) ) return endOfData ( ) ; curr = peekingIterator . next ( ) ; return curr ; } } ; }
If we can assume the iterator is sorted return the distinct elements . This only works if the data provided is sorted .
149
23
138,693
public ActionFrames getFrames ( String action , String type ) { return _frameProvider . getFrames ( this , action , type ) ; }
Returns the image frames for the specified action animation or null if no animation for the specified action is available for this component .
29
24
138,694
public String getFramePath ( String action , String type , Set < String > existentPaths ) { return _frameProvider . getFramePath ( this , action , type , existentPaths ) ; }
Returns the path to the image frames for the specified action animation or null if no animation for the specified action is available for this component .
44
27
138,695
protected OutputStream nextEntry ( OutputStream lastEntry , String path ) throws IOException { ( ( JarOutputStream ) lastEntry ) . putNextEntry ( new JarEntry ( path ) ) ; return lastEntry ; }
Advances to the next named entry in the bundle and returns the stream to which to write that entry .
45
21
138,696
public QueryBuilder map ( String query , String method_name , Object ... items ) throws Exception { JSONObject op = new JSONObject ( ) ; if ( query != null ) op . put ( Constants . REQUEST_QUERY , query ) ; java . util . Map < String , Object > operation = new LinkedHashMap < String , Object > ( ) ; operation . put ( Constants . REQUEST_METHOD_NAME , method_name ) ; if ( query != null ) queryStringRepresentation += query ; queryStringRepresentation += "." + method_name ; operation . put ( Constants . REQUEST_ARGUMENTS , buildArgsArray ( items ) ) ; op . put ( Constants . REQUEST_OPERATION , operation ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; }
Used to get the return from a method call
223
9
138,697
public QueryBuilder instantiate ( String query , Object ... items ) throws Exception { JSONObject op = new JSONObject ( ) ; if ( query != null ) op . put ( Constants . REQUEST_INSTANTIATE , query ) ; if ( query != null ) queryStringRepresentation += query ; op . put ( Constants . REQUEST_ARGUMENTS , buildArgsArray ( items ) ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; }
Used to instantiate a class
149
6
138,698
private JSONArray buildArgsArray ( Object ... items ) throws Exception { JSONArray args = new JSONArray ( ) ; for ( int i = 0 ; i < items . length ; i ++ ) { if ( items [ i ] instanceof java . lang . String ) { args . put ( ( String ) items [ i ] ) ; } else if ( items [ i ] instanceof Number ) { args . put ( ( Number ) items [ i ] ) ; } else if ( items [ i ] instanceof java . lang . Boolean ) { args . put ( ( Boolean ) items [ i ] ) ; } else if ( items [ i ] == null ) { args . put ( ( Object ) null ) ; } else { throw new Exception ( "Invalid type" ) ; } } return args ; }
Internal function used to build a JSON Array of arguments from a list of items
166
15
138,699
private QueryBuilder genericRequest ( String type , String value ) throws Exception { JSONObject op = new JSONObject ( ) ; op . put ( type , value ) ; JSONArray operations = ( JSONArray ) request . get ( Constants . REQUEST_OPERATIONS ) ; operations . put ( op ) ; request . remove ( Constants . REQUEST_OPERATIONS ) ; request . put ( Constants . REQUEST_OPERATIONS , operations ) ; return this ; }
Creates a key value request
97
6