Sapphire Developer Guide > Services

DragAndDropService

DragAndDropService provides means to implement drag-n-drop behavior in a diagram editor.

Example

public class MapDragAndDropService extends DragAndDropService 
{
    @Override
    public boolean droppable( DropContext context ) 
    {
        return context.object() instanceof IFile;
    }

    @Override
    public void drop( DropContext context ) 
    {
        IFile file = (IFile) context.object();
        List locations = new ArrayList();

        InputStream in = null;

        try
        {
            in = file.getContents();
            final BufferedReader br = new BufferedReader( new InputStreamReader( in ) );

            for( String line = br.readLine(); line != null; line = br.readLine() )
            {
                if( line != null )
                {
                    line = line.trim();

                    if( line.length() > 0 )
                    {
                        locations.add( line );
                    }
                }
            }
        }
        catch( CoreException e )
        {
            LoggingService.log( e );
        }
        catch( IOException e )
        {
            LoggingService.log( e );
        }
        finally
        {
            if( in != null )
            {
                try
                {
                    in.close();
                }
                catch( IOException e ) {}
            }
        }

        if( ! locations.isEmpty() )
        {
            SapphireDiagramEditorPagePart diagram = context( SapphireDiagramEditorPagePart.class );
            Map map = context( Map.class );

            Point initialDropPosition = context.position();

            int x = initialDropPosition.getX();
            int y = initialDropPosition.getY();

            for( String locationName : locations )
            {
                if( ! map.hasLocation( locationName ) )
                {
                    Location location = map.getLocations().insert();
                    location.setName( locationName );

                    DiagramNodePart locationNodePart = diagram.getDiagramNodePart(location);
                    locationNodePart.setNodeBounds( x, y );

                    x += 50;
                    y += 50;
                }
            }
        }
    }
}

The DragAndDropService is typically registered as part of diagram page definition in the sdef file.

<diagram-page>
    <service>
        <implementation>MapDropService</implementation>
    </service>
</diagram-page>